UnixSignalHandlerRegistration.cs 2.0 KB

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