Thread.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. #include <AK/Demangle.h>
  2. #include <AK/StringBuilder.h>
  3. #include <Kernel/Arch/i386/CPU.h>
  4. #include <Kernel/FileSystem/FileDescription.h>
  5. #include <Kernel/Process.h>
  6. #include <Kernel/Scheduler.h>
  7. #include <Kernel/Thread.h>
  8. #include <Kernel/VM/MemoryManager.h>
  9. #include <LibC/signal_numbers.h>
  10. #include <LibELF/ELFLoader.h>
  11. //#define SIGNAL_DEBUG
  12. static FPUState s_clean_fpu_state;
  13. u16 thread_specific_selector()
  14. {
  15. static u16 selector;
  16. if (!selector) {
  17. selector = gdt_alloc_entry();
  18. auto& descriptor = get_gdt_entry(selector);
  19. descriptor.dpl = 3;
  20. descriptor.segment_present = 1;
  21. descriptor.granularity = 0;
  22. descriptor.zero = 0;
  23. descriptor.operation_size = 1;
  24. descriptor.descriptor_type = 1;
  25. descriptor.type = 2;
  26. }
  27. return selector;
  28. }
  29. Descriptor& thread_specific_descriptor()
  30. {
  31. return get_gdt_entry(thread_specific_selector());
  32. }
  33. HashTable<Thread*>& thread_table()
  34. {
  35. ASSERT_INTERRUPTS_DISABLED();
  36. static HashTable<Thread*>* table;
  37. if (!table)
  38. table = new HashTable<Thread*>;
  39. return *table;
  40. }
  41. Thread::Thread(Process& process)
  42. : m_process(process)
  43. , m_name(process.name())
  44. {
  45. if (m_process.m_thread_count == 0) {
  46. // First thread gets TID == PID
  47. m_tid = process.pid();
  48. } else {
  49. m_tid = Process::allocate_pid();
  50. }
  51. process.m_thread_count++;
  52. dbgprintf("Thread{%p}: New thread TID=%u in %s(%u)\n", this, m_tid, process.name().characters(), process.pid());
  53. set_default_signal_dispositions();
  54. m_fpu_state = (FPUState*)kmalloc_aligned(sizeof(FPUState), 16);
  55. memcpy(m_fpu_state, &s_clean_fpu_state, sizeof(FPUState));
  56. memset(&m_tss, 0, sizeof(m_tss));
  57. m_tss.iomapbase = sizeof(TSS32);
  58. // Only IF is set when a process boots.
  59. m_tss.eflags = 0x0202;
  60. u16 cs, ds, ss, gs;
  61. if (m_process.is_ring0()) {
  62. cs = 0x08;
  63. ds = 0x10;
  64. ss = 0x10;
  65. gs = 0;
  66. } else {
  67. cs = 0x1b;
  68. ds = 0x23;
  69. ss = 0x23;
  70. gs = thread_specific_selector() | 3;
  71. }
  72. m_tss.ds = ds;
  73. m_tss.es = ds;
  74. m_tss.fs = ds;
  75. m_tss.gs = gs;
  76. m_tss.ss = ss;
  77. m_tss.cs = cs;
  78. m_tss.cr3 = m_process.page_directory().cr3();
  79. if (m_process.is_ring0()) {
  80. 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);
  81. m_kernel_stack_region->set_stack(true);
  82. m_kernel_stack_base = m_kernel_stack_region->vaddr().get();
  83. m_kernel_stack_top = m_kernel_stack_region->vaddr().offset(default_kernel_stack_size).get() & 0xfffffff8u;
  84. m_tss.esp = m_kernel_stack_top;
  85. } else {
  86. // Ring3 processes need a separate stack for Ring0.
  87. 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);
  88. m_kernel_stack_region->set_stack(true);
  89. m_kernel_stack_base = m_kernel_stack_region->vaddr().get();
  90. m_kernel_stack_top = m_kernel_stack_region->vaddr().offset(default_kernel_stack_size).get() & 0xfffffff8u;
  91. m_tss.ss0 = 0x10;
  92. m_tss.esp0 = m_kernel_stack_top;
  93. }
  94. // HACK: Ring2 SS in the TSS is the current PID.
  95. m_tss.ss2 = m_process.pid();
  96. m_far_ptr.offset = 0x98765432;
  97. if (m_process.pid() != 0) {
  98. InterruptDisabler disabler;
  99. thread_table().set(this);
  100. Scheduler::init_thread(*this);
  101. }
  102. }
  103. Thread::~Thread()
  104. {
  105. dbgprintf("~Thread{%p}\n", this);
  106. kfree_aligned(m_fpu_state);
  107. {
  108. InterruptDisabler disabler;
  109. thread_table().remove(this);
  110. }
  111. if (selector())
  112. gdt_free_entry(selector());
  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. copy_to_user((u32*)*stack, &data, sizeof(u32));
  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. copy_to_user(stack_ptr, &value, sizeof(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. SmapDisabler disabler;
  532. for (int i = 0; i < arguments.size(); ++i) {
  533. argv[i] = bufptr;
  534. memcpy(bufptr, arguments[i].characters(), arguments[i].length());
  535. bufptr += arguments[i].length();
  536. *(bufptr++) = '\0';
  537. }
  538. argv[arguments.size()] = nullptr;
  539. for (int i = 0; i < environment.size(); ++i) {
  540. env[i] = bufptr;
  541. memcpy(bufptr, environment[i].characters(), environment[i].length());
  542. bufptr += environment[i].length();
  543. *(bufptr++) = '\0';
  544. }
  545. env[environment.size()] = nullptr;
  546. auto push_on_new_stack = [&new_esp](u32 value) {
  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_thread_specific_data = m_thread_specific_data;
  565. return clone;
  566. }
  567. void Thread::initialize()
  568. {
  569. Scheduler::initialize();
  570. asm volatile("fninit");
  571. asm volatile("fxsave %0"
  572. : "=m"(s_clean_fpu_state));
  573. }
  574. Vector<Thread*> Thread::all_threads()
  575. {
  576. Vector<Thread*> threads;
  577. InterruptDisabler disabler;
  578. threads.ensure_capacity(thread_table().size());
  579. for (auto* thread : thread_table())
  580. threads.unchecked_append(thread);
  581. return threads;
  582. }
  583. bool Thread::is_thread(void* ptr)
  584. {
  585. ASSERT_INTERRUPTS_DISABLED();
  586. return thread_table().contains((Thread*)ptr);
  587. }
  588. void Thread::set_state(State new_state)
  589. {
  590. InterruptDisabler disabler;
  591. if (new_state == m_state)
  592. return;
  593. if (new_state == Blocked) {
  594. // we should always have a Blocker while blocked
  595. ASSERT(m_blocker != nullptr);
  596. }
  597. m_state = new_state;
  598. if (m_process.pid() != 0) {
  599. Scheduler::update_state_for_thread(*this);
  600. }
  601. if (new_state == Dying)
  602. g_finalizer_wait_queue->wake_all();
  603. }
  604. String Thread::backtrace(ProcessInspectionHandle&) const
  605. {
  606. return backtrace_impl();
  607. }
  608. String Thread::backtrace_impl() const
  609. {
  610. SmapDisabler disabler;
  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. bool mask_kernel_addresses = !current->process().is_superuser();
  625. for (auto& symbol : recognized_symbols) {
  626. if (!symbol.address)
  627. break;
  628. if (!symbol.ksym) {
  629. if (!is_user_address(VirtualAddress(symbol.address))) {
  630. builder.append("0xdeadc0de\n");
  631. } else {
  632. if (!Scheduler::is_active() && process.elf_loader() && process.elf_loader()->has_symbols())
  633. builder.appendf("%p %s\n", symbol.address, process.elf_loader()->symbolicate(symbol.address).characters());
  634. else
  635. builder.appendf("%p\n", symbol.address);
  636. }
  637. continue;
  638. }
  639. unsigned offset = symbol.address - symbol.ksym->address;
  640. if (symbol.ksym->address == ksym_highest_address && offset > 4096) {
  641. builder.appendf("%p\n", mask_kernel_addresses ? 0xdeadc0de : symbol.address);
  642. } else {
  643. builder.appendf("%p %s +%u\n", mask_kernel_addresses ? 0xdeadc0de : symbol.address, demangle(symbol.ksym->name).characters(), offset);
  644. }
  645. }
  646. return builder.to_string();
  647. }
  648. Vector<u32> Thread::raw_backtrace(u32 ebp) const
  649. {
  650. auto& process = const_cast<Process&>(this->process());
  651. ProcessPagingScope paging_scope(process);
  652. Vector<u32> backtrace;
  653. backtrace.append(ebp);
  654. for (u32* stack_ptr = (u32*)ebp; process.validate_read_from_kernel(VirtualAddress((u32)stack_ptr), sizeof(void*) * 2); stack_ptr = (u32*)*stack_ptr) {
  655. u32 retaddr = stack_ptr[1];
  656. backtrace.append(retaddr);
  657. }
  658. return backtrace;
  659. }
  660. void Thread::make_thread_specific_region(Badge<Process>)
  661. {
  662. size_t thread_specific_region_alignment = max(process().m_master_tls_alignment, alignof(ThreadSpecificData));
  663. size_t thread_specific_region_size = align_up_to(process().m_master_tls_size, thread_specific_region_alignment) + sizeof(ThreadSpecificData);
  664. auto* region = process().allocate_region({}, thread_specific_region_size, "Thread-specific", PROT_READ | PROT_WRITE, true);
  665. SmapDisabler disabler;
  666. auto* thread_specific_data = (ThreadSpecificData*)region->vaddr().offset(align_up_to(process().m_master_tls_size, thread_specific_region_alignment)).as_ptr();
  667. auto* thread_local_storage = (u8*)((u8*)thread_specific_data) - align_up_to(process().m_master_tls_size, process().m_master_tls_alignment);
  668. m_thread_specific_data = VirtualAddress((u32)thread_specific_data);
  669. thread_specific_data->self = thread_specific_data;
  670. if (process().m_master_tls_size)
  671. memcpy(thread_local_storage, process().m_master_tls_region->vaddr().as_ptr(), process().m_master_tls_size);
  672. }
  673. const LogStream& operator<<(const LogStream& stream, const Thread& value)
  674. {
  675. return stream << value.process().name() << "(" << value.pid() << ":" << value.tid() << ")";
  676. }
  677. void Thread::wait_on(WaitQueue& queue, Thread* beneficiary, const char* reason)
  678. {
  679. bool did_unlock = unlock_process_if_locked();
  680. cli();
  681. set_state(State::Queued);
  682. queue.enqueue(*current);
  683. // Yield and wait for the queue to wake us up again.
  684. if (beneficiary)
  685. Scheduler::donate_to(beneficiary, reason);
  686. else
  687. Scheduler::yield();
  688. // We've unblocked, relock the process if needed and carry on.
  689. if (did_unlock)
  690. relock_process();
  691. }
  692. void Thread::wake_from_queue()
  693. {
  694. ASSERT(state() == State::Queued);
  695. set_state(State::Runnable);
  696. }
  697. Thread* Thread::from_tid(int tid)
  698. {
  699. InterruptDisabler disabler;
  700. Thread* found_thread = nullptr;
  701. Thread::for_each([&](auto& thread) {
  702. if (thread.tid() == tid) {
  703. found_thread = &thread;
  704. return IterationDecision::Break;
  705. }
  706. return IterationDecision::Continue;
  707. });
  708. return found_thread;
  709. }