Thread.cpp 44 KB

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