Thread.cpp 24 KB

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