2
0

ArrayBufferInstance.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. using Jint.Native.Object;
  2. using Jint.Native.TypedArray;
  3. using Jint.Runtime;
  4. namespace Jint.Native.ArrayBuffer
  5. {
  6. /// <summary>
  7. /// https://tc39.es/ecma262/#sec-arraybuffer-objects
  8. /// </summary>
  9. internal sealed class ArrayBufferInstance : ObjectInstance
  10. {
  11. // so that we don't need to allocate while or reading setting values
  12. private readonly byte[] _workBuffer = new byte[8];
  13. private byte[]? _arrayBufferData;
  14. private readonly JsValue _arrayBufferDetachKey = Undefined;
  15. internal ArrayBufferInstance(
  16. Engine engine,
  17. ulong byteLength) : base(engine)
  18. {
  19. var block = byteLength > 0 ? CreateByteDataBlock(byteLength) : System.Array.Empty<byte>();
  20. _arrayBufferData = block;
  21. }
  22. private byte[] CreateByteDataBlock(ulong byteLength)
  23. {
  24. if (byteLength > int.MaxValue)
  25. {
  26. ExceptionHelper.ThrowRangeError(_engine.Realm, "Array buffer allocation failed");
  27. }
  28. return new byte[byteLength];
  29. }
  30. internal int ArrayBufferByteLength => _arrayBufferData?.Length ?? 0;
  31. internal byte[]? ArrayBufferData => _arrayBufferData;
  32. internal bool IsDetachedBuffer => _arrayBufferData is null;
  33. internal bool IsSharedArrayBuffer => false; // TODO SharedArrayBuffer
  34. /// <summary>
  35. /// https://tc39.es/ecma262/#sec-detacharraybuffer
  36. /// </summary>
  37. internal void DetachArrayBuffer(JsValue? key = null)
  38. {
  39. key ??= Undefined;
  40. if (!SameValue(_arrayBufferDetachKey, key))
  41. {
  42. ExceptionHelper.ThrowTypeError(_engine.Realm);
  43. }
  44. _arrayBufferData = null;
  45. }
  46. /// <summary>
  47. /// https://tc39.es/ecma262/#sec-clonearraybuffer
  48. /// </summary>
  49. internal ArrayBufferInstance CloneArrayBuffer(
  50. ArrayBufferConstructor constructor,
  51. int srcByteOffset,
  52. uint srcLength)
  53. {
  54. var targetBuffer = constructor.AllocateArrayBuffer(_engine.Realm.Intrinsics.ArrayBuffer, srcLength);
  55. AssertNotDetached();
  56. var srcBlock = _arrayBufferData!;
  57. var targetBlock = targetBuffer.ArrayBufferData!;
  58. // TODO SharedArrayBuffer would use this
  59. //CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset, srcLength).
  60. System.Array.Copy(srcBlock, srcByteOffset, targetBlock, 0, srcLength);
  61. return targetBuffer;
  62. }
  63. /// <summary>
  64. /// https://tc39.es/ecma262/#sec-getvaluefrombuffer
  65. /// </summary>
  66. internal TypedArrayValue GetValueFromBuffer(
  67. int byteIndex,
  68. TypedArrayElementType type,
  69. bool isTypedArray,
  70. ArrayBufferOrder order,
  71. bool? isLittleEndian = null)
  72. {
  73. if (!IsSharedArrayBuffer)
  74. {
  75. // If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  76. return RawBytesToNumeric(type, byteIndex, isLittleEndian ?? BitConverter.IsLittleEndian);
  77. }
  78. /*
  79. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent EsprimaExtensions.Record.
  80. b. Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  81. c. If isTypedArray is true and IsNoTearConfiguration(type, order) is true, let noTear be true; otherwise let noTear be false.
  82. d. Let rawValue be a List of length elementSize whose elements are nondeterministically chosen byte values.
  83. e. NOTE: In implementations, rawValue is the result of a non-atomic or atomic read instruction on the underlying hardware. The nondeterminism is a semantic prescription of the memory model to describe observable behaviour of hardware with weak consistency.
  84. f. Let readEvent be ReadSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }.
  85. g. Append readEvent to eventList.
  86. h. Append Chosen Value EsprimaExtensions.Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue } to execution.[[ChosenValues]].
  87. */
  88. ExceptionHelper.ThrowNotImplementedException("SharedArrayBuffer not implemented");
  89. return default;
  90. }
  91. /// <summary>
  92. /// https://tc39.es/ecma262/#sec-rawbytestonumeric
  93. /// </summary>
  94. internal TypedArrayValue RawBytesToNumeric(TypedArrayElementType type, int byteIndex, bool isLittleEndian)
  95. {
  96. var elementSize = type.GetElementSize();
  97. var rawBytes = _arrayBufferData!;
  98. // 8 byte values require a little more at the moment
  99. var needsReverse = !isLittleEndian
  100. && elementSize > 1
  101. && type is TypedArrayElementType.Float32 or TypedArrayElementType.Float64 or TypedArrayElementType.BigInt64 or TypedArrayElementType.BigUint64;
  102. if (needsReverse)
  103. {
  104. System.Array.Copy(rawBytes, byteIndex, _workBuffer, 0, elementSize);
  105. byteIndex = 0;
  106. System.Array.Reverse(_workBuffer, 0, elementSize);
  107. rawBytes = _workBuffer;
  108. }
  109. if (type == TypedArrayElementType.Float32)
  110. {
  111. // rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2019 binary32 value.
  112. var value = BitConverter.ToSingle(rawBytes, byteIndex);
  113. // If value is an IEEE 754-2019 binary32 NaN value, return the NaN Number value.
  114. if (float.IsNaN(value))
  115. {
  116. return double.NaN;
  117. }
  118. return value;
  119. }
  120. if (type == TypedArrayElementType.Float64)
  121. {
  122. // rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2019 binary64 value.
  123. var value = BitConverter.ToDouble(rawBytes, byteIndex);
  124. return value;
  125. }
  126. if (type == TypedArrayElementType.BigUint64)
  127. {
  128. var value = BitConverter.ToUInt64(rawBytes, byteIndex);
  129. return value;
  130. }
  131. if (type == TypedArrayElementType.BigInt64)
  132. {
  133. var value = BitConverter.ToInt64(rawBytes, byteIndex);
  134. return value;
  135. }
  136. TypedArrayValue? arrayValue = type switch
  137. {
  138. TypedArrayElementType.Int8 => ((sbyte) rawBytes[byteIndex]),
  139. TypedArrayElementType.Uint8 => (rawBytes[byteIndex]),
  140. TypedArrayElementType.Uint8C =>(rawBytes[byteIndex]),
  141. TypedArrayElementType.Int16 => (isLittleEndian
  142. ? (short) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8))
  143. : (short) (rawBytes[byteIndex + 1] | (rawBytes[byteIndex] << 8))
  144. ),
  145. TypedArrayElementType.Uint16 => (isLittleEndian
  146. ? (ushort) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8))
  147. : (ushort) (rawBytes[byteIndex + 1] | (rawBytes[byteIndex] << 8))
  148. ),
  149. TypedArrayElementType.Int32 => (isLittleEndian
  150. ? rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8) | (rawBytes[byteIndex + 2] << 16) | (rawBytes[byteIndex + 3] << 24)
  151. : rawBytes[byteIndex + 3] | (rawBytes[byteIndex + 2] << 8) | (rawBytes[byteIndex + 1] << 16) | (rawBytes[byteIndex + 0] << 24)
  152. ),
  153. TypedArrayElementType.Uint32 => (isLittleEndian
  154. ? (uint) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8) | (rawBytes[byteIndex + 2] << 16) | (rawBytes[byteIndex + 3] << 24))
  155. : (uint) (rawBytes[byteIndex + 3] | (rawBytes[byteIndex + 2] << 8) | (rawBytes[byteIndex + 1] << 16) | (rawBytes[byteIndex] << 24))
  156. ),
  157. _ => null
  158. };
  159. if (arrayValue is null)
  160. {
  161. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(type), type.ToString());
  162. }
  163. return arrayValue.Value;
  164. }
  165. /// <summary>
  166. /// https://tc39.es/ecma262/#sec-setvalueinbuffer
  167. /// </summary>
  168. internal void SetValueInBuffer(
  169. int byteIndex,
  170. TypedArrayElementType type,
  171. TypedArrayValue value,
  172. bool isTypedArray,
  173. ArrayBufferOrder order,
  174. bool? isLittleEndian = null)
  175. {
  176. var block = _arrayBufferData!;
  177. if (!IsSharedArrayBuffer)
  178. {
  179. // If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  180. var rawBytes = NumericToRawBytes(type, value, isLittleEndian ?? BitConverter.IsLittleEndian);
  181. System.Array.Copy(rawBytes, 0, block, byteIndex, type.GetElementSize());
  182. }
  183. else
  184. {
  185. /*
  186. a. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  187. b. Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  188. c. If isTypedArray is true and IsNoTearConfiguration(type, order) is true, let noTear be true; otherwise let noTear be false.
  189. d. Append WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes } to eventList.
  190. */
  191. ExceptionHelper.ThrowNotImplementedException("SharedArrayBuffer not implemented");
  192. }
  193. }
  194. private byte[] NumericToRawBytes(TypedArrayElementType type, TypedArrayValue value, bool isLittleEndian)
  195. {
  196. byte[] rawBytes;
  197. if (type == TypedArrayElementType.Float32)
  198. {
  199. // Let rawBytes be a List whose elements are the 4 bytes that are the result of converting value to IEEE 754-2019 binary32 format using roundTiesToEven mode. If isLittleEndian is false, the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value is NaN, rawBytes may be set to any implementation chosen IEEE 754-2019 binary32 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishable NaN value.
  200. rawBytes = BitConverter.GetBytes((float) value.DoubleValue);
  201. }
  202. else if (type == TypedArrayElementType.Float64)
  203. {
  204. // Let rawBytes be a List whose elements are the 8 bytes that are the IEEE 754-2019 binary64 format encoding of value. If isLittleEndian is false, the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value is NaN, rawBytes may be set to any implementation chosen IEEE 754-2019 binary64 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishable NaN value.
  205. rawBytes = BitConverter.GetBytes(value.DoubleValue);
  206. }
  207. else if (type == TypedArrayElementType.BigInt64)
  208. {
  209. rawBytes = BitConverter.GetBytes(TypeConverter.ToBigInt64(value.BigInteger));
  210. }
  211. else if (type == TypedArrayElementType.BigUint64)
  212. {
  213. rawBytes = BitConverter.GetBytes(TypeConverter.ToBigUint64(value.BigInteger));
  214. }
  215. else
  216. {
  217. // inlined conversion for faster speed instead of getting the method in spec
  218. var doubleValue = value.DoubleValue;
  219. var intValue = double.IsNaN(doubleValue) || doubleValue == 0 || double.IsInfinity(doubleValue)
  220. ? 0
  221. : (long) doubleValue;
  222. rawBytes = _workBuffer;
  223. switch (type)
  224. {
  225. case TypedArrayElementType.Int8:
  226. rawBytes[0] = (byte) (sbyte) intValue;
  227. break;
  228. case TypedArrayElementType.Uint8:
  229. rawBytes[0] = (byte) intValue;
  230. break;
  231. case TypedArrayElementType.Uint8C:
  232. rawBytes[0] = (byte) TypeConverter.ToUint8Clamp(value.DoubleValue);
  233. break;
  234. case TypedArrayElementType.Int16:
  235. #if !NETSTANDARD2_1
  236. rawBytes = BitConverter.GetBytes((short) intValue);
  237. #else
  238. BitConverter.TryWriteBytes(rawBytes, (short) intValue);
  239. #endif
  240. break;
  241. case TypedArrayElementType.Uint16:
  242. #if !NETSTANDARD2_1
  243. rawBytes = BitConverter.GetBytes((ushort) intValue);
  244. #else
  245. BitConverter.TryWriteBytes(rawBytes, (ushort) intValue);
  246. #endif
  247. break;
  248. case TypedArrayElementType.Int32:
  249. #if !NETSTANDARD2_1
  250. rawBytes = BitConverter.GetBytes((uint) intValue);
  251. #else
  252. BitConverter.TryWriteBytes(rawBytes, (uint) intValue);
  253. #endif
  254. break;
  255. case TypedArrayElementType.Uint32:
  256. #if !NETSTANDARD2_1
  257. rawBytes = BitConverter.GetBytes((uint) intValue);
  258. #else
  259. BitConverter.TryWriteBytes(rawBytes, (uint) intValue);
  260. #endif
  261. break;
  262. default:
  263. ExceptionHelper.ThrowArgumentOutOfRangeException();
  264. return null;
  265. }
  266. }
  267. var elementSize = type.GetElementSize();
  268. if (!isLittleEndian && elementSize > 1)
  269. {
  270. System.Array.Reverse(rawBytes, 0, elementSize);
  271. }
  272. return rawBytes;
  273. }
  274. internal void AssertNotDetached()
  275. {
  276. if (IsDetachedBuffer)
  277. {
  278. ExceptionHelper.ThrowTypeError(_engine.Realm, "ArrayBuffer has been detached");
  279. }
  280. }
  281. }
  282. }