Thread.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. #include <AK/Demangle.h>
  2. #include <AK/StringBuilder.h>
  3. #include <Kernel/FileSystem/FileDescription.h>
  4. #include <Kernel/Process.h>
  5. #include <Kernel/Scheduler.h>
  6. #include <Kernel/Thread.h>
  7. #include <Kernel/VM/MemoryManager.h>
  8. #include <LibC/signal_numbers.h>
  9. #include <LibELF/ELFLoader.h>
  10. //#define SIGNAL_DEBUG
  11. u16 thread_specific_selector()
  12. {
  13. static u16 selector;
  14. if (!selector) {
  15. selector = gdt_alloc_entry();
  16. auto& descriptor = get_gdt_entry(selector);
  17. descriptor.dpl = 3;
  18. descriptor.segment_present = 1;
  19. descriptor.granularity = 0;
  20. descriptor.zero = 0;
  21. descriptor.operation_size = 1;
  22. descriptor.descriptor_type = 1;
  23. descriptor.type = 2;
  24. }
  25. return selector;
  26. }
  27. Descriptor& thread_specific_descriptor()
  28. {
  29. return get_gdt_entry(thread_specific_selector());
  30. }
  31. HashTable<Thread*>& thread_table()
  32. {
  33. ASSERT_INTERRUPTS_DISABLED();
  34. static HashTable<Thread*>* table;
  35. if (!table)
  36. table = new HashTable<Thread*>;
  37. return *table;
  38. }
  39. Thread::Thread(Process& process)
  40. : m_process(process)
  41. , m_tid(process.m_next_tid++)
  42. {
  43. dbgprintf("Thread{%p}: New thread TID=%u in %s(%u)\n", this, m_tid, process.name().characters(), process.pid());
  44. set_default_signal_dispositions();
  45. m_fpu_state = (FPUState*)kmalloc_aligned(sizeof(FPUState), 16);
  46. memset(m_fpu_state, 0, sizeof(FPUState));
  47. memset(&m_tss, 0, sizeof(m_tss));
  48. // Only IF is set when a process boots.
  49. m_tss.eflags = 0x0202;
  50. u16 cs, ds, ss, gs;
  51. if (m_process.is_ring0()) {
  52. cs = 0x08;
  53. ds = 0x10;
  54. ss = 0x10;
  55. gs = 0;
  56. } else {
  57. cs = 0x1b;
  58. ds = 0x23;
  59. ss = 0x23;
  60. gs = thread_specific_selector() | 3;
  61. }
  62. m_tss.ds = ds;
  63. m_tss.es = ds;
  64. m_tss.fs = ds;
  65. m_tss.gs = gs;
  66. m_tss.ss = ss;
  67. m_tss.cs = cs;
  68. m_tss.cr3 = m_process.page_directory().cr3();
  69. if (m_process.is_ring0()) {
  70. // FIXME: This memory is leaked.
  71. // But uh, there's also no kernel process termination, so I guess it's not technically leaked...
  72. m_kernel_stack_base = (u32)kmalloc_eternal(default_kernel_stack_size);
  73. m_kernel_stack_top = (m_kernel_stack_base + default_kernel_stack_size) & 0xfffffff8u;
  74. m_tss.esp = m_kernel_stack_top;
  75. } else {
  76. // Ring3 processes need a separate stack for Ring0.
  77. m_kernel_stack_region = MM.allocate_kernel_region(default_kernel_stack_size, String::format("Kernel Stack (Thread %d)", m_tid));
  78. m_kernel_stack_base = m_kernel_stack_region->vaddr().get();
  79. m_kernel_stack_top = m_kernel_stack_region->vaddr().offset(default_kernel_stack_size).get() & 0xfffffff8u;
  80. m_tss.ss0 = 0x10;
  81. m_tss.esp0 = m_kernel_stack_top;
  82. }
  83. // HACK: Ring2 SS in the TSS is the current PID.
  84. m_tss.ss2 = m_process.pid();
  85. m_far_ptr.offset = 0x98765432;
  86. if (m_process.pid() != 0) {
  87. InterruptDisabler disabler;
  88. thread_table().set(this);
  89. Scheduler::init_thread(*this);
  90. }
  91. }
  92. Thread::~Thread()
  93. {
  94. dbgprintf("~Thread{%p}\n", this);
  95. kfree_aligned(m_fpu_state);
  96. {
  97. InterruptDisabler disabler;
  98. thread_table().remove(this);
  99. }
  100. if (g_last_fpu_thread == this)
  101. g_last_fpu_thread = nullptr;
  102. if (selector())
  103. gdt_free_entry(selector());
  104. if (m_userspace_stack_region)
  105. m_process.deallocate_region(*m_userspace_stack_region);
  106. }
  107. void Thread::unblock()
  108. {
  109. if (current == this) {
  110. set_state(Thread::Running);
  111. return;
  112. }
  113. ASSERT(m_state != Thread::Runnable && m_state != Thread::Running);
  114. set_state(Thread::Runnable);
  115. }
  116. void Thread::set_should_die()
  117. {
  118. if (m_should_die)
  119. return;
  120. InterruptDisabler disabler;
  121. // Remember that we should die instead of returning to
  122. // the userspace.
  123. m_should_die = true;
  124. if (is_blocked()) {
  125. ASSERT(in_kernel());
  126. ASSERT(m_blocker != nullptr);
  127. // We're blocked in the kernel. Pretend to have
  128. // been interrupted by a signal (perhaps that is
  129. // what has actually killed us).
  130. m_blocker->set_interrupted_by_signal();
  131. unblock();
  132. } else if (!in_kernel()) {
  133. // We're executing in userspace (and we're clearly
  134. // not the current thread). No need to unwind, so
  135. // set the state to dying right away. This also
  136. // makes sure we won't be scheduled anymore.
  137. set_state(Thread::State::Dying);
  138. }
  139. }
  140. void Thread::die_if_needed()
  141. {
  142. ASSERT(current == this);
  143. if (!m_should_die)
  144. return;
  145. InterruptDisabler disabler;
  146. set_state(Thread::State::Dying);
  147. if (!Scheduler::is_active())
  148. Scheduler::pick_next_and_switch_now();
  149. }
  150. void Thread::yield_without_holding_big_lock()
  151. {
  152. bool did_unlock = process().big_lock().unlock_if_locked();
  153. Scheduler::yield();
  154. if (did_unlock)
  155. process().big_lock().lock();
  156. }
  157. void Thread::donate_and_yield_without_holding_big_lock(Thread* beneficiary, const char* reason)
  158. {
  159. bool did_unlock = process().big_lock().unlock_if_locked();
  160. Scheduler::donate_to(beneficiary, reason);
  161. if (did_unlock)
  162. process().big_lock().lock();
  163. }
  164. u64 Thread::sleep(u32 ticks)
  165. {
  166. ASSERT(state() == Thread::Running);
  167. u64 wakeup_time = g_uptime + ticks;
  168. auto ret = current->block<Thread::SleepBlocker>(wakeup_time);
  169. if (wakeup_time > g_uptime) {
  170. ASSERT(ret == Thread::BlockResult::InterruptedBySignal);
  171. }
  172. return wakeup_time;
  173. }
  174. u64 Thread::sleep_until(u64 wakeup_time)
  175. {
  176. ASSERT(state() == Thread::Running);
  177. auto ret = current->block<Thread::SleepBlocker>(wakeup_time);
  178. if (wakeup_time > g_uptime)
  179. ASSERT(ret == Thread::BlockResult::InterruptedBySignal);
  180. return wakeup_time;
  181. }
  182. const char* Thread::state_string() const
  183. {
  184. switch (state()) {
  185. case Thread::Invalid:
  186. return "Invalid";
  187. case Thread::Runnable:
  188. return "Runnable";
  189. case Thread::Running:
  190. return "Running";
  191. case Thread::Dying:
  192. return "Dying";
  193. case Thread::Dead:
  194. return "Dead";
  195. case Thread::Stopped:
  196. return "Stopped";
  197. case Thread::Skip1SchedulerPass:
  198. return "Skip1";
  199. case Thread::Skip0SchedulerPasses:
  200. return "Skip0";
  201. case Thread::Blocked:
  202. ASSERT(m_blocker != nullptr);
  203. return m_blocker->state_string();
  204. }
  205. kprintf("Thread::state_string(): Invalid state: %u\n", state());
  206. ASSERT_NOT_REACHED();
  207. return nullptr;
  208. }
  209. void Thread::finalize()
  210. {
  211. ASSERT(current == g_finalizer);
  212. dbgprintf("Finalizing Thread %u in %s(%u)\n", tid(), m_process.name().characters(), pid());
  213. set_state(Thread::State::Dead);
  214. if (m_joiner) {
  215. ASSERT(m_joiner->m_joinee == this);
  216. static_cast<JoinBlocker*>(m_joiner->m_blocker)->set_joinee_exit_value(m_exit_value);
  217. m_joiner->m_joinee = nullptr;
  218. // NOTE: We clear the joiner pointer here as well, to be tidy.
  219. m_joiner = nullptr;
  220. }
  221. if (m_dump_backtrace_on_finalization)
  222. dbg() << backtrace_impl();
  223. if (this == &m_process.main_thread()) {
  224. m_process.finalize();
  225. return;
  226. }
  227. delete this;
  228. }
  229. void Thread::finalize_dying_threads()
  230. {
  231. ASSERT(current == g_finalizer);
  232. Vector<Thread*, 32> dying_threads;
  233. {
  234. InterruptDisabler disabler;
  235. for_each_in_state(Thread::State::Dying, [&](Thread& thread) {
  236. dying_threads.append(&thread);
  237. return IterationDecision::Continue;
  238. });
  239. }
  240. for (auto* thread : dying_threads)
  241. thread->finalize();
  242. }
  243. bool Thread::tick()
  244. {
  245. ++m_ticks;
  246. if (tss().cs & 3)
  247. ++m_process.m_ticks_in_user;
  248. else
  249. ++m_process.m_ticks_in_kernel;
  250. return --m_ticks_left;
  251. }
  252. void Thread::send_signal(u8 signal, Process* sender)
  253. {
  254. ASSERT(signal < 32);
  255. InterruptDisabler disabler;
  256. // FIXME: Figure out what to do for masked signals. Should we also ignore them here?
  257. if (should_ignore_signal(signal)) {
  258. dbg() << "signal " << signal << " was ignored by " << process();
  259. return;
  260. }
  261. if (sender)
  262. dbgprintf("signal: %s(%u) sent %d to %s(%u)\n", sender->name().characters(), sender->pid(), signal, process().name().characters(), pid());
  263. else
  264. dbgprintf("signal: kernel sent %d to %s(%u)\n", signal, process().name().characters(), pid());
  265. m_pending_signals |= 1 << (signal - 1);
  266. }
  267. // Certain exceptions, such as SIGSEGV and SIGILL, put a
  268. // thread into a state where the signal handler must be
  269. // invoked immediately, otherwise it will continue to fault.
  270. // This function should be used in an exception handler to
  271. // ensure that when the thread resumes, it's executing in
  272. // the appropriate signal handler.
  273. void Thread::send_urgent_signal_to_self(u8 signal)
  274. {
  275. // FIXME: because of a bug in dispatch_signal we can't
  276. // setup a signal while we are the current thread. Because of
  277. // this we use a work-around where we send the signal and then
  278. // block, allowing the scheduler to properly dispatch the signal
  279. // before the thread is next run.
  280. send_signal(signal, &process());
  281. (void)block<SemiPermanentBlocker>(SemiPermanentBlocker::Reason::Signal);
  282. }
  283. bool Thread::has_unmasked_pending_signals() const
  284. {
  285. return m_pending_signals & ~m_signal_mask;
  286. }
  287. ShouldUnblockThread Thread::dispatch_one_pending_signal()
  288. {
  289. ASSERT_INTERRUPTS_DISABLED();
  290. u32 signal_candidates = m_pending_signals & ~m_signal_mask;
  291. ASSERT(signal_candidates);
  292. u8 signal = 1;
  293. for (; signal < 32; ++signal) {
  294. if (signal_candidates & (1 << (signal - 1))) {
  295. break;
  296. }
  297. }
  298. return dispatch_signal(signal);
  299. }
  300. enum class DefaultSignalAction {
  301. Terminate,
  302. Ignore,
  303. DumpCore,
  304. Stop,
  305. Continue,
  306. };
  307. DefaultSignalAction default_signal_action(u8 signal)
  308. {
  309. ASSERT(signal && signal < NSIG);
  310. switch (signal) {
  311. case SIGHUP:
  312. case SIGINT:
  313. case SIGKILL:
  314. case SIGPIPE:
  315. case SIGALRM:
  316. case SIGUSR1:
  317. case SIGUSR2:
  318. case SIGVTALRM:
  319. case SIGSTKFLT:
  320. case SIGIO:
  321. case SIGPROF:
  322. case SIGTERM:
  323. case SIGPWR:
  324. return DefaultSignalAction::Terminate;
  325. case SIGCHLD:
  326. case SIGURG:
  327. case SIGWINCH:
  328. return DefaultSignalAction::Ignore;
  329. case SIGQUIT:
  330. case SIGILL:
  331. case SIGTRAP:
  332. case SIGABRT:
  333. case SIGBUS:
  334. case SIGFPE:
  335. case SIGSEGV:
  336. case SIGXCPU:
  337. case SIGXFSZ:
  338. case SIGSYS:
  339. return DefaultSignalAction::DumpCore;
  340. case SIGCONT:
  341. return DefaultSignalAction::Continue;
  342. case SIGSTOP:
  343. case SIGTSTP:
  344. case SIGTTIN:
  345. case SIGTTOU:
  346. return DefaultSignalAction::Stop;
  347. }
  348. ASSERT_NOT_REACHED();
  349. }
  350. bool Thread::should_ignore_signal(u8 signal) const
  351. {
  352. ASSERT(signal < 32);
  353. auto& action = m_signal_action_data[signal];
  354. if (action.handler_or_sigaction.is_null())
  355. return default_signal_action(signal) == DefaultSignalAction::Ignore;
  356. if (action.handler_or_sigaction.as_ptr() == SIG_IGN)
  357. return true;
  358. return false;
  359. }
  360. bool Thread::has_signal_handler(u8 signal) const
  361. {
  362. ASSERT(signal < 32);
  363. auto& action = m_signal_action_data[signal];
  364. return !action.handler_or_sigaction.is_null();
  365. }
  366. static void push_value_on_user_stack(u32* stack, u32 data)
  367. {
  368. *stack -= 4;
  369. *(u32*)*stack = data;
  370. }
  371. ShouldUnblockThread Thread::dispatch_signal(u8 signal)
  372. {
  373. ASSERT_INTERRUPTS_DISABLED();
  374. ASSERT(signal > 0 && signal <= 32);
  375. ASSERT(!process().is_ring0());
  376. #ifdef SIGNAL_DEBUG
  377. kprintf("dispatch_signal %s(%u) <- %u\n", process().name().characters(), pid(), signal);
  378. #endif
  379. auto& action = m_signal_action_data[signal];
  380. // FIXME: Implement SA_SIGINFO signal handlers.
  381. ASSERT(!(action.flags & SA_SIGINFO));
  382. // Mark this signal as handled.
  383. m_pending_signals &= ~(1 << (signal - 1));
  384. if (signal == SIGSTOP) {
  385. set_state(Stopped);
  386. return ShouldUnblockThread::No;
  387. }
  388. if (signal == SIGCONT && state() == Stopped)
  389. set_state(Runnable);
  390. auto handler_vaddr = action.handler_or_sigaction;
  391. if (handler_vaddr.is_null()) {
  392. switch (default_signal_action(signal)) {
  393. case DefaultSignalAction::Stop:
  394. set_state(Stopped);
  395. return ShouldUnblockThread::No;
  396. case DefaultSignalAction::DumpCore:
  397. process().for_each_thread([](auto& thread) {
  398. thread.set_dump_backtrace_on_finalization();
  399. return IterationDecision::Continue;
  400. });
  401. [[fallthrough]];
  402. case DefaultSignalAction::Terminate:
  403. m_process.terminate_due_to_signal(signal);
  404. return ShouldUnblockThread::No;
  405. case DefaultSignalAction::Ignore:
  406. ASSERT_NOT_REACHED();
  407. case DefaultSignalAction::Continue:
  408. return ShouldUnblockThread::Yes;
  409. }
  410. ASSERT_NOT_REACHED();
  411. }
  412. if (handler_vaddr.as_ptr() == SIG_IGN) {
  413. #ifdef SIGNAL_DEBUG
  414. kprintf("%s(%u) ignored signal %u\n", process().name().characters(), pid(), signal);
  415. #endif
  416. return ShouldUnblockThread::Yes;
  417. }
  418. ProcessPagingScope paging_scope(m_process);
  419. u32 old_signal_mask = m_signal_mask;
  420. u32 new_signal_mask = action.mask;
  421. if (action.flags & SA_NODEFER)
  422. new_signal_mask &= ~(1 << (signal - 1));
  423. else
  424. new_signal_mask |= 1 << (signal - 1);
  425. m_signal_mask |= new_signal_mask;
  426. auto setup_stack = [&]<typename ThreadState>(ThreadState state, u32 * stack)
  427. {
  428. u32 old_esp = *stack;
  429. u32 ret_eip = state.eip;
  430. u32 ret_eflags = state.eflags;
  431. // Align the stack to 16 bytes.
  432. // Note that we push 56 bytes (4 * 14) on to the stack,
  433. // so we need to account for this here.
  434. u32 stack_alignment = (*stack - 56) % 16;
  435. *stack -= stack_alignment;
  436. push_value_on_user_stack(stack, ret_eflags);
  437. push_value_on_user_stack(stack, ret_eip);
  438. push_value_on_user_stack(stack, state.eax);
  439. push_value_on_user_stack(stack, state.ecx);
  440. push_value_on_user_stack(stack, state.edx);
  441. push_value_on_user_stack(stack, state.ebx);
  442. push_value_on_user_stack(stack, old_esp);
  443. push_value_on_user_stack(stack, state.ebp);
  444. push_value_on_user_stack(stack, state.esi);
  445. push_value_on_user_stack(stack, state.edi);
  446. // PUSH old_signal_mask
  447. push_value_on_user_stack(stack, old_signal_mask);
  448. push_value_on_user_stack(stack, signal);
  449. push_value_on_user_stack(stack, handler_vaddr.get());
  450. push_value_on_user_stack(stack, 0); //push fake return address
  451. ASSERT((*stack % 16) == 0);
  452. };
  453. // We now place the thread state on the userspace stack.
  454. // Note that when we are in the kernel (ie. blocking) we cannot use the
  455. // tss, as that will contain kernel state; instead, we use a RegisterDump.
  456. // Conversely, when the thread isn't blocking the RegisterDump may not be
  457. // valid (fork, exec etc) but the tss will, so we use that instead.
  458. if (!in_kernel()) {
  459. u32* stack = &m_tss.esp;
  460. setup_stack(m_tss, stack);
  461. Scheduler::prepare_to_modify_tss(*this);
  462. m_tss.cs = 0x1b;
  463. m_tss.ds = 0x23;
  464. m_tss.es = 0x23;
  465. m_tss.fs = 0x23;
  466. m_tss.gs = thread_specific_selector() | 3;
  467. m_tss.eip = g_return_to_ring3_from_signal_trampoline.get();
  468. // FIXME: This state is such a hack. It avoids trouble if 'current' is the process receiving a signal.
  469. set_state(Skip1SchedulerPass);
  470. } else {
  471. auto& regs = get_RegisterDump_from_stack();
  472. u32* stack = &regs.esp_if_crossRing;
  473. setup_stack(regs, stack);
  474. regs.eip = g_return_to_ring3_from_signal_trampoline.get();
  475. }
  476. #ifdef SIGNAL_DEBUG
  477. kprintf("signal: Okay, %s(%u) {%s} has been primed with signal handler %w:%x\n", process().name().characters(), pid(), state_string(), m_tss.cs, m_tss.eip);
  478. #endif
  479. return ShouldUnblockThread::Yes;
  480. }
  481. void Thread::set_default_signal_dispositions()
  482. {
  483. // FIXME: Set up all the right default actions. See signal(7).
  484. memset(&m_signal_action_data, 0, sizeof(m_signal_action_data));
  485. m_signal_action_data[SIGCHLD].handler_or_sigaction = VirtualAddress((u32)SIG_IGN);
  486. m_signal_action_data[SIGWINCH].handler_or_sigaction = VirtualAddress((u32)SIG_IGN);
  487. }
  488. void Thread::push_value_on_stack(u32 value)
  489. {
  490. m_tss.esp -= 4;
  491. u32* stack_ptr = (u32*)m_tss.esp;
  492. *stack_ptr = value;
  493. }
  494. RegisterDump& Thread::get_RegisterDump_from_stack()
  495. {
  496. // The userspace registers should be stored at the top of the stack
  497. // We have to subtract 2 because the processor decrements the kernel
  498. // stack before pushing the args.
  499. return *(RegisterDump*)(kernel_stack_top() - sizeof(RegisterDump) - 2);
  500. }
  501. void Thread::make_userspace_stack_for_main_thread(Vector<String> arguments, Vector<String> environment)
  502. {
  503. auto* region = m_process.allocate_region(VirtualAddress(), default_userspace_stack_size, "Stack (Main thread)", PROT_READ | PROT_WRITE, false);
  504. ASSERT(region);
  505. region->set_stack(true);
  506. m_tss.esp = region->vaddr().offset(default_userspace_stack_size).get();
  507. char* stack_base = (char*)region->vaddr().get();
  508. int argc = arguments.size();
  509. char** argv = (char**)stack_base;
  510. char** env = argv + arguments.size() + 1;
  511. char* bufptr = stack_base + (sizeof(char*) * (arguments.size() + 1)) + (sizeof(char*) * (environment.size() + 1));
  512. for (int i = 0; i < arguments.size(); ++i) {
  513. argv[i] = bufptr;
  514. memcpy(bufptr, arguments[i].characters(), arguments[i].length());
  515. bufptr += arguments[i].length();
  516. *(bufptr++) = '\0';
  517. }
  518. argv[arguments.size()] = nullptr;
  519. for (int i = 0; i < environment.size(); ++i) {
  520. env[i] = bufptr;
  521. memcpy(bufptr, environment[i].characters(), environment[i].length());
  522. bufptr += environment[i].length();
  523. *(bufptr++) = '\0';
  524. }
  525. env[environment.size()] = nullptr;
  526. // NOTE: The stack needs to be 16-byte aligned.
  527. push_value_on_stack((u32)env);
  528. push_value_on_stack((u32)argv);
  529. push_value_on_stack((u32)argc);
  530. push_value_on_stack(0);
  531. }
  532. Thread* Thread::clone(Process& process)
  533. {
  534. auto* clone = new Thread(process);
  535. memcpy(clone->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  536. clone->m_signal_mask = m_signal_mask;
  537. memcpy(clone->m_fpu_state, m_fpu_state, sizeof(FPUState));
  538. clone->m_has_used_fpu = m_has_used_fpu;
  539. clone->m_thread_specific_data = m_thread_specific_data;
  540. return clone;
  541. }
  542. void Thread::initialize()
  543. {
  544. Scheduler::initialize();
  545. }
  546. Vector<Thread*> Thread::all_threads()
  547. {
  548. Vector<Thread*> threads;
  549. InterruptDisabler disabler;
  550. threads.ensure_capacity(thread_table().size());
  551. for (auto* thread : thread_table())
  552. threads.unchecked_append(thread);
  553. return threads;
  554. }
  555. bool Thread::is_thread(void* ptr)
  556. {
  557. ASSERT_INTERRUPTS_DISABLED();
  558. return thread_table().contains((Thread*)ptr);
  559. }
  560. void Thread::set_state(State new_state)
  561. {
  562. InterruptDisabler disabler;
  563. if (new_state == Blocked) {
  564. // we should always have a Blocker while blocked
  565. ASSERT(m_blocker != nullptr);
  566. }
  567. m_state = new_state;
  568. if (m_process.pid() != 0) {
  569. Scheduler::update_state_for_thread(*this);
  570. }
  571. }
  572. String Thread::backtrace(ProcessInspectionHandle&) const
  573. {
  574. return backtrace_impl();
  575. }
  576. String Thread::backtrace_impl() const
  577. {
  578. auto& process = const_cast<Process&>(this->process());
  579. ProcessPagingScope paging_scope(process);
  580. struct RecognizedSymbol {
  581. u32 address;
  582. const KSym* ksym;
  583. };
  584. StringBuilder builder;
  585. Vector<RecognizedSymbol, 64> recognized_symbols;
  586. recognized_symbols.append({ tss().eip, ksymbolicate(tss().eip) });
  587. for (u32* stack_ptr = (u32*)frame_ptr(); process.validate_read_from_kernel(VirtualAddress((u32)stack_ptr)); stack_ptr = (u32*)*stack_ptr) {
  588. u32 retaddr = stack_ptr[1];
  589. recognized_symbols.append({ retaddr, ksymbolicate(retaddr) });
  590. }
  591. for (auto& symbol : recognized_symbols) {
  592. if (!symbol.address)
  593. break;
  594. if (!symbol.ksym) {
  595. if (!Scheduler::is_active() && process.elf_loader() && process.elf_loader()->has_symbols())
  596. builder.appendf("%p %s\n", symbol.address, process.elf_loader()->symbolicate(symbol.address).characters());
  597. else
  598. builder.appendf("%p\n", symbol.address);
  599. continue;
  600. }
  601. unsigned offset = symbol.address - symbol.ksym->address;
  602. if (symbol.ksym->address == ksym_highest_address && offset > 4096)
  603. builder.appendf("%p\n", symbol.address);
  604. else
  605. builder.appendf("%p %s +%u\n", symbol.address, demangle(symbol.ksym->name).characters(), offset);
  606. }
  607. return builder.to_string();
  608. }
  609. void Thread::make_thread_specific_region(Badge<Process>)
  610. {
  611. size_t thread_specific_region_alignment = max(process().m_master_tls_alignment, alignof(ThreadSpecificData));
  612. size_t thread_specific_region_size = align_up_to(process().m_master_tls_size, thread_specific_region_alignment) + sizeof(ThreadSpecificData);
  613. auto* region = process().allocate_region({}, thread_specific_region_size, "Thread-specific", PROT_READ | PROT_WRITE, true);
  614. auto* thread_specific_data = (ThreadSpecificData*)region->vaddr().offset(align_up_to(process().m_master_tls_size, thread_specific_region_alignment)).as_ptr();
  615. auto* thread_local_storage = (u8*)((u8*)thread_specific_data) - align_up_to(process().m_master_tls_size, process().m_master_tls_alignment);
  616. m_thread_specific_data = VirtualAddress((u32)thread_specific_data);
  617. thread_specific_data->self = thread_specific_data;
  618. if (process().m_master_tls_size)
  619. memcpy(thread_local_storage, process().m_master_tls_region->vaddr().as_ptr(), process().m_master_tls_size);
  620. }
  621. const LogStream& operator<<(const LogStream& stream, const Thread& value)
  622. {
  623. return stream << value.process().name() << "(" << value.pid() << ":" << value.tid() << ")";
  624. }
  625. const char* to_string(ThreadPriority priority)
  626. {
  627. switch (priority) {
  628. case ThreadPriority::Idle:
  629. return "Idle";
  630. case ThreadPriority::Low:
  631. return "Low";
  632. case ThreadPriority::Normal:
  633. return "Normal";
  634. case ThreadPriority::High:
  635. return "High";
  636. }
  637. dbg() << "to_string(ThreadPriority): Invalid priority: " << (u32)priority;
  638. ASSERT_NOT_REACHED();
  639. return nullptr;
  640. }