Thread.cpp 27 KB

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