Thread.cpp 28 KB

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