Thread.cpp 23 KB

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