Syscall.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /*
  2. * Copyright (c) 2018-2021, 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 <Kernel/API/Syscall.h>
  27. #include <Kernel/Arch/x86/CPU.h>
  28. #include <Kernel/Panic.h>
  29. #include <Kernel/Process.h>
  30. #include <Kernel/ThreadTracer.h>
  31. #include <Kernel/VM/MemoryManager.h>
  32. namespace Kernel {
  33. extern "C" void syscall_handler(TrapFrame*);
  34. extern "C" void syscall_asm_entry();
  35. // clang-format off
  36. #if ARCH(I386)
  37. asm(
  38. ".globl syscall_asm_entry\n"
  39. "syscall_asm_entry:\n"
  40. " pushl $0x0\n"
  41. " pusha\n"
  42. " pushl %ds\n"
  43. " pushl %es\n"
  44. " pushl %fs\n"
  45. " pushl %gs\n"
  46. " pushl %ss\n"
  47. " mov $" __STRINGIFY(GDT_SELECTOR_DATA0) ", %ax\n"
  48. " mov %ax, %ds\n"
  49. " mov %ax, %es\n"
  50. " mov $" __STRINGIFY(GDT_SELECTOR_PROC) ", %ax\n"
  51. " mov %ax, %fs\n"
  52. " cld\n"
  53. " xor %esi, %esi\n"
  54. " xor %edi, %edi\n"
  55. " pushl %esp \n" // set TrapFrame::regs
  56. " subl $" __STRINGIFY(TRAP_FRAME_SIZE - 4) ", %esp \n"
  57. " movl %esp, %ebx \n"
  58. " pushl %ebx \n" // push pointer to TrapFrame
  59. " call enter_trap_no_irq \n"
  60. " movl %ebx, 0(%esp) \n" // push pointer to TrapFrame
  61. " call syscall_handler \n"
  62. " movl %ebx, 0(%esp) \n" // push pointer to TrapFrame
  63. " jmp common_trap_exit \n");
  64. #elif ARCH(X86_64)
  65. asm(
  66. ".globl syscall_asm_entry\n"
  67. "syscall_asm_entry:\n"
  68. " cli\n"
  69. " hlt\n");
  70. #endif
  71. // clang-format on
  72. namespace Syscall {
  73. static KResultOr<FlatPtr> handle(RegisterState&, FlatPtr function, FlatPtr arg1, FlatPtr arg2, FlatPtr arg3);
  74. UNMAP_AFTER_INIT void initialize()
  75. {
  76. register_user_callable_interrupt_handler(syscall_vector, syscall_asm_entry);
  77. }
  78. #pragma GCC diagnostic ignored "-Wcast-function-type"
  79. typedef KResultOr<FlatPtr> (Process::*Handler)(FlatPtr, FlatPtr, FlatPtr);
  80. typedef KResultOr<FlatPtr> (Process::*HandlerWithRegisterState)(RegisterState&);
  81. #define __ENUMERATE_SYSCALL(x) reinterpret_cast<Handler>(&Process::sys$##x),
  82. static const Handler s_syscall_table[] = {
  83. ENUMERATE_SYSCALLS(__ENUMERATE_SYSCALL)
  84. };
  85. #undef __ENUMERATE_SYSCALL
  86. KResultOr<FlatPtr> handle(RegisterState& regs, FlatPtr function, FlatPtr arg1, FlatPtr arg2, FlatPtr arg3)
  87. {
  88. VERIFY_INTERRUPTS_ENABLED();
  89. auto current_thread = Thread::current();
  90. auto& process = current_thread->process();
  91. current_thread->did_syscall();
  92. if (function == SC_abort || function == SC_exit || function == SC_exit_thread) {
  93. // These syscalls need special handling since they never return to the caller.
  94. if (auto* tracer = process.tracer(); tracer && tracer->is_tracing_syscalls()) {
  95. regs.eax = 0;
  96. tracer->set_trace_syscalls(false);
  97. process.tracer_trap(*current_thread, regs); // this triggers SIGTRAP and stops the thread!
  98. }
  99. switch (function) {
  100. case SC_abort:
  101. process.sys$abort();
  102. break;
  103. case SC_exit:
  104. process.sys$exit(arg1);
  105. break;
  106. case SC_exit_thread:
  107. process.sys$exit_thread(arg1);
  108. break;
  109. default:
  110. VERIFY_NOT_REACHED();
  111. }
  112. }
  113. if (function == SC_fork || function == SC_sigreturn) {
  114. // These syscalls want the RegisterState& rather than individual parameters.
  115. auto handler = (HandlerWithRegisterState)s_syscall_table[function];
  116. return (process.*(handler))(regs);
  117. }
  118. if (function >= Function::__Count) {
  119. dbgln("Unknown syscall {} requested ({:08x}, {:08x}, {:08x})", function, arg1, arg2, arg3);
  120. return ENOSYS;
  121. }
  122. if (s_syscall_table[function] == nullptr) {
  123. dbgln("Null syscall {} requested, you probably need to rebuild this program!", function);
  124. return ENOSYS;
  125. }
  126. return (process.*(s_syscall_table[function]))(arg1, arg2, arg3);
  127. }
  128. }
  129. void syscall_handler(TrapFrame* trap)
  130. {
  131. auto& regs = *trap->regs;
  132. auto current_thread = Thread::current();
  133. VERIFY(current_thread->previous_mode() == Thread::PreviousMode::UserMode);
  134. auto& process = current_thread->process();
  135. if (auto tracer = process.tracer(); tracer && tracer->is_tracing_syscalls()) {
  136. tracer->set_trace_syscalls(false);
  137. process.tracer_trap(*current_thread, regs); // this triggers SIGTRAP and stops the thread!
  138. }
  139. current_thread->yield_if_stopped();
  140. // Make sure SMAP protection is enabled on syscall entry.
  141. clac();
  142. // Apply a random offset in the range 0-255 to the stack pointer,
  143. // to make kernel stacks a bit less deterministic.
  144. u32 lsw;
  145. u32 msw;
  146. read_tsc(lsw, msw);
  147. auto* ptr = (char*)__builtin_alloca(lsw & 0xff);
  148. asm volatile(""
  149. : "=m"(*ptr));
  150. static constexpr FlatPtr iopl_mask = 3u << 12;
  151. if ((regs.eflags & (iopl_mask)) != 0) {
  152. PANIC("Syscall from process with IOPL != 0");
  153. }
  154. // NOTE: We take the big process lock before inspecting memory regions.
  155. process.big_lock().lock();
  156. if (!MM.validate_user_stack(process, VirtualAddress(regs.userspace_esp))) {
  157. dbgln("Invalid stack pointer: {:p}", regs.userspace_esp);
  158. handle_crash(regs, "Bad stack on syscall entry", SIGSTKFLT);
  159. }
  160. auto* calling_region = MM.find_region_from_vaddr(process.space(), VirtualAddress(regs.eip));
  161. if (!calling_region) {
  162. dbgln("Syscall from {:p} which has no associated region", regs.eip);
  163. handle_crash(regs, "Syscall from unknown region", SIGSEGV);
  164. }
  165. if (calling_region->is_writable()) {
  166. dbgln("Syscall from writable memory at {:p}", regs.eip);
  167. handle_crash(regs, "Syscall from writable memory", SIGSEGV);
  168. }
  169. if (process.space().enforces_syscall_regions() && !calling_region->is_syscall_region()) {
  170. dbgln("Syscall from non-syscall region");
  171. handle_crash(regs, "Syscall from non-syscall region", SIGSEGV);
  172. }
  173. auto function = regs.eax;
  174. auto arg1 = regs.edx;
  175. auto arg2 = regs.ecx;
  176. auto arg3 = regs.ebx;
  177. auto result = Syscall::handle(regs, function, arg1, arg2, arg3);
  178. if (result.is_error())
  179. regs.eax = result.error();
  180. else
  181. regs.eax = result.value();
  182. process.big_lock().unlock();
  183. if (auto tracer = process.tracer(); tracer && tracer->is_tracing_syscalls()) {
  184. tracer->set_trace_syscalls(false);
  185. process.tracer_trap(*current_thread, regs); // this triggers SIGTRAP and stops the thread!
  186. }
  187. current_thread->yield_if_stopped();
  188. current_thread->check_dispatch_pending_signal();
  189. // If the previous mode somehow changed something is seriously messed up...
  190. VERIFY(current_thread->previous_mode() == Thread::PreviousMode::UserMode);
  191. // Check if we're supposed to return to userspace or just die.
  192. current_thread->die_if_needed();
  193. VERIFY(!g_scheduler_lock.own_lock());
  194. }
  195. }