Thread.cpp 24 KB

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