NativeSignalHandler.cs 13 KB

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