NativeSignalHandler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. using ARMeilleure.IntermediateRepresentation;
  2. using ARMeilleure.Memory;
  3. using ARMeilleure.Translation;
  4. using ARMeilleure.Translation.Cache;
  5. using System;
  6. using System.Runtime.CompilerServices;
  7. using System.Runtime.InteropServices;
  8. using static ARMeilleure.IntermediateRepresentation.Operand.Factory;
  9. namespace ARMeilleure.Signal
  10. {
  11. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  12. struct SignalHandlerRange
  13. {
  14. public int IsActive;
  15. public nuint RangeAddress;
  16. public nuint RangeEndAddress;
  17. public IntPtr ActionPointer;
  18. }
  19. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  20. struct SignalHandlerConfig
  21. {
  22. /// <summary>
  23. /// The byte offset of the faulting address in the SigInfo or ExceptionRecord struct.
  24. /// </summary>
  25. public int StructAddressOffset;
  26. /// <summary>
  27. /// The byte offset of the write flag in the SigInfo or ExceptionRecord struct.
  28. /// </summary>
  29. public int StructWriteOffset;
  30. /// <summary>
  31. /// The sigaction handler that was registered before this one. (unix only)
  32. /// </summary>
  33. public nuint UnixOldSigaction;
  34. /// <summary>
  35. /// The type of the previous sigaction. True for the 3 argument variant. (unix only)
  36. /// </summary>
  37. public int UnixOldSigaction3Arg;
  38. public SignalHandlerRange Range0;
  39. public SignalHandlerRange Range1;
  40. public SignalHandlerRange Range2;
  41. public SignalHandlerRange Range3;
  42. public SignalHandlerRange Range4;
  43. public SignalHandlerRange Range5;
  44. public SignalHandlerRange Range6;
  45. public SignalHandlerRange Range7;
  46. }
  47. public static class NativeSignalHandler
  48. {
  49. private delegate void UnixExceptionHandler(int sig, IntPtr info, IntPtr ucontext);
  50. [UnmanagedFunctionPointer(CallingConvention.Winapi)]
  51. private delegate int VectoredExceptionHandler(IntPtr exceptionInfo);
  52. private const int MaxTrackedRanges = 8;
  53. private const int StructAddressOffset = 0;
  54. private const int StructWriteOffset = 4;
  55. private const int UnixOldSigaction = 8;
  56. private const int UnixOldSigaction3Arg = 16;
  57. private const int RangeOffset = 20;
  58. private const int EXCEPTION_CONTINUE_SEARCH = 0;
  59. private const int EXCEPTION_CONTINUE_EXECUTION = -1;
  60. private const uint EXCEPTION_ACCESS_VIOLATION = 0xc0000005;
  61. private static ulong _pageSize = GetPageSize();
  62. private static ulong _pageMask = _pageSize - 1;
  63. private static IntPtr _handlerConfig;
  64. private static IntPtr _signalHandlerPtr;
  65. private static IntPtr _signalHandlerHandle;
  66. private static readonly object _lock = new object();
  67. private static bool _initialized;
  68. private static ulong GetPageSize()
  69. {
  70. // TODO: This needs to be based on the current memory manager configuration.
  71. if (OperatingSystem.IsMacOS() && RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
  72. {
  73. return 1UL << 14;
  74. }
  75. else
  76. {
  77. return 1UL << 12;
  78. }
  79. }
  80. static NativeSignalHandler()
  81. {
  82. _handlerConfig = Marshal.AllocHGlobal(Unsafe.SizeOf<SignalHandlerConfig>());
  83. ref SignalHandlerConfig config = ref GetConfigRef();
  84. config = new SignalHandlerConfig();
  85. }
  86. public static void InitializeJitCache(IJitMemoryAllocator allocator)
  87. {
  88. JitCache.Initialize(allocator);
  89. }
  90. public static void InitializeSignalHandler(Func<IntPtr, IntPtr, IntPtr> customSignalHandlerFactory = null)
  91. {
  92. if (_initialized) return;
  93. lock (_lock)
  94. {
  95. if (_initialized) return;
  96. ref SignalHandlerConfig config = ref GetConfigRef();
  97. if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
  98. {
  99. // Unix siginfo struct locations.
  100. // NOTE: These are incredibly likely to be different between kernel version and architectures.
  101. config.StructAddressOffset = OperatingSystem.IsMacOS() ? 24 : 16; // si_addr
  102. config.StructWriteOffset = 8; // si_code
  103. _signalHandlerPtr = Marshal.GetFunctionPointerForDelegate(GenerateUnixSignalHandler(_handlerConfig));
  104. if (customSignalHandlerFactory != null)
  105. {
  106. _signalHandlerPtr = customSignalHandlerFactory(UnixSignalHandlerRegistration.GetSegfaultExceptionHandler().sa_handler, _signalHandlerPtr);
  107. }
  108. var old = UnixSignalHandlerRegistration.RegisterExceptionHandler(_signalHandlerPtr);
  109. config.UnixOldSigaction = (nuint)(ulong)old.sa_handler;
  110. config.UnixOldSigaction3Arg = old.sa_flags & 4;
  111. }
  112. else
  113. {
  114. config.StructAddressOffset = 40; // ExceptionInformation1
  115. config.StructWriteOffset = 32; // ExceptionInformation0
  116. _signalHandlerPtr = Marshal.GetFunctionPointerForDelegate(GenerateWindowsSignalHandler(_handlerConfig));
  117. if (customSignalHandlerFactory != null)
  118. {
  119. _signalHandlerPtr = customSignalHandlerFactory(IntPtr.Zero, _signalHandlerPtr);
  120. }
  121. _signalHandlerHandle = WindowsSignalHandlerRegistration.RegisterExceptionHandler(_signalHandlerPtr);
  122. }
  123. _initialized = true;
  124. }
  125. }
  126. private static unsafe ref SignalHandlerConfig GetConfigRef()
  127. {
  128. return ref Unsafe.AsRef<SignalHandlerConfig>((void*)_handlerConfig);
  129. }
  130. public static unsafe bool AddTrackedRegion(nuint address, nuint endAddress, IntPtr action)
  131. {
  132. var ranges = &((SignalHandlerConfig*)_handlerConfig)->Range0;
  133. for (int i = 0; i < MaxTrackedRanges; i++)
  134. {
  135. if (ranges[i].IsActive == 0)
  136. {
  137. ranges[i].RangeAddress = address;
  138. ranges[i].RangeEndAddress = endAddress;
  139. ranges[i].ActionPointer = action;
  140. ranges[i].IsActive = 1;
  141. return true;
  142. }
  143. }
  144. return false;
  145. }
  146. public static unsafe bool RemoveTrackedRegion(nuint address)
  147. {
  148. var ranges = &((SignalHandlerConfig*)_handlerConfig)->Range0;
  149. for (int i = 0; i < MaxTrackedRanges; i++)
  150. {
  151. if (ranges[i].IsActive == 1 && ranges[i].RangeAddress == address)
  152. {
  153. ranges[i].IsActive = 0;
  154. return true;
  155. }
  156. }
  157. return false;
  158. }
  159. private static Operand EmitGenericRegionCheck(EmitterContext context, IntPtr signalStructPtr, Operand faultAddress, Operand isWrite)
  160. {
  161. Operand inRegionLocal = context.AllocateLocal(OperandType.I32);
  162. context.Copy(inRegionLocal, Const(0));
  163. Operand endLabel = Label();
  164. for (int i = 0; i < MaxTrackedRanges; i++)
  165. {
  166. ulong rangeBaseOffset = (ulong)(RangeOffset + i * Unsafe.SizeOf<SignalHandlerRange>());
  167. Operand nextLabel = Label();
  168. Operand isActive = context.Load(OperandType.I32, Const((ulong)signalStructPtr + rangeBaseOffset));
  169. context.BranchIfFalse(nextLabel, isActive);
  170. Operand rangeAddress = context.Load(OperandType.I64, Const((ulong)signalStructPtr + rangeBaseOffset + 4));
  171. Operand rangeEndAddress = context.Load(OperandType.I64, Const((ulong)signalStructPtr + rangeBaseOffset + 12));
  172. // Is the fault address within this tracked region?
  173. Operand inRange = context.BitwiseAnd(
  174. context.ICompare(faultAddress, rangeAddress, Comparison.GreaterOrEqualUI),
  175. context.ICompare(faultAddress, rangeEndAddress, Comparison.LessUI)
  176. );
  177. // Only call tracking if in range.
  178. context.BranchIfFalse(nextLabel, inRange, BasicBlockFrequency.Cold);
  179. Operand offset = context.BitwiseAnd(context.Subtract(faultAddress, rangeAddress), Const(~_pageMask));
  180. // Call the tracking action, with the pointer's relative offset to the base address.
  181. Operand trackingActionPtr = context.Load(OperandType.I64, Const((ulong)signalStructPtr + rangeBaseOffset + 20));
  182. context.Copy(inRegionLocal, Const(0));
  183. Operand skipActionLabel = Label();
  184. // Tracking action should be non-null to call it, otherwise assume false return.
  185. context.BranchIfFalse(skipActionLabel, trackingActionPtr);
  186. Operand result = context.Call(trackingActionPtr, OperandType.I32, offset, Const(_pageSize), isWrite, Const(0));
  187. context.Copy(inRegionLocal, result);
  188. context.MarkLabel(skipActionLabel);
  189. // If the tracking action returns false or does not exist, it might be an invalid access due to a partial overlap on Windows.
  190. if (OperatingSystem.IsWindows())
  191. {
  192. context.BranchIfTrue(endLabel, inRegionLocal);
  193. context.Copy(inRegionLocal, WindowsPartialUnmapHandler.EmitRetryFromAccessViolation(context));
  194. }
  195. context.Branch(endLabel);
  196. context.MarkLabel(nextLabel);
  197. }
  198. context.MarkLabel(endLabel);
  199. return context.Copy(inRegionLocal);
  200. }
  201. private static UnixExceptionHandler GenerateUnixSignalHandler(IntPtr signalStructPtr)
  202. {
  203. EmitterContext context = new EmitterContext();
  204. // (int sig, SigInfo* sigInfo, void* ucontext)
  205. Operand sigInfoPtr = context.LoadArgument(OperandType.I64, 1);
  206. Operand structAddressOffset = context.Load(OperandType.I64, Const((ulong)signalStructPtr + StructAddressOffset));
  207. Operand structWriteOffset = context.Load(OperandType.I64, Const((ulong)signalStructPtr + StructWriteOffset));
  208. Operand faultAddress = context.Load(OperandType.I64, context.Add(sigInfoPtr, context.ZeroExtend32(OperandType.I64, structAddressOffset)));
  209. Operand writeFlag = context.Load(OperandType.I64, context.Add(sigInfoPtr, context.ZeroExtend32(OperandType.I64, structWriteOffset)));
  210. Operand isWrite = context.ICompareNotEqual(writeFlag, Const(0L)); // Normalize to 0/1.
  211. Operand isInRegion = EmitGenericRegionCheck(context, signalStructPtr, faultAddress, isWrite);
  212. Operand endLabel = Label();
  213. context.BranchIfTrue(endLabel, isInRegion);
  214. Operand unixOldSigaction = context.Load(OperandType.I64, Const((ulong)signalStructPtr + UnixOldSigaction));
  215. Operand unixOldSigaction3Arg = context.Load(OperandType.I64, Const((ulong)signalStructPtr + UnixOldSigaction3Arg));
  216. Operand threeArgLabel = Label();
  217. context.BranchIfTrue(threeArgLabel, unixOldSigaction3Arg);
  218. context.Call(unixOldSigaction, OperandType.None, context.LoadArgument(OperandType.I32, 0));
  219. context.Branch(endLabel);
  220. context.MarkLabel(threeArgLabel);
  221. context.Call(unixOldSigaction,
  222. OperandType.None,
  223. context.LoadArgument(OperandType.I32, 0),
  224. sigInfoPtr,
  225. context.LoadArgument(OperandType.I64, 2)
  226. );
  227. context.MarkLabel(endLabel);
  228. context.Return();
  229. ControlFlowGraph cfg = context.GetControlFlowGraph();
  230. OperandType[] argTypes = new OperandType[] { OperandType.I32, OperandType.I64, OperandType.I64 };
  231. return Compiler.Compile(cfg, argTypes, OperandType.None, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map<UnixExceptionHandler>();
  232. }
  233. private static VectoredExceptionHandler GenerateWindowsSignalHandler(IntPtr signalStructPtr)
  234. {
  235. EmitterContext context = new EmitterContext();
  236. // (ExceptionPointers* exceptionInfo)
  237. Operand exceptionInfoPtr = context.LoadArgument(OperandType.I64, 0);
  238. Operand exceptionRecordPtr = context.Load(OperandType.I64, exceptionInfoPtr);
  239. // First thing's first - this catches a number of exceptions, but we only want access violations.
  240. Operand validExceptionLabel = Label();
  241. Operand exceptionCode = context.Load(OperandType.I32, exceptionRecordPtr);
  242. context.BranchIf(validExceptionLabel, exceptionCode, Const(EXCEPTION_ACCESS_VIOLATION), Comparison.Equal);
  243. context.Return(Const(EXCEPTION_CONTINUE_SEARCH)); // Don't handle this one.
  244. context.MarkLabel(validExceptionLabel);
  245. // Next, read the address of the invalid access, and whether it is a write or not.
  246. Operand structAddressOffset = context.Load(OperandType.I32, Const((ulong)signalStructPtr + StructAddressOffset));
  247. Operand structWriteOffset = context.Load(OperandType.I32, Const((ulong)signalStructPtr + StructWriteOffset));
  248. Operand faultAddress = context.Load(OperandType.I64, context.Add(exceptionRecordPtr, context.ZeroExtend32(OperandType.I64, structAddressOffset)));
  249. Operand writeFlag = context.Load(OperandType.I64, context.Add(exceptionRecordPtr, context.ZeroExtend32(OperandType.I64, structWriteOffset)));
  250. Operand isWrite = context.ICompareNotEqual(writeFlag, Const(0L)); // Normalize to 0/1.
  251. Operand isInRegion = EmitGenericRegionCheck(context, signalStructPtr, faultAddress, isWrite);
  252. Operand endLabel = Label();
  253. // If the region check result is false, then run the next vectored exception handler.
  254. context.BranchIfTrue(endLabel, isInRegion);
  255. context.Return(Const(EXCEPTION_CONTINUE_SEARCH));
  256. context.MarkLabel(endLabel);
  257. // Otherwise, return to execution.
  258. context.Return(Const(EXCEPTION_CONTINUE_EXECUTION));
  259. // Compile and return the function.
  260. ControlFlowGraph cfg = context.GetControlFlowGraph();
  261. OperandType[] argTypes = new OperandType[] { OperandType.I64 };
  262. return Compiler.Compile(cfg, argTypes, OperandType.I32, CompilerOptions.HighCq, RuntimeInformation.ProcessArchitecture).Map<VectoredExceptionHandler>();
  263. }
  264. }
  265. }