Syscall.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 <Kernel/API/Syscall.h>
  27. #include <Kernel/Arch/i386/CPU.h>
  28. #include <Kernel/Panic.h>
  29. #include <Kernel/Process.h>
  30. #include <Kernel/Random.h>
  31. #include <Kernel/ThreadTracer.h>
  32. #include <Kernel/VM/MemoryManager.h>
  33. namespace Kernel {
  34. extern "C" void syscall_handler(TrapFrame*);
  35. extern "C" void syscall_asm_entry();
  36. // clang-format off
  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. // clang-format on
  65. namespace Syscall {
  66. static int handle(RegisterState&, u32 function, u32 arg1, u32 arg2, u32 arg3);
  67. void initialize()
  68. {
  69. register_user_callable_interrupt_handler(syscall_vector, syscall_asm_entry);
  70. klog() << "Syscall: int 0x82 handler installed";
  71. }
  72. #pragma GCC diagnostic ignored "-Wcast-function-type"
  73. typedef int (Process::*Handler)(u32, u32, u32);
  74. #define __ENUMERATE_SYSCALL(x) reinterpret_cast<Handler>(&Process::sys$##x),
  75. static Handler s_syscall_table[] = {
  76. ENUMERATE_SYSCALLS(__ENUMERATE_SYSCALL)
  77. };
  78. #undef __ENUMERATE_SYSCALL
  79. int handle(RegisterState& regs, u32 function, u32 arg1, u32 arg2, u32 arg3)
  80. {
  81. ASSERT_INTERRUPTS_ENABLED();
  82. auto current_thread = Thread::current();
  83. auto& process = current_thread->process();
  84. current_thread->did_syscall();
  85. if (function == SC_exit || function == SC_exit_thread) {
  86. // These syscalls need special handling since they never return to the caller.
  87. if (auto* tracer = process.tracer(); tracer && tracer->is_tracing_syscalls()) {
  88. regs.eax = 0;
  89. tracer->set_trace_syscalls(false);
  90. process.tracer_trap(*current_thread, regs); // this triggers SIGTRAP and stops the thread!
  91. }
  92. cli();
  93. if (function == SC_exit)
  94. process.sys$exit((int)arg1);
  95. else
  96. process.sys$exit_thread(arg1);
  97. ASSERT_NOT_REACHED();
  98. return 0;
  99. }
  100. if (function == SC_fork)
  101. return process.sys$fork(regs);
  102. if (function == SC_sigreturn)
  103. return process.sys$sigreturn(regs);
  104. if (function >= Function::__Count) {
  105. dbgln("Unknown syscall {} requested ({:08x}, {:08x}, {:08x})", function, arg1, arg2, arg3);
  106. return -ENOSYS;
  107. }
  108. if (s_syscall_table[function] == nullptr) {
  109. dbgln("Null syscall {} requested, you probably need to rebuild this program!", function);
  110. return -ENOSYS;
  111. }
  112. return (process.*(s_syscall_table[function]))(arg1, arg2, arg3);
  113. }
  114. }
  115. constexpr int RandomByteBufferSize = 256;
  116. u8 g_random_byte_buffer[RandomByteBufferSize];
  117. int g_random_byte_buffer_offset = RandomByteBufferSize;
  118. void syscall_handler(TrapFrame* trap)
  119. {
  120. auto& regs = *trap->regs;
  121. auto current_thread = Thread::current();
  122. ASSERT(current_thread->previous_mode() == Thread::PreviousMode::UserMode);
  123. auto& process = current_thread->process();
  124. if (auto tracer = process.tracer(); tracer && tracer->is_tracing_syscalls()) {
  125. tracer->set_trace_syscalls(false);
  126. process.tracer_trap(*current_thread, regs); // this triggers SIGTRAP and stops the thread!
  127. }
  128. current_thread->yield_if_stopped();
  129. // Make sure SMAP protection is enabled on syscall entry.
  130. clac();
  131. // Apply a random offset in the range 0-255 to the stack pointer,
  132. // to make kernel stacks a bit less deterministic.
  133. // Since this is very hot code, request random data in chunks instead of
  134. // one byte at a time. This is a noticeable speedup.
  135. if (g_random_byte_buffer_offset == RandomByteBufferSize) {
  136. get_fast_random_bytes(g_random_byte_buffer, RandomByteBufferSize);
  137. g_random_byte_buffer_offset = 0;
  138. }
  139. auto* ptr = (char*)__builtin_alloca(g_random_byte_buffer[g_random_byte_buffer_offset++]);
  140. asm volatile(""
  141. : "=m"(*ptr));
  142. static constexpr u32 iopl_mask = 3u << 12;
  143. if ((regs.eflags & (iopl_mask)) != 0) {
  144. PANIC("Syscall from process with IOPL != 0");
  145. }
  146. if (!MM.validate_user_stack(process, VirtualAddress(regs.userspace_esp))) {
  147. dbgln("Invalid stack pointer: {:p}", regs.userspace_esp);
  148. handle_crash(regs, "Bad stack on syscall entry", SIGSTKFLT);
  149. ASSERT_NOT_REACHED();
  150. }
  151. auto* calling_region = MM.find_region_from_vaddr(process.space(), VirtualAddress(regs.eip));
  152. if (!calling_region) {
  153. dbgln("Syscall from {:p} which has no associated region", regs.eip);
  154. handle_crash(regs, "Syscall from unknown region", SIGSEGV);
  155. ASSERT_NOT_REACHED();
  156. }
  157. if (calling_region->is_writable()) {
  158. dbgln("Syscall from writable memory at {:p}", regs.eip);
  159. handle_crash(regs, "Syscall from writable memory", SIGSEGV);
  160. ASSERT_NOT_REACHED();
  161. }
  162. if (process.space().enforces_syscall_regions() && !calling_region->is_syscall_region()) {
  163. dbgln("Syscall from non-syscall region");
  164. handle_crash(regs, "Syscall from non-syscall region", SIGSEGV);
  165. ASSERT_NOT_REACHED();
  166. }
  167. process.big_lock().lock();
  168. u32 function = regs.eax;
  169. u32 arg1 = regs.edx;
  170. u32 arg2 = regs.ecx;
  171. u32 arg3 = regs.ebx;
  172. regs.eax = Syscall::handle(regs, function, arg1, arg2, arg3);
  173. process.big_lock().unlock();
  174. if (auto tracer = process.tracer(); tracer && tracer->is_tracing_syscalls()) {
  175. tracer->set_trace_syscalls(false);
  176. process.tracer_trap(*current_thread, regs); // this triggers SIGTRAP and stops the thread!
  177. }
  178. current_thread->yield_if_stopped();
  179. current_thread->check_dispatch_pending_signal();
  180. // If the previous mode somehow changed something is seriously messed up...
  181. ASSERT(current_thread->previous_mode() == Thread::PreviousMode::UserMode);
  182. // Check if we're supposed to return to userspace or just die.
  183. current_thread->die_if_needed();
  184. ASSERT(!g_scheduler_lock.own_lock());
  185. }
  186. }