ArrayBufferInstance.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. using System;
  2. using Jint.Native.Object;
  3. using Jint.Native.TypedArray;
  4. using Jint.Runtime;
  5. namespace Jint.Native.ArrayBuffer
  6. {
  7. /// <summary>
  8. /// https://tc39.es/ecma262/#sec-arraybuffer-objects
  9. /// </summary>
  10. public sealed class ArrayBufferInstance : ObjectInstance
  11. {
  12. // so that we don't need to allocate while or reading setting values
  13. private readonly byte[] _workBuffer = new byte[8];
  14. private byte[] _arrayBufferData;
  15. private readonly JsValue _arrayBufferDetachKey = Undefined;
  16. internal ArrayBufferInstance(
  17. Engine engine,
  18. ulong byteLength) : base(engine)
  19. {
  20. var block = byteLength > 0 ? CreateByteDataBlock(byteLength) : System.Array.Empty<byte>();
  21. _arrayBufferData = block;
  22. }
  23. private byte[] CreateByteDataBlock(ulong byteLength)
  24. {
  25. if (byteLength > int.MaxValue)
  26. {
  27. ExceptionHelper.ThrowRangeError(_engine.Realm, "Array buffer allocation failed");
  28. }
  29. return new byte[byteLength];
  30. }
  31. internal int ArrayBufferByteLength => _arrayBufferData.Length;
  32. internal byte[] ArrayBufferData => _arrayBufferData;
  33. internal bool IsDetachedBuffer => _arrayBufferData is null;
  34. internal bool IsSharedArrayBuffer => false; // TODO SharedArrayBuffer
  35. /// <summary>
  36. /// https://tc39.es/ecma262/#sec-detacharraybuffer
  37. /// </summary>
  38. internal void DetachArrayBuffer(JsValue key = null)
  39. {
  40. key ??= Undefined;
  41. if (!SameValue(_arrayBufferDetachKey, key))
  42. {
  43. ExceptionHelper.ThrowTypeError(_engine.Realm);
  44. }
  45. _arrayBufferData = null;
  46. }
  47. /// <summary>
  48. /// https://tc39.es/ecma262/#sec-clonearraybuffer
  49. /// </summary>
  50. internal ArrayBufferInstance CloneArrayBuffer(
  51. ArrayBufferConstructor constructor,
  52. int srcByteOffset,
  53. uint srcLength,
  54. JsValue cloneConstructor)
  55. {
  56. var targetBuffer = constructor.AllocateArrayBuffer(cloneConstructor, srcLength);
  57. AssertNotDetached();
  58. var srcBlock = _arrayBufferData;
  59. var targetBlock = targetBuffer.ArrayBufferData;
  60. // TODO SharedArrayBuffer would use this
  61. //CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset, srcLength).
  62. System.Array.Copy(srcBlock, srcByteOffset, targetBlock, 0, srcLength);
  63. return targetBuffer;
  64. }
  65. /// <summary>
  66. /// https://tc39.es/ecma262/#sec-getvaluefrombuffer
  67. /// </summary>
  68. internal double GetValueFromBuffer(
  69. int byteIndex,
  70. TypedArrayElementType type,
  71. bool isTypedArray,
  72. ArrayBufferOrder order,
  73. bool? isLittleEndian = null)
  74. {
  75. if (!IsSharedArrayBuffer)
  76. {
  77. // If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  78. return RawBytesToNumeric(type, byteIndex, isLittleEndian ?? BitConverter.IsLittleEndian);
  79. }
  80. /*
  81. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent EsprimaExtensions.Record.
  82. b. Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  83. c. If isTypedArray is true and IsNoTearConfiguration(type, order) is true, let noTear be true; otherwise let noTear be false.
  84. d. Let rawValue be a List of length elementSize whose elements are nondeterministically chosen byte values.
  85. 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.
  86. f. Let readEvent be ReadSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }.
  87. g. Append readEvent to eventList.
  88. h. Append Chosen Value EsprimaExtensions.Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue } to execution.[[ChosenValues]].
  89. */
  90. ExceptionHelper.ThrowNotImplementedException("SharedArrayBuffer not implemented");
  91. return 0;
  92. }
  93. /// <summary>
  94. /// https://tc39.es/ecma262/#sec-rawbytestonumeric
  95. /// </summary>
  96. internal double RawBytesToNumeric(TypedArrayElementType type, int byteIndex, bool isLittleEndian)
  97. {
  98. var elementSize = type.GetElementSize();
  99. var rawBytes = _arrayBufferData;
  100. // floats require a little more at the moment
  101. var needsReverse = !isLittleEndian && elementSize > 1 && (type == TypedArrayElementType.Float32 || type == TypedArrayElementType.Float64);
  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.IsBigIntElementType())
  127. {
  128. // return the BigInt value that corresponds to intValue
  129. ExceptionHelper.ThrowNotImplementedException("BigInt not implemented");
  130. }
  131. long? intValue = type switch
  132. {
  133. TypedArrayElementType.Int8 => ((sbyte) rawBytes[byteIndex]),
  134. TypedArrayElementType.Uint8 => (rawBytes[byteIndex]),
  135. TypedArrayElementType.Uint8C =>(rawBytes[byteIndex]),
  136. TypedArrayElementType.Int16 => (isLittleEndian
  137. ? (short) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8))
  138. : (short) (rawBytes[byteIndex + 1] | (rawBytes[byteIndex] << 8))
  139. ),
  140. TypedArrayElementType.Uint16 => (isLittleEndian
  141. ? (ushort) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8))
  142. : (ushort) (rawBytes[byteIndex + 1] | (rawBytes[byteIndex] << 8))
  143. ),
  144. TypedArrayElementType.Int32 => (isLittleEndian
  145. ? rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8) | (rawBytes[byteIndex + 2] << 16) | (rawBytes[byteIndex + 3] << 24)
  146. : rawBytes[byteIndex + 3] | (rawBytes[byteIndex + 2] << 8) | (rawBytes[byteIndex + 1] << 16) | (rawBytes[byteIndex + 0] << 24)
  147. ),
  148. TypedArrayElementType.Uint32 => (isLittleEndian
  149. ? (uint) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8) | (rawBytes[byteIndex + 2] << 16) | (rawBytes[byteIndex + 3] << 24))
  150. : (uint) (rawBytes[byteIndex + 3] | (rawBytes[byteIndex + 2] << 8) | (rawBytes[byteIndex + 1] << 16) | (rawBytes[byteIndex] << 24))
  151. ),
  152. _ => null
  153. };
  154. if (intValue is null)
  155. {
  156. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(type), type.ToString());
  157. }
  158. return (double) intValue;
  159. }
  160. /// <summary>
  161. /// https://tc39.es/ecma262/#sec-setvalueinbuffer
  162. /// </summary>
  163. internal void SetValueInBuffer(
  164. int byteIndex,
  165. TypedArrayElementType type,
  166. double value,
  167. bool isTypedArray,
  168. ArrayBufferOrder order,
  169. bool? isLittleEndian = null)
  170. {
  171. var block = _arrayBufferData;
  172. if (!IsSharedArrayBuffer)
  173. {
  174. // If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  175. var rawBytes = NumericToRawBytes(type, value, isLittleEndian ?? BitConverter.IsLittleEndian);
  176. System.Array.Copy(rawBytes, 0, block, byteIndex, type.GetElementSize());
  177. }
  178. else
  179. {
  180. /*
  181. a. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  182. b. Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  183. c. If isTypedArray is true and IsNoTearConfiguration(type, order) is true, let noTear be true; otherwise let noTear be false.
  184. d. Append WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes } to eventList.
  185. */
  186. ExceptionHelper.ThrowNotImplementedException("SharedArrayBuffer not implemented");
  187. }
  188. }
  189. private byte[] NumericToRawBytes(TypedArrayElementType type, double value, bool isLittleEndian)
  190. {
  191. byte[] rawBytes;
  192. if (type == TypedArrayElementType.Float32)
  193. {
  194. // 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.
  195. rawBytes = BitConverter.GetBytes((float) value);
  196. }
  197. else if (type == TypedArrayElementType.Float64)
  198. {
  199. // 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.
  200. rawBytes = BitConverter.GetBytes(value);
  201. }
  202. else
  203. {
  204. // inlined conversion for faster speed instead of getting the method in spec
  205. var intValue = (long) value;
  206. rawBytes = _workBuffer;
  207. switch (type)
  208. {
  209. case TypedArrayElementType.Int8:
  210. rawBytes[0] = (byte) (sbyte) intValue;
  211. break;
  212. case TypedArrayElementType.Uint8:
  213. rawBytes[0] = (byte) intValue;
  214. break;
  215. case TypedArrayElementType.Uint8C:
  216. rawBytes[0] = (byte) TypeConverter.ToUint8Clamp(value);
  217. break;
  218. case TypedArrayElementType.Int16:
  219. #if !NETSTANDARD2_1
  220. rawBytes = BitConverter.GetBytes((short) intValue);
  221. #else
  222. BitConverter.TryWriteBytes(rawBytes, (short) intValue);
  223. #endif
  224. break;
  225. case TypedArrayElementType.Uint16:
  226. #if !NETSTANDARD2_1
  227. rawBytes = BitConverter.GetBytes((ushort) intValue);
  228. #else
  229. BitConverter.TryWriteBytes(rawBytes, (ushort) intValue);
  230. #endif
  231. break;
  232. case TypedArrayElementType.Int32:
  233. #if !NETSTANDARD2_1
  234. rawBytes = BitConverter.GetBytes((int) intValue);
  235. #else
  236. BitConverter.TryWriteBytes(rawBytes, (int) intValue);
  237. #endif
  238. break;
  239. case TypedArrayElementType.Uint32:
  240. #if !NETSTANDARD2_1
  241. rawBytes = BitConverter.GetBytes((uint) intValue);
  242. #else
  243. BitConverter.TryWriteBytes(rawBytes, (uint) intValue);
  244. #endif
  245. break;
  246. default:
  247. ExceptionHelper.ThrowArgumentOutOfRangeException();
  248. return null;
  249. }
  250. }
  251. var elementSize = type.GetElementSize();
  252. if (!isLittleEndian && elementSize > 1)
  253. {
  254. System.Array.Reverse(rawBytes, 0, elementSize);
  255. }
  256. return rawBytes;
  257. }
  258. internal void AssertNotDetached()
  259. {
  260. if (IsDetachedBuffer)
  261. {
  262. ExceptionHelper.ThrowTypeError(_engine.Realm, "ArrayBuffer has been detached");
  263. }
  264. }
  265. }
  266. }