JavaScriptObfuscatorMemory.spec.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { assert } from 'chai';
  2. import { readFileAsString } from '../helpers/readFileAsString';
  3. import { StringArrayEncoding } from '../../src/enums/node-transformers/string-array-transformers/StringArrayEncoding';
  4. import { JavaScriptObfuscator } from '../../src/JavaScriptObfuscatorFacade';
  5. const heapValueToMB = (value: number) => Math.round(value / 1024 / 1024 * 100) / 100;
  6. describe('JavaScriptObfuscator memory', function () {
  7. const iterationsCount: number = 500;
  8. const gcDiffThreshold: number = 10;
  9. const allowedHeapDiffThreshold: number = 80;
  10. this.timeout(250000);
  11. describe('memory: heap usage', () => {
  12. it('should keep heap usage without memory leaks', () => {
  13. const sourceCode: string = readFileAsString('./test/fixtures/sample.js');
  14. const maxHeapUsed: number[] = [];
  15. let prevHeapUsed: number | null = null;
  16. for (let i: number = 0; i < iterationsCount; i++) {
  17. JavaScriptObfuscator.obfuscate(
  18. sourceCode,
  19. {
  20. compact: true,
  21. controlFlowFlattening: true,
  22. controlFlowFlatteningThreshold: 0.75,
  23. deadCodeInjection: true,
  24. deadCodeInjectionThreshold: 0.4,
  25. debugProtection: false,
  26. debugProtectionInterval: 0,
  27. disableConsoleOutput: true,
  28. identifierNamesGenerator: 'mangled',
  29. log: false,
  30. renameGlobals: false,
  31. stringArrayRotate: true,
  32. selfDefending: true,
  33. stringArrayShuffle: true,
  34. splitStrings: true,
  35. splitStringsChunkLength: 2,
  36. stringArray: true,
  37. stringArrayEncoding: [StringArrayEncoding.Base64],
  38. stringArrayThreshold: 0.75,
  39. transformObjectKeys: true,
  40. unicodeEscapeSequence: false
  41. }
  42. );
  43. const heap = process.memoryUsage();
  44. const heapUsed: number = heapValueToMB(heap.heapUsed);
  45. const gcDiff: number = (prevHeapUsed ?? heapUsed) - heapUsed;
  46. if (prevHeapUsed && gcDiff > gcDiffThreshold) {
  47. maxHeapUsed.push(prevHeapUsed);
  48. }
  49. prevHeapUsed = heapUsed;
  50. }
  51. const sortedMaxHeapUsed: number[] = [...maxHeapUsed].sort((a: number, b: number) => a - b);
  52. const firstMaxHeapMBUsed: number = sortedMaxHeapUsed[0] ?? 0;
  53. const lastMaxHeapMbUsed: number = sortedMaxHeapUsed[sortedMaxHeapUsed.length - 1] ?? 0;
  54. const diff: number = lastMaxHeapMbUsed - firstMaxHeapMBUsed;
  55. assert.closeTo(diff, 0, allowedHeapDiffThreshold);
  56. });
  57. });
  58. });