Thread.cpp 45 KB

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