Thread.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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/ELFLoader.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. m_stop_state = m_state;
  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. m_stop_state = m_state;
  469. set_state(Stopped);
  470. return ShouldUnblockThread::No;
  471. }
  472. thread_tracer->unset_signal(signal);
  473. }
  474. }
  475. auto handler_vaddr = action.handler_or_sigaction;
  476. if (handler_vaddr.is_null()) {
  477. switch (default_signal_action(signal)) {
  478. case DefaultSignalAction::Stop:
  479. m_stop_signal = signal;
  480. set_state(Stopped);
  481. return ShouldUnblockThread::No;
  482. case DefaultSignalAction::DumpCore:
  483. process().for_each_thread([](auto& thread) {
  484. thread.set_dump_backtrace_on_finalization();
  485. return IterationDecision::Continue;
  486. });
  487. [[fallthrough]];
  488. case DefaultSignalAction::Terminate:
  489. m_process.terminate_due_to_signal(signal);
  490. return ShouldUnblockThread::No;
  491. case DefaultSignalAction::Ignore:
  492. ASSERT_NOT_REACHED();
  493. case DefaultSignalAction::Continue:
  494. return ShouldUnblockThread::Yes;
  495. }
  496. ASSERT_NOT_REACHED();
  497. }
  498. if (handler_vaddr.as_ptr() == SIG_IGN) {
  499. #ifdef SIGNAL_DEBUG
  500. klog() << "ignored signal " << signal;
  501. #endif
  502. return ShouldUnblockThread::Yes;
  503. }
  504. ProcessPagingScope paging_scope(m_process);
  505. u32 old_signal_mask = m_signal_mask;
  506. u32 new_signal_mask = action.mask;
  507. if (action.flags & SA_NODEFER)
  508. new_signal_mask &= ~(1 << (signal - 1));
  509. else
  510. new_signal_mask |= 1 << (signal - 1);
  511. m_signal_mask |= new_signal_mask;
  512. auto setup_stack = [&]<typename ThreadState>(ThreadState state, u32 * stack)
  513. {
  514. u32 old_esp = *stack;
  515. u32 ret_eip = state.eip;
  516. u32 ret_eflags = state.eflags;
  517. // Align the stack to 16 bytes.
  518. // Note that we push 56 bytes (4 * 14) on to the stack,
  519. // so we need to account for this here.
  520. u32 stack_alignment = (*stack - 56) % 16;
  521. *stack -= stack_alignment;
  522. push_value_on_user_stack(stack, ret_eflags);
  523. push_value_on_user_stack(stack, ret_eip);
  524. push_value_on_user_stack(stack, state.eax);
  525. push_value_on_user_stack(stack, state.ecx);
  526. push_value_on_user_stack(stack, state.edx);
  527. push_value_on_user_stack(stack, state.ebx);
  528. push_value_on_user_stack(stack, old_esp);
  529. push_value_on_user_stack(stack, state.ebp);
  530. push_value_on_user_stack(stack, state.esi);
  531. push_value_on_user_stack(stack, state.edi);
  532. // PUSH old_signal_mask
  533. push_value_on_user_stack(stack, old_signal_mask);
  534. push_value_on_user_stack(stack, signal);
  535. push_value_on_user_stack(stack, handler_vaddr.get());
  536. push_value_on_user_stack(stack, 0); //push fake return address
  537. ASSERT((*stack % 16) == 0);
  538. };
  539. // We now place the thread state on the userspace stack.
  540. // Note that when we are in the kernel (ie. blocking) we cannot use the
  541. // tss, as that will contain kernel state; instead, we use a RegisterState.
  542. // Conversely, when the thread isn't blocking the RegisterState may not be
  543. // valid (fork, exec etc) but the tss will, so we use that instead.
  544. if (!in_kernel()) {
  545. u32* stack = &m_tss.esp;
  546. setup_stack(m_tss, stack);
  547. Scheduler::prepare_to_modify_tss(*this);
  548. m_tss.cs = 0x1b;
  549. m_tss.ds = 0x23;
  550. m_tss.es = 0x23;
  551. m_tss.fs = 0x23;
  552. m_tss.gs = thread_specific_selector() | 3;
  553. m_tss.eip = g_return_to_ring3_from_signal_trampoline.get();
  554. // FIXME: This state is such a hack. It avoids trouble if 'current' is the process receiving a signal.
  555. set_state(Skip1SchedulerPass);
  556. } else {
  557. auto& regs = get_register_dump_from_stack();
  558. u32* stack = &regs.userspace_esp;
  559. setup_stack(regs, stack);
  560. regs.eip = g_return_to_ring3_from_signal_trampoline.get();
  561. }
  562. #ifdef SIGNAL_DEBUG
  563. klog() << "signal: Okay, {" << state_string() << "} has been primed with signal handler " << String::format("%w", m_tss.cs) << ":" << String::format("%x", m_tss.eip);
  564. #endif
  565. return ShouldUnblockThread::Yes;
  566. }
  567. void Thread::set_default_signal_dispositions()
  568. {
  569. // FIXME: Set up all the right default actions. See signal(7).
  570. memset(&m_signal_action_data, 0, sizeof(m_signal_action_data));
  571. m_signal_action_data[SIGCHLD].handler_or_sigaction = VirtualAddress(SIG_IGN);
  572. m_signal_action_data[SIGWINCH].handler_or_sigaction = VirtualAddress(SIG_IGN);
  573. }
  574. void Thread::push_value_on_stack(FlatPtr value)
  575. {
  576. m_tss.esp -= 4;
  577. FlatPtr* stack_ptr = (FlatPtr*)m_tss.esp;
  578. copy_to_user(stack_ptr, &value);
  579. }
  580. RegisterState& Thread::get_register_dump_from_stack()
  581. {
  582. // The userspace registers should be stored at the top of the stack
  583. // We have to subtract 2 because the processor decrements the kernel
  584. // stack before pushing the args.
  585. return *(RegisterState*)(kernel_stack_top() - sizeof(RegisterState));
  586. }
  587. u32 Thread::make_userspace_stack_for_main_thread(Vector<String> arguments, Vector<String> environment)
  588. {
  589. auto* region = m_process.allocate_region(VirtualAddress(), default_userspace_stack_size, "Stack (Main thread)", PROT_READ | PROT_WRITE, false);
  590. ASSERT(region);
  591. region->set_stack(true);
  592. u32 new_esp = region->vaddr().offset(default_userspace_stack_size).get();
  593. // FIXME: This is weird, we put the argument contents at the base of the stack,
  594. // and the argument pointers at the top? Why?
  595. char* stack_base = (char*)region->vaddr().get();
  596. int argc = arguments.size();
  597. char** argv = (char**)stack_base;
  598. char** env = argv + arguments.size() + 1;
  599. char* bufptr = stack_base + (sizeof(char*) * (arguments.size() + 1)) + (sizeof(char*) * (environment.size() + 1));
  600. SmapDisabler disabler;
  601. for (size_t i = 0; i < arguments.size(); ++i) {
  602. argv[i] = bufptr;
  603. memcpy(bufptr, arguments[i].characters(), arguments[i].length());
  604. bufptr += arguments[i].length();
  605. *(bufptr++) = '\0';
  606. }
  607. argv[arguments.size()] = nullptr;
  608. for (size_t i = 0; i < environment.size(); ++i) {
  609. env[i] = bufptr;
  610. memcpy(bufptr, environment[i].characters(), environment[i].length());
  611. bufptr += environment[i].length();
  612. *(bufptr++) = '\0';
  613. }
  614. env[environment.size()] = nullptr;
  615. auto push_on_new_stack = [&new_esp](u32 value) {
  616. new_esp -= 4;
  617. u32* stack_ptr = (u32*)new_esp;
  618. *stack_ptr = value;
  619. };
  620. // NOTE: The stack needs to be 16-byte aligned.
  621. push_on_new_stack((FlatPtr)env);
  622. push_on_new_stack((FlatPtr)argv);
  623. push_on_new_stack((FlatPtr)argc);
  624. push_on_new_stack(0);
  625. return new_esp;
  626. }
  627. Thread* Thread::clone(Process& process)
  628. {
  629. auto* clone = new Thread(process);
  630. memcpy(clone->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  631. clone->m_signal_mask = m_signal_mask;
  632. memcpy(clone->m_fpu_state, m_fpu_state, sizeof(FPUState));
  633. clone->m_thread_specific_data = m_thread_specific_data;
  634. return clone;
  635. }
  636. void Thread::initialize()
  637. {
  638. Scheduler::initialize();
  639. asm volatile("fninit");
  640. asm volatile("fxsave %0"
  641. : "=m"(s_clean_fpu_state));
  642. }
  643. Vector<Thread*> Thread::all_threads()
  644. {
  645. Vector<Thread*> threads;
  646. InterruptDisabler disabler;
  647. threads.ensure_capacity(thread_table().size());
  648. for (auto* thread : thread_table())
  649. threads.unchecked_append(thread);
  650. return threads;
  651. }
  652. bool Thread::is_thread(void* ptr)
  653. {
  654. ASSERT_INTERRUPTS_DISABLED();
  655. return thread_table().contains((Thread*)ptr);
  656. }
  657. void Thread::set_state(State new_state)
  658. {
  659. InterruptDisabler disabler;
  660. if (new_state == m_state)
  661. return;
  662. if (new_state == Blocked) {
  663. // we should always have a Blocker while blocked
  664. ASSERT(m_blocker != nullptr);
  665. }
  666. m_state = new_state;
  667. if (m_process.pid() != 0) {
  668. Scheduler::update_state_for_thread(*this);
  669. }
  670. if (new_state == Dying) {
  671. g_finalizer_has_work = true;
  672. g_finalizer_wait_queue->wake_all();
  673. }
  674. }
  675. String Thread::backtrace(ProcessInspectionHandle&) const
  676. {
  677. return backtrace_impl();
  678. }
  679. struct RecognizedSymbol {
  680. u32 address;
  681. const KSym* ksym;
  682. };
  683. static bool symbolicate(const RecognizedSymbol& symbol, const Process& process, StringBuilder& builder, Process::ELFBundle* elf_bundle)
  684. {
  685. if (!symbol.address)
  686. return false;
  687. bool mask_kernel_addresses = !process.is_superuser();
  688. if (!symbol.ksym) {
  689. if (!is_user_address(VirtualAddress(symbol.address))) {
  690. builder.append("0xdeadc0de\n");
  691. } else {
  692. if (!Scheduler::is_active() && elf_bundle && elf_bundle->elf_loader->has_symbols())
  693. builder.appendf("%p %s\n", symbol.address, elf_bundle->elf_loader->symbolicate(symbol.address).characters());
  694. else
  695. builder.appendf("%p\n", symbol.address);
  696. }
  697. return true;
  698. }
  699. unsigned offset = symbol.address - symbol.ksym->address;
  700. if (symbol.ksym->address == ksym_highest_address && offset > 4096) {
  701. builder.appendf("%p\n", mask_kernel_addresses ? 0xdeadc0de : symbol.address);
  702. } else {
  703. builder.appendf("%p %s +%u\n", mask_kernel_addresses ? 0xdeadc0de : symbol.address, demangle(symbol.ksym->name).characters(), offset);
  704. }
  705. return true;
  706. }
  707. String Thread::backtrace_impl() const
  708. {
  709. Vector<RecognizedSymbol, 128> recognized_symbols;
  710. u32 start_frame;
  711. if (current == this) {
  712. asm volatile("movl %%ebp, %%eax"
  713. : "=a"(start_frame));
  714. } else {
  715. start_frame = frame_ptr();
  716. recognized_symbols.append({ tss().eip, ksymbolicate(tss().eip) });
  717. }
  718. auto& process = const_cast<Process&>(this->process());
  719. auto elf_bundle = process.elf_bundle();
  720. ProcessPagingScope paging_scope(process);
  721. FlatPtr stack_ptr = start_frame;
  722. for (;;) {
  723. if (!process.validate_read_from_kernel(VirtualAddress(stack_ptr), sizeof(void*) * 2))
  724. break;
  725. FlatPtr retaddr;
  726. if (is_user_range(VirtualAddress(stack_ptr), sizeof(FlatPtr) * 2)) {
  727. copy_from_user(&retaddr, &((FlatPtr*)stack_ptr)[1]);
  728. recognized_symbols.append({ retaddr, ksymbolicate(retaddr) });
  729. copy_from_user(&stack_ptr, (FlatPtr*)stack_ptr);
  730. } else {
  731. memcpy(&retaddr, &((FlatPtr*)stack_ptr)[1], sizeof(FlatPtr));
  732. recognized_symbols.append({ retaddr, ksymbolicate(retaddr) });
  733. memcpy(&stack_ptr, (FlatPtr*)stack_ptr, sizeof(FlatPtr));
  734. }
  735. }
  736. StringBuilder builder;
  737. for (auto& symbol : recognized_symbols) {
  738. if (!symbolicate(symbol, process, builder, elf_bundle.ptr()))
  739. break;
  740. }
  741. return builder.to_string();
  742. }
  743. Vector<FlatPtr> Thread::raw_backtrace(FlatPtr ebp) const
  744. {
  745. InterruptDisabler disabler;
  746. auto& process = const_cast<Process&>(this->process());
  747. ProcessPagingScope paging_scope(process);
  748. Vector<FlatPtr, Profiling::max_stack_frame_count> backtrace;
  749. backtrace.append(ebp);
  750. 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) {
  751. FlatPtr retaddr = stack_ptr[1];
  752. backtrace.append(retaddr);
  753. if (backtrace.size() == Profiling::max_stack_frame_count)
  754. break;
  755. }
  756. return backtrace;
  757. }
  758. void Thread::make_thread_specific_region(Badge<Process>)
  759. {
  760. size_t thread_specific_region_alignment = max(process().m_master_tls_alignment, alignof(ThreadSpecificData));
  761. size_t thread_specific_region_size = align_up_to(process().m_master_tls_size, thread_specific_region_alignment) + sizeof(ThreadSpecificData);
  762. auto* region = process().allocate_region({}, thread_specific_region_size, "Thread-specific", PROT_READ | PROT_WRITE, true);
  763. SmapDisabler disabler;
  764. auto* thread_specific_data = (ThreadSpecificData*)region->vaddr().offset(align_up_to(process().m_master_tls_size, thread_specific_region_alignment)).as_ptr();
  765. auto* thread_local_storage = (u8*)((u8*)thread_specific_data) - align_up_to(process().m_master_tls_size, process().m_master_tls_alignment);
  766. m_thread_specific_data = VirtualAddress(thread_specific_data);
  767. thread_specific_data->self = thread_specific_data;
  768. if (process().m_master_tls_size)
  769. memcpy(thread_local_storage, process().m_master_tls_region->vaddr().as_ptr(), process().m_master_tls_size);
  770. }
  771. const LogStream& operator<<(const LogStream& stream, const Thread& value)
  772. {
  773. return stream << value.process().name() << "(" << value.pid() << ":" << value.tid() << ")";
  774. }
  775. void Thread::wait_on(WaitQueue& queue, Atomic<bool>* lock, Thread* beneficiary, const char* reason)
  776. {
  777. cli();
  778. bool did_unlock = unlock_process_if_locked();
  779. if (lock)
  780. *lock = false;
  781. set_state(State::Queued);
  782. queue.enqueue(*current);
  783. // Yield and wait for the queue to wake us up again.
  784. if (beneficiary)
  785. Scheduler::donate_to(beneficiary, reason);
  786. else
  787. Scheduler::yield();
  788. // We've unblocked, relock the process if needed and carry on.
  789. if (did_unlock)
  790. relock_process();
  791. }
  792. void Thread::wake_from_queue()
  793. {
  794. ASSERT(state() == State::Queued);
  795. set_state(State::Runnable);
  796. }
  797. Thread* Thread::from_tid(int tid)
  798. {
  799. InterruptDisabler disabler;
  800. Thread* found_thread = nullptr;
  801. Thread::for_each([&](auto& thread) {
  802. if (thread.tid() == tid) {
  803. found_thread = &thread;
  804. return IterationDecision::Break;
  805. }
  806. return IterationDecision::Continue;
  807. });
  808. return found_thread;
  809. }
  810. void Thread::reset_fpu_state()
  811. {
  812. memcpy(m_fpu_state, &s_clean_fpu_state, sizeof(FPUState));
  813. }
  814. void Thread::start_tracing_from(pid_t tracer)
  815. {
  816. m_tracer = ThreadTracer::create(tracer);
  817. }
  818. void Thread::stop_tracing()
  819. {
  820. m_tracer = nullptr;
  821. }
  822. void Thread::tracer_trap(const RegisterState& regs)
  823. {
  824. ASSERT(m_tracer.ptr());
  825. m_tracer->set_regs(regs);
  826. send_urgent_signal_to_self(SIGTRAP);
  827. }
  828. }