Thread.cpp 42 KB

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