MacOsPageAllocator.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using MonoMod.Utils;
  5. namespace BepInEx.IL2CPP.Allocator
  6. {
  7. internal class MacOsPageAllocator : UnixPageAllocator
  8. {
  9. protected override IEnumerable<(IntPtr, IntPtr)> MapMemoryAreas()
  10. {
  11. var size = IntPtr.Zero;
  12. var info = new LibSystem.vm_region_basic_info_64();
  13. var infoCount = (uint)(Marshal.SizeOf<LibSystem.vm_region_basic_info_64>() / sizeof(int));
  14. var objectName = 0u;
  15. var address = IntPtr.Zero;
  16. while (LibSystem.vm_region_64(LibSystem.TaskSelf, ref address, ref size, LibSystem.VM_REGION_BASIC_INFO_64, ref info, ref infoCount, ref objectName) == LibSystem.KERN_SUCCESS)
  17. {
  18. var start = new IntPtr(address.ToInt64());
  19. var end = new IntPtr(address.ToInt64() + size.ToInt64());
  20. address = end;
  21. yield return (start, end);
  22. }
  23. }
  24. private static class LibSystem
  25. {
  26. public const int VM_REGION_BASIC_INFO_64 = 9;
  27. public const int KERN_SUCCESS = 0;
  28. public static readonly IntPtr TaskSelf;
  29. static LibSystem()
  30. {
  31. typeof(LibSystem).ResolveDynDllImports(new Dictionary<string, List<DynDllMapping>>
  32. {
  33. ["libSystem"] = new List<DynDllMapping>
  34. {
  35. "/usr/lib/libSystem.dylib" // OSX POSIX
  36. }
  37. });
  38. var libsystem = DynDll.OpenLibrary("/usr/lib/libSystem.dylib");
  39. TaskSelf = libsystem.GetFunction("mach_task_self_"); // This isn't a function but rather an exported symbol
  40. }
  41. // ReSharper disable InconsistentNaming
  42. [StructLayout(LayoutKind.Sequential)]
  43. public readonly struct vm_region_basic_info_64
  44. {
  45. public readonly int protection;
  46. public readonly int max_protection;
  47. public readonly uint inheritance;
  48. [MarshalAs(UnmanagedType.I4)]
  49. public readonly bool shared;
  50. [MarshalAs(UnmanagedType.I4)]
  51. public readonly bool reserved;
  52. public readonly ulong offset;
  53. public readonly int behavior;
  54. public readonly ushort user_wired_count;
  55. }
  56. // ReSharper restore InconsistentNaming
  57. // ReSharper disable InconsistentNaming
  58. [DynDllImport("libSystem")]
  59. public static vm_region_64Delegate vm_region_64;
  60. public delegate int vm_region_64Delegate(IntPtr target_task, ref IntPtr address, ref IntPtr size, int flavor, ref vm_region_basic_info_64 info, ref uint infoCnt, ref uint object_name);
  61. // ReSharper restore InconsistentNaming
  62. }
  63. }
  64. }