2
0

MemoryLimit.cs 1.6 KB

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