Thread.cpp 22 KB

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