Thread.cpp 28 KB

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