Thread.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. u64 Thread::sleep(u32 ticks)
  158. {
  159. ASSERT(state() == Thread::Running);
  160. u64 wakeup_time = g_uptime + ticks;
  161. auto ret = current->block<Thread::SleepBlocker>(wakeup_time);
  162. if (wakeup_time > g_uptime) {
  163. ASSERT(ret == Thread::BlockResult::InterruptedBySignal);
  164. }
  165. return wakeup_time;
  166. }
  167. u64 Thread::sleep_until(u64 wakeup_time)
  168. {
  169. ASSERT(state() == Thread::Running);
  170. auto ret = current->block<Thread::SleepBlocker>(wakeup_time);
  171. if (wakeup_time > g_uptime)
  172. ASSERT(ret == Thread::BlockResult::InterruptedBySignal);
  173. return wakeup_time;
  174. }
  175. const char* Thread::state_string() const
  176. {
  177. switch (state()) {
  178. case Thread::Invalid:
  179. return "Invalid";
  180. case Thread::Runnable:
  181. return "Runnable";
  182. case Thread::Running:
  183. return "Running";
  184. case Thread::Dying:
  185. return "Dying";
  186. case Thread::Dead:
  187. return "Dead";
  188. case Thread::Stopped:
  189. return "Stopped";
  190. case Thread::Skip1SchedulerPass:
  191. return "Skip1";
  192. case Thread::Skip0SchedulerPasses:
  193. return "Skip0";
  194. case Thread::Blocked:
  195. ASSERT(m_blocker != nullptr);
  196. return m_blocker->state_string();
  197. }
  198. kprintf("Thread::state_string(): Invalid state: %u\n", state());
  199. ASSERT_NOT_REACHED();
  200. return nullptr;
  201. }
  202. void Thread::finalize()
  203. {
  204. ASSERT(current == g_finalizer);
  205. dbgprintf("Finalizing Thread %u in %s(%u)\n", tid(), m_process.name().characters(), pid());
  206. set_state(Thread::State::Dead);
  207. if (m_joiner) {
  208. ASSERT(m_joiner->m_joinee == this);
  209. static_cast<JoinBlocker*>(m_joiner->m_blocker)->set_joinee_exit_value(m_exit_value);
  210. m_joiner->m_joinee = nullptr;
  211. // NOTE: We clear the joiner pointer here as well, to be tidy.
  212. m_joiner = nullptr;
  213. }
  214. if (m_dump_backtrace_on_finalization)
  215. dbg() << backtrace_impl();
  216. if (this == &m_process.main_thread()) {
  217. m_process.finalize();
  218. return;
  219. }
  220. delete this;
  221. }
  222. void Thread::finalize_dying_threads()
  223. {
  224. ASSERT(current == g_finalizer);
  225. Vector<Thread*, 32> dying_threads;
  226. {
  227. InterruptDisabler disabler;
  228. for_each_in_state(Thread::State::Dying, [&](Thread& thread) {
  229. dying_threads.append(&thread);
  230. return IterationDecision::Continue;
  231. });
  232. }
  233. for (auto* thread : dying_threads)
  234. thread->finalize();
  235. }
  236. bool Thread::tick()
  237. {
  238. ++m_ticks;
  239. if (tss().cs & 3)
  240. ++m_process.m_ticks_in_user;
  241. else
  242. ++m_process.m_ticks_in_kernel;
  243. return --m_ticks_left;
  244. }
  245. void Thread::send_signal(u8 signal, Process* sender)
  246. {
  247. ASSERT(signal < 32);
  248. InterruptDisabler disabler;
  249. // FIXME: Figure out what to do for masked signals. Should we also ignore them here?
  250. if (should_ignore_signal(signal)) {
  251. dbg() << "signal " << signal << " was ignored by " << process();
  252. return;
  253. }
  254. if (sender)
  255. dbgprintf("signal: %s(%u) sent %d to %s(%u)\n", sender->name().characters(), sender->pid(), signal, process().name().characters(), pid());
  256. else
  257. dbgprintf("signal: kernel sent %d to %s(%u)\n", signal, process().name().characters(), pid());
  258. m_pending_signals |= 1 << (signal - 1);
  259. }
  260. // Certain exceptions, such as SIGSEGV and SIGILL, put a
  261. // thread into a state where the signal handler must be
  262. // invoked immediately, otherwise it will continue to fault.
  263. // This function should be used in an exception handler to
  264. // ensure that when the thread resumes, it's executing in
  265. // the appropriate signal handler.
  266. void Thread::send_urgent_signal_to_self(u8 signal)
  267. {
  268. // FIXME: because of a bug in dispatch_signal we can't
  269. // setup a signal while we are the current thread. Because of
  270. // this we use a work-around where we send the signal and then
  271. // block, allowing the scheduler to properly dispatch the signal
  272. // before the thread is next run.
  273. send_signal(signal, &process());
  274. (void)block<SemiPermanentBlocker>(SemiPermanentBlocker::Reason::Signal);
  275. }
  276. bool Thread::has_unmasked_pending_signals() const
  277. {
  278. return m_pending_signals & ~m_signal_mask;
  279. }
  280. ShouldUnblockThread Thread::dispatch_one_pending_signal()
  281. {
  282. ASSERT_INTERRUPTS_DISABLED();
  283. u32 signal_candidates = m_pending_signals & ~m_signal_mask;
  284. ASSERT(signal_candidates);
  285. u8 signal = 1;
  286. for (; signal < 32; ++signal) {
  287. if (signal_candidates & (1 << (signal - 1))) {
  288. break;
  289. }
  290. }
  291. return dispatch_signal(signal);
  292. }
  293. enum class DefaultSignalAction {
  294. Terminate,
  295. Ignore,
  296. DumpCore,
  297. Stop,
  298. Continue,
  299. };
  300. DefaultSignalAction default_signal_action(u8 signal)
  301. {
  302. ASSERT(signal && signal < NSIG);
  303. switch (signal) {
  304. case SIGHUP:
  305. case SIGINT:
  306. case SIGKILL:
  307. case SIGPIPE:
  308. case SIGALRM:
  309. case SIGUSR1:
  310. case SIGUSR2:
  311. case SIGVTALRM:
  312. case SIGSTKFLT:
  313. case SIGIO:
  314. case SIGPROF:
  315. case SIGTERM:
  316. case SIGPWR:
  317. return DefaultSignalAction::Terminate;
  318. case SIGCHLD:
  319. case SIGURG:
  320. case SIGWINCH:
  321. return DefaultSignalAction::Ignore;
  322. case SIGQUIT:
  323. case SIGILL:
  324. case SIGTRAP:
  325. case SIGABRT:
  326. case SIGBUS:
  327. case SIGFPE:
  328. case SIGSEGV:
  329. case SIGXCPU:
  330. case SIGXFSZ:
  331. case SIGSYS:
  332. return DefaultSignalAction::DumpCore;
  333. case SIGCONT:
  334. return DefaultSignalAction::Continue;
  335. case SIGSTOP:
  336. case SIGTSTP:
  337. case SIGTTIN:
  338. case SIGTTOU:
  339. return DefaultSignalAction::Stop;
  340. }
  341. ASSERT_NOT_REACHED();
  342. }
  343. bool Thread::should_ignore_signal(u8 signal) const
  344. {
  345. ASSERT(signal < 32);
  346. auto& action = m_signal_action_data[signal];
  347. if (action.handler_or_sigaction.is_null())
  348. return default_signal_action(signal) == DefaultSignalAction::Ignore;
  349. if (action.handler_or_sigaction.as_ptr() == SIG_IGN)
  350. return true;
  351. return false;
  352. }
  353. bool Thread::has_signal_handler(u8 signal) const
  354. {
  355. ASSERT(signal < 32);
  356. auto& action = m_signal_action_data[signal];
  357. return !action.handler_or_sigaction.is_null();
  358. }
  359. static void push_value_on_user_stack(u32* stack, u32 data)
  360. {
  361. *stack -= 4;
  362. *(u32*)*stack = data;
  363. }
  364. ShouldUnblockThread Thread::dispatch_signal(u8 signal)
  365. {
  366. ASSERT_INTERRUPTS_DISABLED();
  367. ASSERT(signal > 0 && signal <= 32);
  368. ASSERT(!process().is_ring0());
  369. #ifdef SIGNAL_DEBUG
  370. kprintf("dispatch_signal %s(%u) <- %u\n", process().name().characters(), pid(), signal);
  371. #endif
  372. auto& action = m_signal_action_data[signal];
  373. // FIXME: Implement SA_SIGINFO signal handlers.
  374. ASSERT(!(action.flags & SA_SIGINFO));
  375. // Mark this signal as handled.
  376. m_pending_signals &= ~(1 << (signal - 1));
  377. if (signal == SIGSTOP) {
  378. set_state(Stopped);
  379. return ShouldUnblockThread::No;
  380. }
  381. if (signal == SIGCONT && state() == Stopped)
  382. set_state(Runnable);
  383. auto handler_vaddr = action.handler_or_sigaction;
  384. if (handler_vaddr.is_null()) {
  385. switch (default_signal_action(signal)) {
  386. case DefaultSignalAction::Stop:
  387. set_state(Stopped);
  388. return ShouldUnblockThread::No;
  389. case DefaultSignalAction::DumpCore:
  390. process().for_each_thread([](auto& thread) {
  391. thread.set_dump_backtrace_on_finalization();
  392. return IterationDecision::Continue;
  393. });
  394. [[fallthrough]];
  395. case DefaultSignalAction::Terminate:
  396. m_process.terminate_due_to_signal(signal);
  397. return ShouldUnblockThread::No;
  398. case DefaultSignalAction::Ignore:
  399. ASSERT_NOT_REACHED();
  400. case DefaultSignalAction::Continue:
  401. return ShouldUnblockThread::Yes;
  402. }
  403. ASSERT_NOT_REACHED();
  404. }
  405. if (handler_vaddr.as_ptr() == SIG_IGN) {
  406. #ifdef SIGNAL_DEBUG
  407. kprintf("%s(%u) ignored signal %u\n", process().name().characters(), pid(), signal);
  408. #endif
  409. return ShouldUnblockThread::Yes;
  410. }
  411. ProcessPagingScope paging_scope(m_process);
  412. u32 old_signal_mask = m_signal_mask;
  413. u32 new_signal_mask = action.mask;
  414. if (action.flags & SA_NODEFER)
  415. new_signal_mask &= ~(1 << (signal - 1));
  416. else
  417. new_signal_mask |= 1 << (signal - 1);
  418. m_signal_mask |= new_signal_mask;
  419. auto setup_stack = [&]<typename ThreadState>(ThreadState state, u32 * stack)
  420. {
  421. u32 old_esp = *stack;
  422. u32 ret_eip = state.eip;
  423. u32 ret_eflags = state.eflags;
  424. // Align the stack to 16 bytes.
  425. // Note that we push 56 bytes (4 * 14) on to the stack,
  426. // so we need to account for this here.
  427. u32 stack_alignment = (*stack - 56) % 16;
  428. *stack -= stack_alignment;
  429. push_value_on_user_stack(stack, ret_eflags);
  430. push_value_on_user_stack(stack, ret_eip);
  431. push_value_on_user_stack(stack, state.eax);
  432. push_value_on_user_stack(stack, state.ecx);
  433. push_value_on_user_stack(stack, state.edx);
  434. push_value_on_user_stack(stack, state.ebx);
  435. push_value_on_user_stack(stack, old_esp);
  436. push_value_on_user_stack(stack, state.ebp);
  437. push_value_on_user_stack(stack, state.esi);
  438. push_value_on_user_stack(stack, state.edi);
  439. // PUSH old_signal_mask
  440. push_value_on_user_stack(stack, old_signal_mask);
  441. push_value_on_user_stack(stack, signal);
  442. push_value_on_user_stack(stack, handler_vaddr.get());
  443. push_value_on_user_stack(stack, 0); //push fake return address
  444. ASSERT((*stack % 16) == 0);
  445. };
  446. // We now place the thread state on the userspace stack.
  447. // Note that when we are in the kernel (ie. blocking) we cannot use the
  448. // tss, as that will contain kernel state; instead, we use a RegisterDump.
  449. // Conversely, when the thread isn't blocking the RegisterDump may not be
  450. // valid (fork, exec etc) but the tss will, so we use that instead.
  451. if (!in_kernel()) {
  452. u32* stack = &m_tss.esp;
  453. setup_stack(m_tss, stack);
  454. Scheduler::prepare_to_modify_tss(*this);
  455. m_tss.cs = 0x1b;
  456. m_tss.ds = 0x23;
  457. m_tss.es = 0x23;
  458. m_tss.fs = 0x23;
  459. m_tss.gs = thread_specific_selector() | 3;
  460. m_tss.eip = g_return_to_ring3_from_signal_trampoline.get();
  461. // FIXME: This state is such a hack. It avoids trouble if 'current' is the process receiving a signal.
  462. set_state(Skip1SchedulerPass);
  463. } else {
  464. auto& regs = get_RegisterDump_from_stack();
  465. u32* stack = &regs.esp_if_crossRing;
  466. setup_stack(regs, stack);
  467. regs.eip = g_return_to_ring3_from_signal_trampoline.get();
  468. }
  469. #ifdef SIGNAL_DEBUG
  470. 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);
  471. #endif
  472. return ShouldUnblockThread::Yes;
  473. }
  474. void Thread::set_default_signal_dispositions()
  475. {
  476. // FIXME: Set up all the right default actions. See signal(7).
  477. memset(&m_signal_action_data, 0, sizeof(m_signal_action_data));
  478. m_signal_action_data[SIGCHLD].handler_or_sigaction = VirtualAddress((u32)SIG_IGN);
  479. m_signal_action_data[SIGWINCH].handler_or_sigaction = VirtualAddress((u32)SIG_IGN);
  480. }
  481. void Thread::push_value_on_stack(u32 value)
  482. {
  483. m_tss.esp -= 4;
  484. u32* stack_ptr = (u32*)m_tss.esp;
  485. *stack_ptr = value;
  486. }
  487. RegisterDump& Thread::get_RegisterDump_from_stack()
  488. {
  489. // The userspace registers should be stored at the top of the stack
  490. // We have to subtract 2 because the processor decrements the kernel
  491. // stack before pushing the args.
  492. return *(RegisterDump*)(kernel_stack_top() - sizeof(RegisterDump) - 2);
  493. }
  494. void Thread::make_userspace_stack_for_main_thread(Vector<String> arguments, Vector<String> environment)
  495. {
  496. auto* region = m_process.allocate_region(VirtualAddress(), default_userspace_stack_size, "Stack (Main thread)", PROT_READ | PROT_WRITE, false);
  497. ASSERT(region);
  498. region->set_stack(true);
  499. m_tss.esp = region->vaddr().offset(default_userspace_stack_size).get();
  500. char* stack_base = (char*)region->vaddr().get();
  501. int argc = arguments.size();
  502. char** argv = (char**)stack_base;
  503. char** env = argv + arguments.size() + 1;
  504. char* bufptr = stack_base + (sizeof(char*) * (arguments.size() + 1)) + (sizeof(char*) * (environment.size() + 1));
  505. for (int i = 0; i < arguments.size(); ++i) {
  506. argv[i] = bufptr;
  507. memcpy(bufptr, arguments[i].characters(), arguments[i].length());
  508. bufptr += arguments[i].length();
  509. *(bufptr++) = '\0';
  510. }
  511. argv[arguments.size()] = nullptr;
  512. for (int i = 0; i < environment.size(); ++i) {
  513. env[i] = bufptr;
  514. memcpy(bufptr, environment[i].characters(), environment[i].length());
  515. bufptr += environment[i].length();
  516. *(bufptr++) = '\0';
  517. }
  518. env[environment.size()] = nullptr;
  519. // NOTE: The stack needs to be 16-byte aligned.
  520. push_value_on_stack((u32)env);
  521. push_value_on_stack((u32)argv);
  522. push_value_on_stack((u32)argc);
  523. push_value_on_stack(0);
  524. }
  525. Thread* Thread::clone(Process& process)
  526. {
  527. auto* clone = new Thread(process);
  528. memcpy(clone->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  529. clone->m_signal_mask = m_signal_mask;
  530. memcpy(clone->m_fpu_state, m_fpu_state, sizeof(FPUState));
  531. clone->m_has_used_fpu = m_has_used_fpu;
  532. clone->m_thread_specific_data = m_thread_specific_data;
  533. return clone;
  534. }
  535. void Thread::initialize()
  536. {
  537. Scheduler::initialize();
  538. }
  539. Vector<Thread*> Thread::all_threads()
  540. {
  541. Vector<Thread*> threads;
  542. InterruptDisabler disabler;
  543. threads.ensure_capacity(thread_table().size());
  544. for (auto* thread : thread_table())
  545. threads.unchecked_append(thread);
  546. return threads;
  547. }
  548. bool Thread::is_thread(void* ptr)
  549. {
  550. ASSERT_INTERRUPTS_DISABLED();
  551. return thread_table().contains((Thread*)ptr);
  552. }
  553. void Thread::set_state(State new_state)
  554. {
  555. InterruptDisabler disabler;
  556. if (new_state == Blocked) {
  557. // we should always have a Blocker while blocked
  558. ASSERT(m_blocker != nullptr);
  559. }
  560. m_state = new_state;
  561. if (m_process.pid() != 0) {
  562. Scheduler::update_state_for_thread(*this);
  563. }
  564. }
  565. String Thread::backtrace(ProcessInspectionHandle&) const
  566. {
  567. return backtrace_impl();
  568. }
  569. String Thread::backtrace_impl() const
  570. {
  571. auto& process = const_cast<Process&>(this->process());
  572. ProcessPagingScope paging_scope(process);
  573. struct RecognizedSymbol {
  574. u32 address;
  575. const KSym* ksym;
  576. };
  577. StringBuilder builder;
  578. Vector<RecognizedSymbol, 64> recognized_symbols;
  579. recognized_symbols.append({ tss().eip, ksymbolicate(tss().eip) });
  580. for (u32* stack_ptr = (u32*)frame_ptr(); process.validate_read_from_kernel(VirtualAddress((u32)stack_ptr)); stack_ptr = (u32*)*stack_ptr) {
  581. u32 retaddr = stack_ptr[1];
  582. recognized_symbols.append({ retaddr, ksymbolicate(retaddr) });
  583. }
  584. for (auto& symbol : recognized_symbols) {
  585. if (!symbol.address)
  586. break;
  587. if (!symbol.ksym) {
  588. if (!Scheduler::is_active() && process.elf_loader() && process.elf_loader()->has_symbols())
  589. builder.appendf("%p %s\n", symbol.address, process.elf_loader()->symbolicate(symbol.address).characters());
  590. else
  591. builder.appendf("%p\n", symbol.address);
  592. continue;
  593. }
  594. unsigned offset = symbol.address - symbol.ksym->address;
  595. if (symbol.ksym->address == ksym_highest_address && offset > 4096)
  596. builder.appendf("%p\n", symbol.address);
  597. else
  598. builder.appendf("%p %s +%u\n", symbol.address, demangle(symbol.ksym->name).characters(), offset);
  599. }
  600. return builder.to_string();
  601. }
  602. void Thread::make_thread_specific_region(Badge<Process>)
  603. {
  604. size_t thread_specific_region_alignment = max(process().m_master_tls_alignment, alignof(ThreadSpecificData));
  605. size_t thread_specific_region_size = align_up_to(process().m_master_tls_size, thread_specific_region_alignment) + sizeof(ThreadSpecificData);
  606. auto* region = process().allocate_region({}, thread_specific_region_size, "Thread-specific", PROT_READ | PROT_WRITE, true);
  607. auto* thread_specific_data = (ThreadSpecificData*)region->vaddr().offset(align_up_to(process().m_master_tls_size, thread_specific_region_alignment)).as_ptr();
  608. auto* thread_local_storage = (u8*)((u8*)thread_specific_data) - align_up_to(process().m_master_tls_size, process().m_master_tls_alignment);
  609. m_thread_specific_data = VirtualAddress((u32)thread_specific_data);
  610. thread_specific_data->self = thread_specific_data;
  611. if (process().m_master_tls_size)
  612. memcpy(thread_local_storage, process().m_master_tls_region->vaddr().as_ptr(), process().m_master_tls_size);
  613. }
  614. const LogStream& operator<<(const LogStream& stream, const Thread& value)
  615. {
  616. return stream << value.process().name() << "(" << value.pid() << ":" << value.tid() << ")";
  617. }
  618. const char* to_string(ThreadPriority priority)
  619. {
  620. switch (priority) {
  621. case ThreadPriority::Idle:
  622. return "Idle";
  623. case ThreadPriority::Low:
  624. return "Low";
  625. case ThreadPriority::Normal:
  626. return "Normal";
  627. case ThreadPriority::High:
  628. return "High";
  629. }
  630. dbg() << "to_string(ThreadPriority): Invalid priority: " << (u32)priority;
  631. ASSERT_NOT_REACHED();
  632. return nullptr;
  633. }