Thread.cpp 42 KB

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