JAVASCRIPT   32

v8.js

Guest on 15th May 2021 10:24:00 AM

  1. // Copyright (c) 2014, StrongLoop Inc.
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14.  
  15. 'use strict';
  16.  
  17. const { Buffer } = require('buffer');
  18. const {
  19.   Serializer: _Serializer,
  20.   Deserializer: _Deserializer
  21. } = process.binding('serdes');
  22. const { copy } = process.binding('buffer');
  23. const { objectToString } = require('internal/util');
  24. const { FastBuffer } = require('internal/buffer');
  25.  
  26. // Calling exposed c++ functions directly throws exception as it expected to be
  27. // called with new operator and caused an assert to fire.
  28. // Creating JS wrapper so that it gets caught at JS layer.
  29. class Serializer extends _Serializer { }
  30.  
  31. class Deserializer extends _Deserializer { }
  32.  
  33. const {
  34.   cachedDataVersionTag,
  35.   setFlagsFromString,
  36.   heapStatisticsArrayBuffer,
  37.   heapSpaceStatisticsArrayBuffer,
  38.   updateHeapStatisticsArrayBuffer,
  39.   updateHeapSpaceStatisticsArrayBuffer,
  40.  
  41.   // Properties for heap and heap space statistics buffer extraction.
  42.   kTotalHeapSizeIndex,
  43.   kTotalHeapSizeExecutableIndex,
  44.   kTotalPhysicalSizeIndex,
  45.   kTotalAvailableSize,
  46.   kUsedHeapSizeIndex,
  47.   kHeapSizeLimitIndex,
  48.   kDoesZapGarbageIndex,
  49.   kMallocedMemoryIndex,
  50.   kPeakMallocedMemoryIndex,
  51.   kHeapSpaces,
  52.   kHeapSpaceStatisticsPropertiesCount,
  53.   kSpaceSizeIndex,
  54.   kSpaceUsedSizeIndex,
  55.   kSpaceAvailableSizeIndex,
  56.   kPhysicalSpaceSizeIndex
  57. } = process.binding('v8');
  58.  
  59. const kNumberOfHeapSpaces = kHeapSpaces.length;
  60.  
  61. const heapStatisticsBuffer =
  62.     new Float64Array(heapStatisticsArrayBuffer);
  63.  
  64. const heapSpaceStatisticsBuffer =
  65.     new Float64Array(heapSpaceStatisticsArrayBuffer);
  66.  
  67. function getHeapStatistics() {
  68.   const buffer = heapStatisticsBuffer;
  69.  
  70.   updateHeapStatisticsArrayBuffer();
  71.  
  72.   return {
  73.     'total_heap_size': buffer[kTotalHeapSizeIndex],
  74.     'total_heap_size_executable': buffer[kTotalHeapSizeExecutableIndex],
  75.     'total_physical_size': buffer[kTotalPhysicalSizeIndex],
  76.     'total_available_size': buffer[kTotalAvailableSize],
  77.     'used_heap_size': buffer[kUsedHeapSizeIndex],
  78.     'heap_size_limit': buffer[kHeapSizeLimitIndex],
  79.     'malloced_memory': buffer[kMallocedMemoryIndex],
  80.     'peak_malloced_memory': buffer[kPeakMallocedMemoryIndex],
  81.     'does_zap_garbage': buffer[kDoesZapGarbageIndex]
  82.   };
  83. }
  84.  
  85. function getHeapSpaceStatistics() {
  86.   const heapSpaceStatistics = new Array(kNumberOfHeapSpaces);
  87.   const buffer = heapSpaceStatisticsBuffer;
  88.   updateHeapSpaceStatisticsArrayBuffer();
  89.  
  90.   for (var i = 0; i < kNumberOfHeapSpaces; i++) {
  91.     const propertyOffset = i * kHeapSpaceStatisticsPropertiesCount;
  92.     heapSpaceStatistics[i] = {
  93.       space_name: kHeapSpaces[i],
  94.       space_size: buffer[propertyOffset + kSpaceSizeIndex],
  95.       space_used_size: buffer[propertyOffset + kSpaceUsedSizeIndex],
  96.       space_available_size: buffer[propertyOffset + kSpaceAvailableSizeIndex],
  97.       physical_space_size: buffer[propertyOffset + kPhysicalSpaceSizeIndex]
  98.     };
  99.   }
  100.  
  101.   return heapSpaceStatistics;
  102. }
  103.  
  104. /* V8 serialization API */
  105.  
  106. /* JS methods for the base objects */
  107. Serializer.prototype._getDataCloneError = Error;
  108.  
  109. Deserializer.prototype.readRawBytes = function readRawBytes(length) {
  110.   const offset = this._readRawBytes(length);
  111.   // `this.buffer` can be a Buffer or a plain Uint8Array, so just calling
  112.   // `.slice()` doesn't work.
  113.   return new FastBuffer(this.buffer.buffer,
  114.                         this.buffer.byteOffset + offset,
  115.                         length);
  116. };
  117.  
  118. /* Keep track of how to handle different ArrayBufferViews.
  119.  * The default Serializer for Node does not use the V8 methods for serializing
  120.  * those objects because Node's `Buffer` objects use pooled allocation in many
  121.  * cases, and their underlying `ArrayBuffer`s would show up in the
  122.  * serialization. Because a) those may contain sensitive data and the user
  123.  * may not be aware of that and b) they are often much larger than the `Buffer`
  124.  * itself, custom serialization is applied. */
  125. const arrayBufferViewTypes = [Int8Array, Uint8Array, Uint8ClampedArray,
  126.                               Int16Array, Uint16Array, Int32Array, Uint32Array,
  127.                               Float32Array, Float64Array, DataView];
  128.  
  129. const arrayBufferViewTypeToIndex = new Map();
  130.  
  131. {
  132.   const dummy = new ArrayBuffer();
  133.   for (const [i, ctor] of arrayBufferViewTypes.entries()) {
  134.     const tag = objectToString(new ctor(dummy));
  135.     arrayBufferViewTypeToIndex.set(tag, i);
  136.   }
  137. }
  138.  
  139. const bufferConstructorIndex = arrayBufferViewTypes.push(Buffer) - 1;
  140.  
  141. class DefaultSerializer extends Serializer {
  142.   constructor() {
  143.     super();
  144.  
  145.     this._setTreatArrayBufferViewsAsHostObjects(true);
  146.   }
  147.  
  148.   _writeHostObject(abView) {
  149.     let i = 0;
  150.     if (abView.constructor === Buffer) {
  151.       i = bufferConstructorIndex;
  152.     } else {
  153.       const tag = objectToString(abView);
  154.       i = arrayBufferViewTypeToIndex.get(tag);
  155.  
  156.       if (i === undefined) {
  157.         throw this._getDataCloneError(`Unknown host object type: ${tag}`);
  158.       }
  159.     }
  160.     this.writeUint32(i);
  161.     this.writeUint32(abView.byteLength);
  162.     this.writeRawBytes(new Uint8Array(abView.buffer,
  163.                                       abView.byteOffset,
  164.                                       abView.byteLength));
  165.   }
  166. }
  167.  
  168. class DefaultDeserializer extends Deserializer {
  169.   constructor(buffer) {
  170.     super(buffer);
  171.   }
  172.  
  173.   _readHostObject() {
  174.     const typeIndex = this.readUint32();
  175.     const ctor = arrayBufferViewTypes[typeIndex];
  176.     const byteLength = this.readUint32();
  177.     const byteOffset = this._readRawBytes(byteLength);
  178.     const BYTES_PER_ELEMENT = ctor.BYTES_PER_ELEMENT || 1;
  179.  
  180.     const offset = this.buffer.byteOffset + byteOffset;
  181.     if (offset % BYTES_PER_ELEMENT === 0) {
  182.       return new ctor(this.buffer.buffer,
  183.                       offset,
  184.                       byteLength / BYTES_PER_ELEMENT);
  185.     } else {
  186.       // Copy to an aligned buffer first.
  187.       const buffer_copy = Buffer.allocUnsafe(byteLength);
  188.       copy(this.buffer, buffer_copy, 0, byteOffset, byteOffset + byteLength);
  189.       return new ctor(buffer_copy.buffer,
  190.                       buffer_copy.byteOffset,
  191.                       byteLength / BYTES_PER_ELEMENT);
  192.     }
  193.   }
  194. }
  195.  
  196. function serialize(value) {
  197.   const ser = new DefaultSerializer();
  198.   ser.writeHeader();
  199.   ser.writeValue(value);
  200.   return ser.releaseBuffer();
  201. }
  202.  
  203. function deserialize(buffer) {
  204.   const der = new DefaultDeserializer(buffer);
  205.   der.readHeader();
  206.   return der.readValue();
  207. }
  208.  
  209. module.exports = exports = {
  210.   cachedDataVersionTag,
  211.   getHeapStatistics,
  212.   getHeapSpaceStatistics,
  213.   setFlagsFromString,
  214.   Serializer,
  215.   Deserializer,
  216.   DefaultSerializer,
  217.   DefaultDeserializer,
  218.   deserialize,
  219.   serialize
  220. };

Raw Paste


Login or Register to edit or fork this paste. It's free.