All files / lib vm.js

97.71% Statements 427/437
96.26% Branches 103/107
100% Functions 17/17
97.71% Lines 427/437

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 2064x 2064x 1x 2063x 2061x 2061x 2061x 2061x 2061x 2061x 2061x 2061x 2061x 2061x 2061x 2061x 2061x 2061x 2061x 2061x 2064x 6x 6x 6x 6x 6x 6x 2033x 2033x 2033x 2033x 2033x 2033x 2033x 2033x 2033x 2033x 2033x 2033x 2033x 2062x 178x 178x 1854x 2045x 1057x 1x 1x 1x 1x 1056x 1056x 1056x 1056x 1056x 1056x 1056x 1056x 2064x 139x 139x 1179x 1179x 3x 3x 1153x 1179x 139x 139x 724x 724x 724x 724x 3x 3x 673x 724x 139x 139x 282x 282x 282x 139x 139x 823x 823x 4x 4x 4x 823x 139x 1895x 1895x 1895x 1895x 1895x 1849x 1895x 36x 36x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 1864x 1895x 139x 539x 539x 539x 338x 338x 338x 338x 338x 338x 338x 539x 337x 528x 528x 5x 5x 5x 5x 5x 5x 5x 4x 4x 335x 528x 335x 539x 139x 1641x 1641x 18x 18x 1623x 1641x 139x 139x 805x 805x 255x 255x 547x 547x 547x 547x 547x 547x 547x 547x 547x 547x 547x 547x 805x 543x 805x 541x 541x 541x 805x 5x 5x 5x 5x 540x 540x 803x 5x 5x 5x 5x 5x 5x 540x 540x 540x 805x 139x 1978x 1978x 1978x 139x 139x 139x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 10x 6x 6x 6x 139x 100x 100x 100x 16x 16x 16x 16x 91x 77x 77x 93x 93x 100x 139x 257x 257x 3x 3x 257x 257x 257x 257x 139x 934x 934x 1x 1x 934x 934x 139x 30695x 30695x 30695x 30675x 30675x 30675x 30675x 30687x 30687x 30687x 30687x 30687x 30687x 30687x 30687x 30687x 30687x 30687x 30687x 30687x 30687x 30687x 30687x 30695x 30683x 30695x 8x 8x 8x 3x 8x 6x 6x 6x 6x 6x 6x 8x 30676x 30676x 2x 2x 30676x 30676x 30676x 30676x 30676x 30676x 30676x 30676x 30676x 30676x 30676x 30676x 30676x 30676x 30695x     30645x 30674x     30645x 30667x 30630x         30630x 30630x 30630x 30630x 30630x 30630x 30630x 30630x 30630x 30645x 30645x 30695x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 12x 12x 12x 12x 12x 12x 12x 12x 12x     8x 12x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 2x 2x 2x 2x 2x 2x 2x  
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
'use strict';
 
const {
  ArrayPrototypeForEach,
  ArrayPrototypeUnshift,
  Symbol,
  PromiseReject,
  ReflectApply,
} = primordials;
 
const {
  ContextifyScript,
  MicrotaskQueue,
  makeContext,
  isContext: _isContext,
  constants,
  compileFunction: _compileFunction,
  measureMemory: _measureMemory,
} = internalBinding('contextify');
const {
  ERR_CONTEXT_NOT_INITIALIZED,
  ERR_INVALID_ARG_TYPE,
} = require('internal/errors').codes;
const {
  isArrayBufferView,
} = require('internal/util/types');
const {
  validateInt32,
  validateUint32,
  validateString,
  validateArray,
  validateBoolean,
  validateBuffer,
  validateObject,
  validateOneOf,
} = require('internal/validators');
const {
  kVmBreakFirstLineSymbol,
  emitExperimentalWarning,
} = require('internal/util');
const kParsingContext = Symbol('script parsing context');
 
class Script extends ContextifyScript {
  constructor(code, options = {}) {
    code = `${code}`;
    if (typeof options === 'string') {
      options = { filename: options };
    } else {
      validateObject(options, 'options');
    }
 
    const {
      filename = 'evalmachine.<anonymous>',
      lineOffset = 0,
      columnOffset = 0,
      cachedData,
      produceCachedData = false,
      importModuleDynamically,
      [kParsingContext]: parsingContext,
    } = options;
 
    validateString(filename, 'options.filename');
    validateInt32(lineOffset, 'options.lineOffset');
    validateInt32(columnOffset, 'options.columnOffset');
    if (cachedData !== undefined && !isArrayBufferView(cachedData)) {
      throw new ERR_INVALID_ARG_TYPE(
        'options.cachedData',
        ['Buffer', 'TypedArray', 'DataView'],
        cachedData
      );
    }
    validateBoolean(produceCachedData, 'options.produceCachedData');
 
    // Calling `ReThrow()` on a native TryCatch does not generate a new
    // abort-on-uncaught-exception check. A dummy try/catch in JS land
    // protects against that.
    try { // eslint-disable-line no-useless-catch
      super(code,
            filename,
            lineOffset,
            columnOffset,
            cachedData,
            produceCachedData,
            parsingContext);
    } catch (e) {
      throw e; /* node-do-not-add-exception-line */
    }
 
    if (importModuleDynamically !== undefined) {
      if (typeof importModuleDynamically !== 'function') {
        throw new ERR_INVALID_ARG_TYPE('options.importModuleDynamically',
                                       'function',
                                       importModuleDynamically);
      }
      const { importModuleDynamicallyWrap } =
        require('internal/vm/module');
      const { callbackMap } = internalBinding('module_wrap');
      callbackMap.set(this, {
        importModuleDynamically:
          importModuleDynamicallyWrap(importModuleDynamically),
      });
    }
  }
 
  runInThisContext(options) {
    const { breakOnSigint, args } = getRunInContextArgs(options);
    if (breakOnSigint && process.listenerCount('SIGINT') > 0) {
      return sigintHandlersWrap(super.runInThisContext, this, args);
    }
    return ReflectApply(super.runInThisContext, this, args);
  }
 
  runInContext(contextifiedObject, options) {
    validateContext(contextifiedObject);
    const { breakOnSigint, args } = getRunInContextArgs(options);
    ArrayPrototypeUnshift(args, contextifiedObject);
    if (breakOnSigint && process.listenerCount('SIGINT') > 0) {
      return sigintHandlersWrap(super.runInContext, this, args);
    }
    return ReflectApply(super.runInContext, this, args);
  }
 
  runInNewContext(contextObject, options) {
    const context = createContext(contextObject, getContextOptions(options));
    return this.runInContext(context, options);
  }
}
 
function validateContext(contextifiedObject) {
  if (!isContext(contextifiedObject)) {
    throw new ERR_INVALID_ARG_TYPE('contextifiedObject', 'vm.Context',
                                   contextifiedObject);
  }
}
 
function getRunInContextArgs(options = {}) {
  validateObject(options, 'options');
 
  let timeout = options.timeout;
  if (timeout === undefined) {
    timeout = -1;
  } else {
    validateUint32(timeout, 'options.timeout', true);
  }
 
  const {
    displayErrors = true,
    breakOnSigint = false,
    [kVmBreakFirstLineSymbol]: breakFirstLine = false,
  } = options;
 
  validateBoolean(displayErrors, 'options.displayErrors');
  validateBoolean(breakOnSigint, 'options.breakOnSigint');
 
  return {
    breakOnSigint,
    args: [timeout, displayErrors, breakOnSigint, breakFirstLine]
  };
}
 
function getContextOptions(options) {
  if (!options)
    return {};
  const contextOptions = {
    name: options.contextName,
    origin: options.contextOrigin,
    codeGeneration: undefined,
    microtaskMode: options.microtaskMode,
  };
  if (contextOptions.name !== undefined)
    validateString(contextOptions.name, 'options.contextName');
  if (contextOptions.origin !== undefined)
    validateString(contextOptions.origin, 'options.contextOrigin');
  if (options.contextCodeGeneration !== undefined) {
    validateObject(options.contextCodeGeneration,
                   'options.contextCodeGeneration');
    const { strings, wasm } = options.contextCodeGeneration;
    if (strings !== undefined)
      validateBoolean(strings, 'options.contextCodeGeneration.strings');
    if (wasm !== undefined)
      validateBoolean(wasm, 'options.contextCodeGeneration.wasm');
    contextOptions.codeGeneration = { strings, wasm };
  }
  if (options.microtaskMode !== undefined)
    validateString(options.microtaskMode, 'options.microtaskMode');
  return contextOptions;
}
 
function isContext(object) {
  if (typeof object !== 'object' || object === null) {
    throw new ERR_INVALID_ARG_TYPE('object', 'Object', object);
  }
  return _isContext(object);
}
 
let defaultContextNameIndex = 1;
function createContext(contextObject = {}, options = {}) {
  if (isContext(contextObject)) {
    return contextObject;
  }
 
  validateObject(options, 'options');
 
  const {
    name = `VM Context ${defaultContextNameIndex++}`,
    origin,
    codeGeneration,
    microtaskMode
  } = options;
 
  validateString(name, 'options.name');
  if (origin !== undefined)
    validateString(origin, 'options.origin');
  if (codeGeneration !== undefined)
    validateObject(codeGeneration, 'options.codeGeneration');
 
  let strings = true;
  let wasm = true;
  if (codeGeneration !== undefined) {
    ({ strings = true, wasm = true } = codeGeneration);
    validateBoolean(strings, 'options.codeGeneration.strings');
    validateBoolean(wasm, 'options.codeGeneration.wasm');
  }
 
  let microtaskQueue = null;
  if (microtaskMode !== undefined) {
    validateOneOf(microtaskMode, 'options.microtaskMode',
                  ['afterEvaluate', undefined]);
 
    if (microtaskMode === 'afterEvaluate')
      microtaskQueue = new MicrotaskQueue();
  }
 
  makeContext(contextObject, name, origin, strings, wasm, microtaskQueue);
  return contextObject;
}
 
function createScript(code, options) {
  return new Script(code, options);
}
 
// Remove all SIGINT listeners and re-attach them after the wrapped function
// has executed, so that caught SIGINT are handled by the listeners again.
function sigintHandlersWrap(fn, thisArg, argsArray) {
  const sigintListeners = process.rawListeners('SIGINT');
 
  process.removeAllListeners('SIGINT');
 
  try {
    return ReflectApply(fn, thisArg, argsArray);
  } finally {
    // Add using the public methods so that the `newListener` handler of
    // process can re-attach the listeners.
    ArrayPrototypeForEach(sigintListeners, (listener) => {
      process.addListener('SIGINT', listener);
    });
  }
}
 
function runInContext(code, contextifiedObject, options) {
  validateContext(contextifiedObject);
  if (typeof options === 'string') {
    options = {
      filename: options,
      [kParsingContext]: contextifiedObject
    };
  } else {
    options = { ...options, [kParsingContext]: contextifiedObject };
  }
  return createScript(code, options)
    .runInContext(contextifiedObject, options);
}
 
function runInNewContext(code, contextObject, options) {
  if (typeof options === 'string') {
    options = { filename: options };
  }
  contextObject = createContext(contextObject, getContextOptions(options));
  options = { ...options, [kParsingContext]: contextObject };
  return createScript(code, options).runInNewContext(contextObject, options);
}
 
function runInThisContext(code, options) {
  if (typeof options === 'string') {
    options = { filename: options };
  }
  return createScript(code, options).runInThisContext(options);
}
 
function compileFunction(code, params, options = {}) {
  validateString(code, 'code');
  if (params !== undefined) {
    validateArray(params, 'params');
    ArrayPrototypeForEach(params,
                          (param, i) => validateString(param, `params[${i}]`));
  }
 
  const {
    filename = '',
    columnOffset = 0,
    lineOffset = 0,
    cachedData = undefined,
    produceCachedData = false,
    parsingContext = undefined,
    contextExtensions = [],
    importModuleDynamically,
  } = options;
 
  validateString(filename, 'options.filename');
  validateUint32(columnOffset, 'options.columnOffset');
  validateUint32(lineOffset, 'options.lineOffset');
  if (cachedData !== undefined)
    validateBuffer(cachedData, 'options.cachedData');
  validateBoolean(produceCachedData, 'options.produceCachedData');
  if (parsingContext !== undefined) {
    if (
      typeof parsingContext !== 'object' ||
      parsingContext === null ||
      !isContext(parsingContext)
    ) {
      throw new ERR_INVALID_ARG_TYPE(
        'options.parsingContext',
        'Context',
        parsingContext
      );
    }
  }
  validateArray(contextExtensions, 'options.contextExtensions');
  ArrayPrototypeForEach(contextExtensions, (extension, i) => {
    const name = `options.contextExtensions[${i}]`;
    validateObject(extension, name, { nullable: true });
  });
 
  const result = _compileFunction(
    code,
    filename,
    lineOffset,
    columnOffset,
    cachedData,
    produceCachedData,
    parsingContext,
    contextExtensions,
    params
  );
 
  if (produceCachedData) {
    result.function.cachedDataProduced = result.cachedDataProduced;
  }
 
  if (result.cachedData) {
    result.function.cachedData = result.cachedData;
  }
 
  if (importModuleDynamically !== undefined) {
    if (typeof importModuleDynamically !== 'function') {
      throw new ERR_INVALID_ARG_TYPE('options.importModuleDynamically',
                                     'function',
                                     importModuleDynamically);
    }
    const { importModuleDynamicallyWrap } =
      require('internal/vm/module');
    const { callbackMap } = internalBinding('module_wrap');
    const wrapped = importModuleDynamicallyWrap(importModuleDynamically);
    const func = result.function;
    callbackMap.set(result.cacheKey, {
      importModuleDynamically: (s, _k) => wrapped(s, func),
    });
  }
 
  return result.function;
}
 
const measureMemoryModes = {
  summary: constants.measureMemory.mode.SUMMARY,
  detailed: constants.measureMemory.mode.DETAILED,
};
 
const measureMemoryExecutions = {
  default: constants.measureMemory.execution.DEFAULT,
  eager: constants.measureMemory.execution.EAGER,
};
 
function measureMemory(options = {}) {
  emitExperimentalWarning('vm.measureMemory');
  validateObject(options, 'options');
  const { mode = 'summary', execution = 'default' } = options;
  validateOneOf(mode, 'options.mode', ['summary', 'detailed']);
  validateOneOf(execution, 'options.execution', ['default', 'eager']);
  const result = _measureMemory(measureMemoryModes[mode],
                                measureMemoryExecutions[execution]);
  if (result === undefined) {
    return PromiseReject(new ERR_CONTEXT_NOT_INITIALIZED());
  }
  return result;
}
 
module.exports = {
  Script,
  createContext,
  createScript,
  runInContext,
  runInNewContext,
  runInThisContext,
  isContext,
  compileFunction,
  measureMemory,
};
 
if (require('internal/options').getOptionValue('--experimental-vm-modules')) {
  const {
    Module, SourceTextModule, SyntheticModule,
  } = require('internal/vm/module');
  module.exports.Module = Module;
  module.exports.SourceTextModule = SourceTextModule;
  module.exports.SyntheticModule = SyntheticModule;
}