Thread.cpp 27 KB

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