summaryrefslogtreecommitdiff
path: root/test/parallel/test-vm-cached-data.js
blob: 1b14999cdbc2f74c3c891c605c49eceb1f8bf4ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use strict';
const common = require('../common');
const assert = require('assert');
const vm = require('vm');
const spawnSync = require('child_process').spawnSync;

function getSource(tag) {
  return `(function ${tag}() { return '${tag}'; })`;
}

function produce(source, count) {
  if (!count)
    count = 1;

  const out = spawnSync(process.execPath, [ '-e', `
    'use strict';
    const assert = require('assert');
    const vm = require('vm');

    var data;
    for (var i = 0; i < ${count}; i++) {
      var script = new vm.Script(process.argv[1], {
        produceCachedData: true
      });

      assert(!script.cachedDataProduced || script.cachedData instanceof Buffer);

      if (script.cachedDataProduced)
        data = script.cachedData.toString('base64');
    }
    console.log(data);
  `, source]);

  assert.strictEqual(out.status, 0, String(out.stderr));

  return Buffer.from(out.stdout.toString(), 'base64');
}

function testProduceConsume() {
  const source = getSource('original');

  const data = produce(source);

  for (const cachedData of common.getArrayBufferViews(data)) {
    // It should consume code cache
    const script = new vm.Script(source, {
      cachedData
    });
    assert(!script.cachedDataRejected);
    assert.strictEqual(script.runInThisContext()(), 'original');
  }
}
testProduceConsume();

function testProduceMultiple() {
  const source = getSource('original');

  produce(source, 3);
}
testProduceMultiple();

function testRejectInvalid() {
  const source = getSource('invalid');

  const data = produce(source);

  // It should reject invalid code cache
  const script = new vm.Script(getSource('invalid_1'), {
    cachedData: data
  });
  assert(script.cachedDataRejected);
  assert.strictEqual(script.runInThisContext()(), 'invalid_1');
}
testRejectInvalid();

function testRejectSlice() {
  const source = getSource('slice');

  const data = produce(source).slice(4);

  const script = new vm.Script(source, {
    cachedData: data
  });
  assert(script.cachedDataRejected);
}
testRejectSlice();

// It should throw on non-Buffer cachedData
common.expectsError(() => {
  new vm.Script('function abc() {}', {
    cachedData: 'ohai'
  });
}, {
  code: 'ERR_INVALID_ARG_TYPE',
  type: TypeError,
  message: /must be one of type Buffer, TypedArray, or DataView/
});