Thread.cpp 53 KB

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