MemoryLimitConstraint.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using Jint.Runtime;
  2. namespace Jint.Constraints;
  3. public sealed class MemoryLimitConstraint : Constraint
  4. {
  5. private readonly long _memoryLimit;
  6. private long _initialMemoryUsage;
  7. #if !NET8_0_OR_GREATER
  8. private static readonly Func<long>? _getAllocatedBytesForCurrentThread;
  9. static MemoryLimitConstraint()
  10. {
  11. var methodInfo = typeof(GC).GetMethod("GetAllocatedBytesForCurrentThread");
  12. if (methodInfo != null)
  13. {
  14. _getAllocatedBytesForCurrentThread = (Func<long>) Delegate.CreateDelegate(typeof(Func<long>), null, methodInfo);
  15. }
  16. }
  17. #endif
  18. internal MemoryLimitConstraint(long memoryLimit)
  19. {
  20. _memoryLimit = memoryLimit;
  21. }
  22. public override void Check()
  23. {
  24. if (_memoryLimit <= 0)
  25. {
  26. return;
  27. }
  28. #if NET8_0_OR_GREATER
  29. var usage = GC.GetAllocatedBytesForCurrentThread();
  30. #else
  31. if (_getAllocatedBytesForCurrentThread == null)
  32. {
  33. Throw.PlatformNotSupportedException("The current platform doesn't support MemoryLimit.");
  34. }
  35. var usage = _getAllocatedBytesForCurrentThread();
  36. #endif
  37. if (usage - _initialMemoryUsage > _memoryLimit)
  38. {
  39. Throw.MemoryLimitExceededException($"Script has allocated {usage - _initialMemoryUsage} but is limited to {_memoryLimit}");
  40. }
  41. }
  42. public override void Reset()
  43. {
  44. #if NET8_0_OR_GREATER
  45. _initialMemoryUsage = GC.GetAllocatedBytesForCurrentThread();
  46. #else
  47. _initialMemoryUsage = _getAllocatedBytesForCurrentThread?.Invoke() ?? 0;
  48. #endif
  49. }
  50. }