Thread.cpp 22 KB

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