Thread.cpp 43 KB

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