Thread.cpp 22 KB

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