Thread.cpp 27 KB

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