Thread.cpp 54 KB

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