UnixSignalHandlerRegistration.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace ARMeilleure.Signal
  4. {
  5. static partial class UnixSignalHandlerRegistration
  6. {
  7. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  8. public unsafe struct SigSet
  9. {
  10. fixed long sa_mask[16];
  11. }
  12. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  13. public struct SigAction
  14. {
  15. public IntPtr sa_handler;
  16. public SigSet sa_mask;
  17. public int sa_flags;
  18. public IntPtr sa_restorer;
  19. }
  20. private const int SIGSEGV = 11;
  21. private const int SIGBUS = 10;
  22. private const int SA_SIGINFO = 0x00000004;
  23. [LibraryImport("libc", SetLastError = true)]
  24. private static partial int sigaction(int signum, ref SigAction sigAction, out SigAction oldAction);
  25. [LibraryImport("libc", SetLastError = true)]
  26. private static partial int sigaction(int signum, IntPtr sigAction, out SigAction oldAction);
  27. [LibraryImport("libc", SetLastError = true)]
  28. private static partial int sigemptyset(ref SigSet set);
  29. public static SigAction GetSegfaultExceptionHandler()
  30. {
  31. int result = sigaction(SIGSEGV, IntPtr.Zero, out SigAction old);
  32. if (result != 0)
  33. {
  34. throw new InvalidOperationException($"Could not get SIGSEGV sigaction. Error: {result}");
  35. }
  36. return old;
  37. }
  38. public static SigAction RegisterExceptionHandler(IntPtr action)
  39. {
  40. SigAction sig = new SigAction
  41. {
  42. sa_handler = action,
  43. sa_flags = SA_SIGINFO
  44. };
  45. sigemptyset(ref sig.sa_mask);
  46. int result = sigaction(SIGSEGV, ref sig, out SigAction old);
  47. if (result != 0)
  48. {
  49. throw new InvalidOperationException($"Could not register SIGSEGV sigaction. Error: {result}");
  50. }
  51. if (OperatingSystem.IsMacOS())
  52. {
  53. result = sigaction(SIGBUS, ref sig, out _);
  54. if (result != 0)
  55. {
  56. throw new InvalidOperationException($"Could not register SIGBUS sigaction. Error: {result}");
  57. }
  58. }
  59. return old;
  60. }
  61. public static bool RestoreExceptionHandler(SigAction oldAction)
  62. {
  63. return sigaction(SIGSEGV, ref oldAction, out SigAction _) == 0 && (!OperatingSystem.IsMacOS() || sigaction(SIGBUS, ref oldAction, out SigAction _) == 0);
  64. }
  65. }
  66. }