Thread.cpp 54 KB

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