Thread.cpp 29 KB

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