Thread.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Demangle.h>
  27. #include <AK/StringBuilder.h>
  28. #include <AK/Time.h>
  29. #include <Kernel/Arch/i386/CPU.h>
  30. #include <Kernel/FileSystem/FileDescription.h>
  31. #include <Kernel/KSyms.h>
  32. #include <Kernel/Process.h>
  33. #include <Kernel/Profiling.h>
  34. #include <Kernel/Scheduler.h>
  35. #include <Kernel/Thread.h>
  36. #include <Kernel/ThreadTracer.h>
  37. #include <Kernel/TimerQueue.h>
  38. #include <Kernel/VM/MemoryManager.h>
  39. #include <Kernel/VM/PageDirectory.h>
  40. #include <Kernel/VM/ProcessPagingScope.h>
  41. #include <LibC/signal_numbers.h>
  42. #include <LibELF/Loader.h>
  43. //#define SIGNAL_DEBUG
  44. //#define THREAD_DEBUG
  45. namespace Kernel {
  46. Thread::Thread(NonnullRefPtr<Process> process)
  47. : m_process(move(process))
  48. , m_name(m_process->name())
  49. {
  50. if (m_process->m_thread_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed) == 0) {
  51. // First thread gets TID == PID
  52. m_tid = m_process->pid().value();
  53. } else {
  54. m_tid = Process::allocate_pid().value();
  55. }
  56. #ifdef THREAD_DEBUG
  57. dbg() << "Created new thread " << m_process->name() << "(" << m_process->pid().value() << ":" << m_tid.value() << ")";
  58. #endif
  59. set_default_signal_dispositions();
  60. m_fpu_state = (FPUState*)kmalloc_aligned<16>(sizeof(FPUState));
  61. reset_fpu_state();
  62. memset(&m_tss, 0, sizeof(m_tss));
  63. m_tss.iomapbase = sizeof(TSS32);
  64. // Only IF is set when a process boots.
  65. m_tss.eflags = 0x0202;
  66. if (m_process->is_kernel_process()) {
  67. m_tss.cs = GDT_SELECTOR_CODE0;
  68. m_tss.ds = GDT_SELECTOR_DATA0;
  69. m_tss.es = GDT_SELECTOR_DATA0;
  70. m_tss.fs = GDT_SELECTOR_PROC;
  71. m_tss.ss = GDT_SELECTOR_DATA0;
  72. m_tss.gs = 0;
  73. } else {
  74. m_tss.cs = GDT_SELECTOR_CODE3 | 3;
  75. m_tss.ds = GDT_SELECTOR_DATA3 | 3;
  76. m_tss.es = GDT_SELECTOR_DATA3 | 3;
  77. m_tss.fs = GDT_SELECTOR_DATA3 | 3;
  78. m_tss.ss = GDT_SELECTOR_DATA3 | 3;
  79. m_tss.gs = GDT_SELECTOR_TLS | 3;
  80. }
  81. m_tss.cr3 = m_process->page_directory().cr3();
  82. m_kernel_stack_region = MM.allocate_kernel_region(default_kernel_stack_size, String::format("Kernel Stack (Thread %d)", m_tid.value()), Region::Access::Read | Region::Access::Write, false, true);
  83. m_kernel_stack_region->set_stack(true);
  84. m_kernel_stack_base = m_kernel_stack_region->vaddr().get();
  85. m_kernel_stack_top = m_kernel_stack_region->vaddr().offset(default_kernel_stack_size).get() & 0xfffffff8u;
  86. if (m_process->is_kernel_process()) {
  87. m_tss.esp = m_tss.esp0 = m_kernel_stack_top;
  88. } else {
  89. // Ring 3 processes get a separate stack for ring 0.
  90. // The ring 3 stack will be assigned by exec().
  91. m_tss.ss0 = GDT_SELECTOR_DATA0;
  92. m_tss.esp0 = m_kernel_stack_top;
  93. }
  94. // We need to add another reference if we could successfully create
  95. // all the resources needed for this thread. The reason for this is that
  96. // we don't want to delete this thread after dropping the reference,
  97. // it may still be running or scheduled to be run.
  98. // The finalizer is responsible for dropping this reference once this
  99. // thread is ready to be cleaned up.
  100. ref();
  101. if (m_process->pid() != 0)
  102. Scheduler::init_thread(*this);
  103. }
  104. Thread::~Thread()
  105. {
  106. {
  107. // We need to explicitly remove ourselves from the thread list
  108. // here. We may get pre-empted in the middle of destructing this
  109. // thread, which causes problems if the thread list is iterated.
  110. // Specifically, if this is the last thread of a process, checking
  111. // block conditions would access m_process, which would be in
  112. // the middle of being destroyed.
  113. ScopedSpinLock lock(g_scheduler_lock);
  114. g_scheduler_data->thread_list_for_state(m_state).remove(*this);
  115. }
  116. }
  117. void Thread::unblock_from_blocker(Blocker& blocker)
  118. {
  119. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  120. ScopedSpinLock lock(m_lock);
  121. if (m_blocker != &blocker)
  122. return;
  123. if (!is_stopped())
  124. unblock();
  125. }
  126. void Thread::unblock(u8 signal)
  127. {
  128. ASSERT(g_scheduler_lock.own_lock());
  129. ASSERT(m_lock.own_lock());
  130. if (m_state != Thread::Blocked)
  131. return;
  132. ASSERT(m_blocker);
  133. if (signal != 0)
  134. m_blocker->set_interrupted_by_signal(signal);
  135. m_blocker = nullptr;
  136. if (Thread::current() == this) {
  137. set_state(Thread::Running);
  138. return;
  139. }
  140. ASSERT(m_state != Thread::Runnable && m_state != Thread::Running);
  141. set_state(Thread::Runnable);
  142. }
  143. void Thread::set_should_die()
  144. {
  145. if (m_should_die) {
  146. #ifdef THREAD_DEBUG
  147. dbg() << *this << " Should already die";
  148. #endif
  149. return;
  150. }
  151. ScopedCritical critical;
  152. // Remember that we should die instead of returning to
  153. // the userspace.
  154. {
  155. ScopedSpinLock lock(g_scheduler_lock);
  156. m_should_die = true;
  157. // NOTE: Even the current thread can technically be in "Stopped"
  158. // state! This is the case when another thread sent a SIGSTOP to
  159. // it while it was running and it calls e.g. exit() before
  160. // the scheduler gets involved again.
  161. if (is_stopped()) {
  162. // If we were stopped, we need to briefly resume so that
  163. // the kernel stacks can clean up. We won't ever return back
  164. // to user mode, though
  165. resume_from_stopped();
  166. } else if (state() == Queued) {
  167. // m_queue can only be accessed safely if g_scheduler_lock is held!
  168. if (m_queue) {
  169. m_queue->dequeue(*this);
  170. m_queue = nullptr;
  171. // Wake the thread
  172. wake_from_queue();
  173. }
  174. }
  175. }
  176. if (is_blocked()) {
  177. ScopedSpinLock lock(m_lock);
  178. ASSERT(m_blocker != nullptr);
  179. // We're blocked in the kernel.
  180. m_blocker->set_interrupted_by_death();
  181. unblock();
  182. }
  183. }
  184. void Thread::die_if_needed()
  185. {
  186. ASSERT(Thread::current() == this);
  187. if (!m_should_die)
  188. return;
  189. unlock_process_if_locked();
  190. ScopedCritical critical;
  191. set_should_die();
  192. // Flag a context switch. Because we're in a critical section,
  193. // Scheduler::yield will actually only mark a pending scontext switch
  194. // Simply leaving the critical section would not necessarily trigger
  195. // a switch.
  196. Scheduler::yield();
  197. // Now leave the critical section so that we can also trigger the
  198. // actual context switch
  199. u32 prev_flags;
  200. Processor::current().clear_critical(prev_flags, false);
  201. dbg() << "die_if_needed returned form clear_critical!!! in irq: " << Processor::current().in_irq();
  202. // We should never get here, but the scoped scheduler lock
  203. // will be released by Scheduler::context_switch again
  204. ASSERT_NOT_REACHED();
  205. }
  206. void Thread::exit(void* exit_value)
  207. {
  208. ASSERT(Thread::current() == this);
  209. m_join_condition.thread_did_exit(exit_value);
  210. set_should_die();
  211. unlock_process_if_locked();
  212. die_if_needed();
  213. }
  214. void Thread::yield_without_holding_big_lock()
  215. {
  216. ASSERT(!g_scheduler_lock.own_lock());
  217. bool did_unlock = unlock_process_if_locked();
  218. // NOTE: Even though we call Scheduler::yield here, unless we happen
  219. // to be outside of a critical section, the yield will be postponed
  220. // until leaving it in relock_process.
  221. Scheduler::yield();
  222. relock_process(did_unlock);
  223. }
  224. bool Thread::unlock_process_if_locked()
  225. {
  226. return process().big_lock().force_unlock_if_locked();
  227. }
  228. void Thread::relock_process(bool did_unlock)
  229. {
  230. // Clearing the critical section may trigger the context switch
  231. // flagged by calling Scheduler::donate_to or Scheduler::yield
  232. // above. We have to do it this way because we intentionally
  233. // leave the critical section here to be able to switch contexts.
  234. u32 prev_flags;
  235. u32 prev_crit = Processor::current().clear_critical(prev_flags, true);
  236. if (did_unlock) {
  237. // We've unblocked, relock the process if needed and carry on.
  238. process().big_lock().lock();
  239. }
  240. // NOTE: We may be on a different CPU now!
  241. Processor::current().restore_critical(prev_crit, prev_flags);
  242. }
  243. auto Thread::sleep(const timespec& duration, timespec* remaining_time) -> BlockResult
  244. {
  245. ASSERT(state() == Thread::Running);
  246. return Thread::current()->block<Thread::SleepBlocker>(nullptr, Thread::BlockTimeout(false, &duration), remaining_time);
  247. }
  248. auto Thread::sleep_until(const timespec& deadline) -> BlockResult
  249. {
  250. ASSERT(state() == Thread::Running);
  251. return Thread::current()->block<Thread::SleepBlocker>(nullptr, Thread::BlockTimeout(true, &deadline));
  252. }
  253. const char* Thread::state_string() const
  254. {
  255. switch (state()) {
  256. case Thread::Invalid:
  257. return "Invalid";
  258. case Thread::Runnable:
  259. return "Runnable";
  260. case Thread::Running:
  261. return "Running";
  262. case Thread::Dying:
  263. return "Dying";
  264. case Thread::Dead:
  265. return "Dead";
  266. case Thread::Stopped:
  267. return "Stopped";
  268. case Thread::Queued:
  269. return "Queued";
  270. case Thread::Blocked: {
  271. ScopedSpinLock lock(m_lock);
  272. ASSERT(m_blocker != nullptr);
  273. return m_blocker->state_string();
  274. }
  275. }
  276. klog() << "Thread::state_string(): Invalid state: " << state();
  277. ASSERT_NOT_REACHED();
  278. return nullptr;
  279. }
  280. void Thread::finalize()
  281. {
  282. ASSERT(Thread::current() == g_finalizer);
  283. ASSERT(Thread::current() != this);
  284. #ifdef LOCK_DEBUG
  285. ASSERT(!m_lock.own_lock());
  286. if (lock_count() > 0) {
  287. dbg() << "Thread " << *this << " leaking " << lock_count() << " Locks!";
  288. ScopedSpinLock list_lock(m_holding_locks_lock);
  289. for (auto& info : m_holding_locks_list)
  290. dbg() << " - " << info.lock->name() << " @ " << info.lock << " locked at " << info.file << ":" << info.line << " count: " << info.count;
  291. ASSERT_NOT_REACHED();
  292. }
  293. #endif
  294. {
  295. ScopedSpinLock lock(g_scheduler_lock);
  296. #ifdef THREAD_DEBUG
  297. dbg() << "Finalizing thread " << *this;
  298. #endif
  299. set_state(Thread::State::Dead);
  300. m_join_condition.thread_finalizing();
  301. }
  302. if (m_dump_backtrace_on_finalization)
  303. dbg() << backtrace_impl();
  304. kfree_aligned(m_fpu_state);
  305. auto thread_cnt_before = m_process->m_thread_count.fetch_sub(1, AK::MemoryOrder::memory_order_acq_rel);
  306. ASSERT(thread_cnt_before != 0);
  307. if (thread_cnt_before == 1)
  308. process().finalize(*this);
  309. else
  310. process().unblock_waiters(*this, Thread::WaitBlocker::UnblockFlags::Terminated);
  311. }
  312. void Thread::finalize_dying_threads()
  313. {
  314. ASSERT(Thread::current() == g_finalizer);
  315. Vector<Thread*, 32> dying_threads;
  316. {
  317. ScopedSpinLock lock(g_scheduler_lock);
  318. for_each_in_state(Thread::State::Dying, [&](Thread& thread) {
  319. if (thread.is_finalizable())
  320. dying_threads.append(&thread);
  321. return IterationDecision::Continue;
  322. });
  323. }
  324. for (auto* thread : dying_threads) {
  325. thread->finalize();
  326. // This thread will never execute again, drop the running reference
  327. // NOTE: This may not necessarily drop the last reference if anything
  328. // else is still holding onto this thread!
  329. thread->unref();
  330. }
  331. }
  332. bool Thread::tick()
  333. {
  334. ++m_ticks;
  335. if (tss().cs & 3)
  336. ++m_process->m_ticks_in_user;
  337. else
  338. ++m_process->m_ticks_in_kernel;
  339. return --m_ticks_left;
  340. }
  341. bool Thread::has_pending_signal(u8 signal) const
  342. {
  343. ScopedSpinLock lock(g_scheduler_lock);
  344. return pending_signals_for_state() & (1 << (signal - 1));
  345. }
  346. u32 Thread::pending_signals() const
  347. {
  348. ScopedSpinLock lock(g_scheduler_lock);
  349. return pending_signals_for_state();
  350. }
  351. u32 Thread::pending_signals_for_state() const
  352. {
  353. ASSERT(g_scheduler_lock.own_lock());
  354. constexpr u32 stopped_signal_mask = (1 << (SIGCONT - 1)) | (1 << (SIGKILL - 1)) | (1 << (SIGTRAP - 1));
  355. return m_state != Stopped ? m_pending_signals : m_pending_signals & stopped_signal_mask;
  356. }
  357. void Thread::send_signal(u8 signal, [[maybe_unused]] Process* sender)
  358. {
  359. ASSERT(signal < 32);
  360. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  361. // FIXME: Figure out what to do for masked signals. Should we also ignore them here?
  362. if (should_ignore_signal(signal)) {
  363. #ifdef SIGNAL_DEBUG
  364. dbg() << "Signal " << signal << " was ignored by " << process();
  365. #endif
  366. return;
  367. }
  368. #ifdef SIGNAL_DEBUG
  369. if (sender)
  370. dbg() << "Signal: " << *sender << " sent " << signal << " to " << process();
  371. else
  372. dbg() << "Signal: Kernel sent " << signal << " to " << process();
  373. #endif
  374. m_pending_signals |= 1 << (signal - 1);
  375. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  376. ScopedSpinLock lock(m_lock);
  377. if (m_state == Stopped) {
  378. if (pending_signals_for_state())
  379. resume_from_stopped();
  380. } else {
  381. unblock(signal);
  382. }
  383. }
  384. u32 Thread::update_signal_mask(u32 signal_mask)
  385. {
  386. ScopedSpinLock lock(g_scheduler_lock);
  387. auto previous_signal_mask = m_signal_mask;
  388. m_signal_mask = signal_mask;
  389. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  390. return previous_signal_mask;
  391. }
  392. u32 Thread::signal_mask() const
  393. {
  394. ScopedSpinLock lock(g_scheduler_lock);
  395. return m_signal_mask;
  396. }
  397. u32 Thread::signal_mask_block(sigset_t signal_set, bool block)
  398. {
  399. ScopedSpinLock lock(g_scheduler_lock);
  400. auto previous_signal_mask = m_signal_mask;
  401. if (block)
  402. m_signal_mask &= ~signal_set;
  403. else
  404. m_signal_mask |= signal_set;
  405. m_have_any_unmasked_pending_signals.store(pending_signals_for_state() & ~m_signal_mask, AK::memory_order_release);
  406. return previous_signal_mask;
  407. }
  408. void Thread::clear_signals()
  409. {
  410. ScopedSpinLock lock(g_scheduler_lock);
  411. m_signal_mask = 0;
  412. m_pending_signals = 0;
  413. m_have_any_unmasked_pending_signals.store(false, AK::memory_order_release);
  414. }
  415. // Certain exceptions, such as SIGSEGV and SIGILL, put a
  416. // thread into a state where the signal handler must be
  417. // invoked immediately, otherwise it will continue to fault.
  418. // This function should be used in an exception handler to
  419. // ensure that when the thread resumes, it's executing in
  420. // the appropriate signal handler.
  421. void Thread::send_urgent_signal_to_self(u8 signal)
  422. {
  423. ASSERT(Thread::current() == this);
  424. DispatchSignalResult result;
  425. {
  426. ScopedSpinLock lock(g_scheduler_lock);
  427. result = dispatch_signal(signal);
  428. }
  429. if (result == DispatchSignalResult::Yield)
  430. yield_without_holding_big_lock();
  431. }
  432. DispatchSignalResult Thread::dispatch_one_pending_signal()
  433. {
  434. ASSERT(m_lock.own_lock());
  435. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  436. if (signal_candidates == 0)
  437. return DispatchSignalResult::Continue;
  438. u8 signal = 1;
  439. for (; signal < 32; ++signal) {
  440. if (signal_candidates & (1 << (signal - 1))) {
  441. break;
  442. }
  443. }
  444. return dispatch_signal(signal);
  445. }
  446. DispatchSignalResult Thread::try_dispatch_one_pending_signal(u8 signal)
  447. {
  448. ASSERT(signal != 0);
  449. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  450. ScopedSpinLock lock(m_lock);
  451. u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask;
  452. if (!(signal_candidates & (1 << (signal - 1))))
  453. return DispatchSignalResult::Continue;
  454. return dispatch_signal(signal);
  455. }
  456. enum class DefaultSignalAction {
  457. Terminate,
  458. Ignore,
  459. DumpCore,
  460. Stop,
  461. Continue,
  462. };
  463. static DefaultSignalAction default_signal_action(u8 signal)
  464. {
  465. ASSERT(signal && signal < NSIG);
  466. switch (signal) {
  467. case SIGHUP:
  468. case SIGINT:
  469. case SIGKILL:
  470. case SIGPIPE:
  471. case SIGALRM:
  472. case SIGUSR1:
  473. case SIGUSR2:
  474. case SIGVTALRM:
  475. case SIGSTKFLT:
  476. case SIGIO:
  477. case SIGPROF:
  478. case SIGTERM:
  479. return DefaultSignalAction::Terminate;
  480. case SIGCHLD:
  481. case SIGURG:
  482. case SIGWINCH:
  483. case SIGINFO:
  484. return DefaultSignalAction::Ignore;
  485. case SIGQUIT:
  486. case SIGILL:
  487. case SIGTRAP:
  488. case SIGABRT:
  489. case SIGBUS:
  490. case SIGFPE:
  491. case SIGSEGV:
  492. case SIGXCPU:
  493. case SIGXFSZ:
  494. case SIGSYS:
  495. return DefaultSignalAction::DumpCore;
  496. case SIGCONT:
  497. return DefaultSignalAction::Continue;
  498. case SIGSTOP:
  499. case SIGTSTP:
  500. case SIGTTIN:
  501. case SIGTTOU:
  502. return DefaultSignalAction::Stop;
  503. }
  504. ASSERT_NOT_REACHED();
  505. }
  506. bool Thread::should_ignore_signal(u8 signal) const
  507. {
  508. ASSERT(signal < 32);
  509. auto& action = m_signal_action_data[signal];
  510. if (action.handler_or_sigaction.is_null())
  511. return default_signal_action(signal) == DefaultSignalAction::Ignore;
  512. if (action.handler_or_sigaction.as_ptr() == SIG_IGN)
  513. return true;
  514. return false;
  515. }
  516. bool Thread::has_signal_handler(u8 signal) const
  517. {
  518. ASSERT(signal < 32);
  519. auto& action = m_signal_action_data[signal];
  520. return !action.handler_or_sigaction.is_null();
  521. }
  522. static bool push_value_on_user_stack(u32* stack, u32 data)
  523. {
  524. *stack -= 4;
  525. return copy_to_user((u32*)*stack, &data);
  526. }
  527. void Thread::resume_from_stopped()
  528. {
  529. ASSERT(is_stopped());
  530. ASSERT(m_stop_state != State::Invalid);
  531. ASSERT(g_scheduler_lock.own_lock());
  532. set_state(m_stop_state != Blocked ? m_stop_state : Runnable);
  533. }
  534. DispatchSignalResult Thread::dispatch_signal(u8 signal)
  535. {
  536. ASSERT_INTERRUPTS_DISABLED();
  537. ASSERT(g_scheduler_lock.own_lock());
  538. ASSERT(signal > 0 && signal <= 32);
  539. ASSERT(process().is_user_process());
  540. ASSERT(this == Thread::current());
  541. #ifdef SIGNAL_DEBUG
  542. klog() << "signal: dispatch signal " << signal << " to " << *this;
  543. #endif
  544. if (m_state == Invalid || !is_initialized()) {
  545. // Thread has barely been created, we need to wait until it is
  546. // at least in Runnable state and is_initialized() returns true,
  547. // which indicates that it is fully set up an we actually have
  548. // a register state on the stack that we can modify
  549. return DispatchSignalResult::Deferred;
  550. }
  551. if (is_stopped() && signal != SIGCONT && signal != SIGKILL && signal != SIGTRAP) {
  552. #ifdef SIGNAL_DEBUG
  553. klog() << "signal: " << *this << " is stopped, will handle signal " << signal << " when resumed";
  554. #endif
  555. return DispatchSignalResult::Deferred;
  556. }
  557. auto& action = m_signal_action_data[signal];
  558. // FIXME: Implement SA_SIGINFO signal handlers.
  559. ASSERT(!(action.flags & SA_SIGINFO));
  560. // Mark this signal as handled.
  561. m_pending_signals &= ~(1 << (signal - 1));
  562. m_have_any_unmasked_pending_signals.store(m_pending_signals & ~m_signal_mask, AK::memory_order_release);
  563. auto* thread_tracer = tracer();
  564. if (signal == SIGSTOP || (thread_tracer && default_signal_action(signal) == DefaultSignalAction::DumpCore)) {
  565. if (!is_stopped()) {
  566. #ifdef SIGNAL_DEBUG
  567. dbg() << "signal: signal " << signal << " stopping thread " << *this;
  568. #endif
  569. m_stop_signal = signal;
  570. set_state(State::Stopped);
  571. }
  572. return DispatchSignalResult::Yield;
  573. }
  574. if (signal == SIGCONT && is_stopped()) {
  575. #ifdef SIGNAL_DEBUG
  576. dbg() << "signal: SIGCONT resuming " << *this << " from stopped";
  577. #endif
  578. resume_from_stopped();
  579. } else {
  580. if (thread_tracer != nullptr) {
  581. // when a thread is traced, it should be stopped whenever it receives a signal
  582. // the tracer is notified of this by using waitpid()
  583. // only "pending signals" from the tracer are sent to the tracee
  584. if (!thread_tracer->has_pending_signal(signal)) {
  585. m_stop_signal = signal;
  586. #ifdef SIGNAL_DEBUG
  587. dbg() << "signal: " << signal << " stopping " << *this << " for tracer";
  588. #endif
  589. set_state(Stopped);
  590. return DispatchSignalResult::Yield;
  591. }
  592. thread_tracer->unset_signal(signal);
  593. }
  594. }
  595. auto handler_vaddr = action.handler_or_sigaction;
  596. if (handler_vaddr.is_null()) {
  597. switch (default_signal_action(signal)) {
  598. case DefaultSignalAction::Stop:
  599. m_stop_signal = signal;
  600. set_state(Stopped);
  601. return DispatchSignalResult::Yield;
  602. case DefaultSignalAction::DumpCore:
  603. process().for_each_thread([](auto& thread) {
  604. thread.set_dump_backtrace_on_finalization();
  605. return IterationDecision::Continue;
  606. });
  607. [[fallthrough]];
  608. case DefaultSignalAction::Terminate:
  609. m_process->terminate_due_to_signal(signal);
  610. return DispatchSignalResult::Terminate;
  611. case DefaultSignalAction::Ignore:
  612. ASSERT_NOT_REACHED();
  613. case DefaultSignalAction::Continue:
  614. return DispatchSignalResult::Continue;
  615. }
  616. ASSERT_NOT_REACHED();
  617. }
  618. if (handler_vaddr.as_ptr() == SIG_IGN) {
  619. #ifdef SIGNAL_DEBUG
  620. klog() << "signal: " << *this << " ignored signal " << signal;
  621. #endif
  622. return DispatchSignalResult::Continue;
  623. }
  624. ProcessPagingScope paging_scope(m_process);
  625. u32 old_signal_mask = m_signal_mask;
  626. u32 new_signal_mask = action.mask;
  627. if (action.flags & SA_NODEFER)
  628. new_signal_mask &= ~(1 << (signal - 1));
  629. else
  630. new_signal_mask |= 1 << (signal - 1);
  631. m_signal_mask |= new_signal_mask;
  632. m_have_any_unmasked_pending_signals.store(m_pending_signals & ~m_signal_mask, AK::memory_order_release);
  633. auto setup_stack = [&](RegisterState& state) {
  634. u32* stack = &state.userspace_esp;
  635. u32 old_esp = *stack;
  636. u32 ret_eip = state.eip;
  637. u32 ret_eflags = state.eflags;
  638. #ifdef SIGNAL_DEBUG
  639. klog() << "signal: setting up user stack to return to eip: " << String::format("%p", ret_eip) << " esp: " << String::format("%p", old_esp);
  640. #endif
  641. // Align the stack to 16 bytes.
  642. // Note that we push 56 bytes (4 * 14) on to the stack,
  643. // so we need to account for this here.
  644. u32 stack_alignment = (*stack - 56) % 16;
  645. *stack -= stack_alignment;
  646. push_value_on_user_stack(stack, ret_eflags);
  647. push_value_on_user_stack(stack, ret_eip);
  648. push_value_on_user_stack(stack, state.eax);
  649. push_value_on_user_stack(stack, state.ecx);
  650. push_value_on_user_stack(stack, state.edx);
  651. push_value_on_user_stack(stack, state.ebx);
  652. push_value_on_user_stack(stack, old_esp);
  653. push_value_on_user_stack(stack, state.ebp);
  654. push_value_on_user_stack(stack, state.esi);
  655. push_value_on_user_stack(stack, state.edi);
  656. // PUSH old_signal_mask
  657. push_value_on_user_stack(stack, old_signal_mask);
  658. push_value_on_user_stack(stack, signal);
  659. push_value_on_user_stack(stack, handler_vaddr.get());
  660. push_value_on_user_stack(stack, 0); //push fake return address
  661. ASSERT((*stack % 16) == 0);
  662. };
  663. // We now place the thread state on the userspace stack.
  664. // Note that we use a RegisterState.
  665. // Conversely, when the thread isn't blocking the RegisterState may not be
  666. // valid (fork, exec etc) but the tss will, so we use that instead.
  667. auto& regs = get_register_dump_from_stack();
  668. setup_stack(regs);
  669. regs.eip = g_return_to_ring3_from_signal_trampoline.get();
  670. #ifdef SIGNAL_DEBUG
  671. klog() << "signal: Okay, " << *this << " {" << state_string() << "} has been primed with signal handler " << String::format("%w", m_tss.cs) << ":" << String::format("%x", m_tss.eip) << " to deliver " << signal;
  672. #endif
  673. return DispatchSignalResult::Continue;
  674. }
  675. void Thread::set_default_signal_dispositions()
  676. {
  677. // FIXME: Set up all the right default actions. See signal(7).
  678. memset(&m_signal_action_data, 0, sizeof(m_signal_action_data));
  679. m_signal_action_data[SIGCHLD].handler_or_sigaction = VirtualAddress(SIG_IGN);
  680. m_signal_action_data[SIGWINCH].handler_or_sigaction = VirtualAddress(SIG_IGN);
  681. }
  682. bool Thread::push_value_on_stack(FlatPtr value)
  683. {
  684. m_tss.esp -= 4;
  685. FlatPtr* stack_ptr = (FlatPtr*)m_tss.esp;
  686. return copy_to_user(stack_ptr, &value);
  687. }
  688. RegisterState& Thread::get_register_dump_from_stack()
  689. {
  690. return *(RegisterState*)(kernel_stack_top() - sizeof(RegisterState));
  691. }
  692. KResultOr<u32> Thread::make_userspace_stack_for_main_thread(Vector<String> arguments, Vector<String> environment, Vector<AuxiliaryValue> auxiliary_values)
  693. {
  694. auto* region = m_process->allocate_region(VirtualAddress(), default_userspace_stack_size, "Stack (Main thread)", PROT_READ | PROT_WRITE, false);
  695. if (!region)
  696. return KResult(-ENOMEM);
  697. region->set_stack(true);
  698. FlatPtr new_esp = region->vaddr().offset(default_userspace_stack_size).get();
  699. auto push_on_new_stack = [&new_esp](u32 value) {
  700. new_esp -= 4;
  701. Userspace<u32*> stack_ptr = new_esp;
  702. return copy_to_user(stack_ptr, &value);
  703. };
  704. auto push_aux_value_on_new_stack = [&new_esp](auxv_t value) {
  705. new_esp -= sizeof(auxv_t);
  706. Userspace<auxv_t*> stack_ptr = new_esp;
  707. return copy_to_user(stack_ptr, &value);
  708. };
  709. auto push_string_on_new_stack = [&new_esp](const String& string) {
  710. new_esp -= round_up_to_power_of_two(string.length() + 1, 4);
  711. Userspace<u32*> stack_ptr = new_esp;
  712. return copy_to_user(stack_ptr, string.characters(), string.length() + 1);
  713. };
  714. Vector<FlatPtr> argv_entries;
  715. for (auto& argument : arguments) {
  716. push_string_on_new_stack(argument);
  717. argv_entries.append(new_esp);
  718. }
  719. Vector<FlatPtr> env_entries;
  720. for (auto& variable : environment) {
  721. push_string_on_new_stack(variable);
  722. env_entries.append(new_esp);
  723. }
  724. for (auto& value : auxiliary_values) {
  725. if (!value.optional_string.is_empty()) {
  726. push_string_on_new_stack(value.optional_string);
  727. value.auxv.a_un.a_ptr = (void*)new_esp;
  728. }
  729. }
  730. for (ssize_t i = auxiliary_values.size() - 1; i >= 0; --i) {
  731. auto& value = auxiliary_values[i];
  732. push_aux_value_on_new_stack(value.auxv);
  733. }
  734. push_on_new_stack(0);
  735. for (ssize_t i = env_entries.size() - 1; i >= 0; --i)
  736. push_on_new_stack(env_entries[i]);
  737. FlatPtr envp = new_esp;
  738. push_on_new_stack(0);
  739. for (ssize_t i = argv_entries.size() - 1; i >= 0; --i)
  740. push_on_new_stack(argv_entries[i]);
  741. FlatPtr argv = new_esp;
  742. // NOTE: The stack needs to be 16-byte aligned.
  743. new_esp -= new_esp % 16;
  744. push_on_new_stack((FlatPtr)envp);
  745. push_on_new_stack((FlatPtr)argv);
  746. push_on_new_stack((FlatPtr)argv_entries.size());
  747. push_on_new_stack(0);
  748. return new_esp;
  749. }
  750. RefPtr<Thread> Thread::clone(Process& process)
  751. {
  752. auto clone = adopt(*new Thread(process));
  753. memcpy(clone->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  754. clone->m_signal_mask = m_signal_mask;
  755. memcpy(clone->m_fpu_state, m_fpu_state, sizeof(FPUState));
  756. clone->m_thread_specific_data = m_thread_specific_data;
  757. clone->m_thread_specific_region_size = m_thread_specific_region_size;
  758. return clone;
  759. }
  760. void Thread::set_state(State new_state)
  761. {
  762. ASSERT(g_scheduler_lock.own_lock());
  763. if (new_state == m_state)
  764. return;
  765. if (new_state == Blocked) {
  766. // we should always have a Blocker while blocked
  767. ASSERT(m_blocker != nullptr);
  768. }
  769. auto previous_state = m_state;
  770. if (previous_state == Invalid) {
  771. // If we were *just* created, we may have already pending signals
  772. ScopedSpinLock thread_lock(m_lock);
  773. if (has_unmasked_pending_signals()) {
  774. dbg() << "Dispatch pending signals to new thread " << *this;
  775. dispatch_one_pending_signal();
  776. }
  777. }
  778. m_state = new_state;
  779. #ifdef THREAD_DEBUG
  780. dbg() << "Set Thread " << *this << " state to " << state_string();
  781. #endif
  782. if (m_process->pid() != 0) {
  783. update_state_for_thread(previous_state);
  784. ASSERT(g_scheduler_data->has_thread(*this));
  785. }
  786. if (previous_state == Stopped) {
  787. m_stop_state = State::Invalid;
  788. process().unblock_waiters(*this, Thread::WaitBlocker::UnblockFlags::Continued);
  789. }
  790. if (m_state == Stopped) {
  791. // We don't want to restore to Running state, only Runnable!
  792. m_stop_state = previous_state != Running ? m_state : Runnable;
  793. process().unblock_waiters(*this, Thread::WaitBlocker::UnblockFlags::Stopped, m_stop_signal);
  794. } else if (m_state == Dying) {
  795. ASSERT(previous_state != Queued);
  796. if (this != Thread::current() && is_finalizable()) {
  797. // Some other thread set this thread to Dying, notify the
  798. // finalizer right away as it can be cleaned up now
  799. Scheduler::notify_finalizer();
  800. }
  801. }
  802. }
  803. void Thread::update_state_for_thread(Thread::State previous_state)
  804. {
  805. ASSERT_INTERRUPTS_DISABLED();
  806. ASSERT(g_scheduler_data);
  807. ASSERT(g_scheduler_lock.own_lock());
  808. auto& previous_list = g_scheduler_data->thread_list_for_state(previous_state);
  809. auto& list = g_scheduler_data->thread_list_for_state(state());
  810. if (&previous_list != &list) {
  811. previous_list.remove(*this);
  812. }
  813. if (list.contains(*this))
  814. return;
  815. list.append(*this);
  816. }
  817. String Thread::backtrace()
  818. {
  819. return backtrace_impl();
  820. }
  821. struct RecognizedSymbol {
  822. u32 address;
  823. const KernelSymbol* symbol { nullptr };
  824. };
  825. static bool symbolicate(const RecognizedSymbol& symbol, const Process& process, StringBuilder& builder, Process::ELFBundle* elf_bundle)
  826. {
  827. if (!symbol.address)
  828. return false;
  829. bool mask_kernel_addresses = !process.is_superuser();
  830. if (!symbol.symbol) {
  831. if (!is_user_address(VirtualAddress(symbol.address))) {
  832. builder.append("0xdeadc0de\n");
  833. } else {
  834. if (elf_bundle && elf_bundle->elf_loader->has_symbols())
  835. builder.appendf("%p %s\n", symbol.address, elf_bundle->elf_loader->symbolicate(symbol.address).characters());
  836. else
  837. builder.appendf("%p\n", symbol.address);
  838. }
  839. return true;
  840. }
  841. unsigned offset = symbol.address - symbol.symbol->address;
  842. if (symbol.symbol->address == g_highest_kernel_symbol_address && offset > 4096) {
  843. builder.appendf("%p\n", mask_kernel_addresses ? 0xdeadc0de : symbol.address);
  844. } else {
  845. builder.appendf("%p %s +%u\n", mask_kernel_addresses ? 0xdeadc0de : symbol.address, demangle(symbol.symbol->name).characters(), offset);
  846. }
  847. return true;
  848. }
  849. String Thread::backtrace_impl()
  850. {
  851. Vector<RecognizedSymbol, 128> recognized_symbols;
  852. auto& process = const_cast<Process&>(this->process());
  853. OwnPtr<Process::ELFBundle> elf_bundle;
  854. if (!Processor::current().in_irq()) {
  855. // If we're handling IRQs we can't really safely symbolicate
  856. elf_bundle = process.elf_bundle();
  857. }
  858. ProcessPagingScope paging_scope(process);
  859. // To prevent a context switch involving this thread, which may happen
  860. // on another processor, we need to acquire the scheduler lock while
  861. // walking the stack
  862. {
  863. ScopedSpinLock lock(g_scheduler_lock);
  864. FlatPtr stack_ptr, eip;
  865. if (Processor::get_context_frame_ptr(*this, stack_ptr, eip)) {
  866. recognized_symbols.append({ eip, symbolicate_kernel_address(eip) });
  867. while (stack_ptr) {
  868. FlatPtr retaddr;
  869. if (is_user_range(VirtualAddress(stack_ptr), sizeof(FlatPtr) * 2)) {
  870. if (!copy_from_user(&retaddr, &((FlatPtr*)stack_ptr)[1]))
  871. break;
  872. recognized_symbols.append({ retaddr, symbolicate_kernel_address(retaddr) });
  873. if (!copy_from_user(&stack_ptr, (FlatPtr*)stack_ptr))
  874. break;
  875. } else {
  876. void* fault_at;
  877. if (!safe_memcpy(&retaddr, &((FlatPtr*)stack_ptr)[1], sizeof(FlatPtr), fault_at))
  878. break;
  879. recognized_symbols.append({ retaddr, symbolicate_kernel_address(retaddr) });
  880. if (!safe_memcpy(&stack_ptr, (FlatPtr*)stack_ptr, sizeof(FlatPtr), fault_at))
  881. break;
  882. }
  883. }
  884. }
  885. }
  886. StringBuilder builder;
  887. for (auto& symbol : recognized_symbols) {
  888. if (!symbolicate(symbol, process, builder, elf_bundle.ptr()))
  889. break;
  890. }
  891. return builder.to_string();
  892. }
  893. Vector<FlatPtr> Thread::raw_backtrace(FlatPtr ebp, FlatPtr eip) const
  894. {
  895. InterruptDisabler disabler;
  896. auto& process = const_cast<Process&>(this->process());
  897. ProcessPagingScope paging_scope(process);
  898. Vector<FlatPtr, Profiling::max_stack_frame_count> backtrace;
  899. backtrace.append(eip);
  900. FlatPtr stack_ptr_copy;
  901. FlatPtr stack_ptr = (FlatPtr)ebp;
  902. while (stack_ptr) {
  903. void* fault_at;
  904. if (!safe_memcpy(&stack_ptr_copy, (void*)stack_ptr, sizeof(FlatPtr), fault_at))
  905. break;
  906. FlatPtr retaddr;
  907. if (!safe_memcpy(&retaddr, (void*)(stack_ptr + sizeof(FlatPtr)), sizeof(FlatPtr), fault_at))
  908. break;
  909. backtrace.append(retaddr);
  910. if (backtrace.size() == Profiling::max_stack_frame_count)
  911. break;
  912. stack_ptr = stack_ptr_copy;
  913. }
  914. return backtrace;
  915. }
  916. KResult Thread::make_thread_specific_region(Badge<Process>)
  917. {
  918. size_t thread_specific_region_alignment = max(process().m_master_tls_alignment, alignof(ThreadSpecificData));
  919. m_thread_specific_region_size = align_up_to(process().m_master_tls_size, thread_specific_region_alignment) + sizeof(ThreadSpecificData);
  920. auto* region = process().allocate_region({}, m_thread_specific_region_size, "Thread-specific", PROT_READ | PROT_WRITE, true);
  921. if (!region)
  922. return KResult(-ENOMEM);
  923. SmapDisabler disabler;
  924. auto* thread_specific_data = (ThreadSpecificData*)region->vaddr().offset(align_up_to(process().m_master_tls_size, thread_specific_region_alignment)).as_ptr();
  925. auto* thread_local_storage = (u8*)((u8*)thread_specific_data) - align_up_to(process().m_master_tls_size, process().m_master_tls_alignment);
  926. m_thread_specific_data = VirtualAddress(thread_specific_data);
  927. thread_specific_data->self = thread_specific_data;
  928. if (process().m_master_tls_size)
  929. memcpy(thread_local_storage, process().m_master_tls_region.unsafe_ptr()->vaddr().as_ptr(), process().m_master_tls_size);
  930. return KSuccess;
  931. }
  932. const LogStream& operator<<(const LogStream& stream, const Thread& value)
  933. {
  934. return stream << value.process().name() << "(" << value.pid().value() << ":" << value.tid().value() << ")";
  935. }
  936. Thread::BlockResult Thread::wait_on(WaitQueue& queue, const char* reason, const BlockTimeout& timeout, Atomic<bool>* lock, RefPtr<Thread> beneficiary)
  937. {
  938. auto* current_thread = Thread::current();
  939. RefPtr<Timer> timer;
  940. bool block_finished = false;
  941. bool did_timeout = false;
  942. bool did_unlock;
  943. {
  944. ScopedCritical critical;
  945. // We need to be in a critical section *and* then also acquire the
  946. // scheduler lock. The only way acquiring the scheduler lock could
  947. // block us is if another core were to be holding it, in which case
  948. // we need to wait until the scheduler lock is released again
  949. {
  950. ScopedSpinLock sched_lock(g_scheduler_lock);
  951. if (!timeout.is_infinite()) {
  952. timer = TimerQueue::the().add_timer_without_id(timeout.absolute_time(), [&]() {
  953. // NOTE: this may execute on the same or any other processor!
  954. ScopedSpinLock lock(g_scheduler_lock);
  955. if (!block_finished) {
  956. did_timeout = true;
  957. wake_from_queue();
  958. }
  959. });
  960. if (!timer) {
  961. if (lock)
  962. *lock = false;
  963. // We timed out already, don't block
  964. return BlockResult::InterruptedByTimeout;
  965. }
  966. }
  967. // m_queue can only be accessed safely if g_scheduler_lock is held!
  968. m_queue = &queue;
  969. if (!queue.enqueue(*current_thread)) {
  970. // The WaitQueue was already requested to wake someone when
  971. // nobody was waiting. So return right away as we shouldn't
  972. // be waiting
  973. // NOTE: Do not set lock to false in this case!
  974. return BlockResult::NotBlocked;
  975. }
  976. if (lock)
  977. *lock = false;
  978. did_unlock = unlock_process_if_locked();
  979. set_state(State::Queued);
  980. m_wait_reason = reason;
  981. // Yield and wait for the queue to wake us up again.
  982. if (beneficiary)
  983. Scheduler::donate_to(beneficiary, reason);
  984. else
  985. Scheduler::yield();
  986. }
  987. // We've unblocked, relock the process if needed and carry on.
  988. relock_process(did_unlock);
  989. // This looks counter productive, but we may not actually leave
  990. // the critical section we just restored. It depends on whether
  991. // we were in one while being called.
  992. if (current_thread->should_die()) {
  993. // We're being unblocked so that we can clean up. We shouldn't
  994. // be in Dying state until we're about to return back to user mode
  995. ASSERT(current_thread->state() == Thread::Running);
  996. #ifdef THREAD_DEBUG
  997. dbg() << "Dying thread " << *current_thread << " was unblocked";
  998. #endif
  999. }
  1000. }
  1001. BlockResult result(BlockResult::WokeNormally);
  1002. {
  1003. // To be able to look at m_wait_queue_node we once again need the
  1004. // scheduler lock, which is held when we insert into the queue
  1005. ScopedSpinLock sched_lock(g_scheduler_lock);
  1006. block_finished = true;
  1007. if (m_queue) {
  1008. ASSERT(m_queue == &queue);
  1009. // If our thread was still in the queue, we timed out
  1010. m_queue = nullptr;
  1011. if (queue.dequeue(*current_thread))
  1012. result = BlockResult::InterruptedByTimeout;
  1013. } else {
  1014. // Our thread was already removed from the queue. The only
  1015. // way this can happen if someone else is trying to kill us.
  1016. // In this case, the queue should not contain us anymore.
  1017. result = BlockResult::InterruptedByDeath;
  1018. }
  1019. }
  1020. if (timer && !did_timeout) {
  1021. // Cancel the timer while not holding any locks. This allows
  1022. // the timer function to complete before we remove it
  1023. // (e.g. if it's on another processor)
  1024. TimerQueue::the().cancel_timer(timer.release_nonnull());
  1025. }
  1026. return result;
  1027. }
  1028. void Thread::wake_from_queue()
  1029. {
  1030. ScopedSpinLock lock(g_scheduler_lock);
  1031. ASSERT(state() == State::Queued);
  1032. m_wait_reason = nullptr;
  1033. if (this != Thread::current())
  1034. set_state(State::Runnable);
  1035. else
  1036. set_state(State::Running);
  1037. }
  1038. RefPtr<Thread> Thread::from_tid(ThreadID tid)
  1039. {
  1040. RefPtr<Thread> found_thread;
  1041. ScopedSpinLock lock(g_scheduler_lock);
  1042. Thread::for_each([&](auto& thread) {
  1043. if (thread.tid() == tid) {
  1044. found_thread = &thread;
  1045. return IterationDecision::Break;
  1046. }
  1047. return IterationDecision::Continue;
  1048. });
  1049. return found_thread;
  1050. }
  1051. void Thread::reset_fpu_state()
  1052. {
  1053. memcpy(m_fpu_state, &Processor::current().clean_fpu_state(), sizeof(FPUState));
  1054. }
  1055. void Thread::start_tracing_from(ProcessID tracer)
  1056. {
  1057. m_tracer = ThreadTracer::create(tracer);
  1058. }
  1059. void Thread::stop_tracing()
  1060. {
  1061. m_tracer = nullptr;
  1062. }
  1063. void Thread::tracer_trap(const RegisterState& regs)
  1064. {
  1065. ASSERT(m_tracer.ptr());
  1066. m_tracer->set_regs(regs);
  1067. send_urgent_signal_to_self(SIGTRAP);
  1068. }
  1069. const Thread::Blocker& Thread::blocker() const
  1070. {
  1071. ASSERT(m_lock.own_lock());
  1072. ASSERT(m_blocker);
  1073. return *m_blocker;
  1074. }
  1075. }