ArrayBuffer.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. // Implements ArrayBuffer according to Khronos spec.
  6. //----------------------------------------------------------------------------
  7. #pragma once
  8. namespace Js
  9. {
  10. class ArrayBufferParent;
  11. class ArrayBuffer;
  12. class SharedArrayBuffer;
  13. class ArrayBufferContentForDelayedFreeBase;
  14. class ArrayBufferBase : public DynamicObject
  15. {
  16. protected:
  17. #if ENABLE_FAST_ARRAYBUFFER
  18. #define MAX_ASMJS_ARRAYBUFFER_LENGTH 0x100000000 // 4GB
  19. #define MAX_WASM__ARRAYBUFFER_LENGTH 0x200000000 // 8GB
  20. typedef void*(*AllocWrapperType)(size_t);
  21. #define AsmJsVirtualAllocator ((AllocWrapperType)Js::ArrayBuffer::AllocWrapper<MAX_ASMJS_ARRAYBUFFER_LENGTH>)
  22. #define WasmVirtualAllocator ((AllocWrapperType)Js::ArrayBuffer::AllocWrapper<MAX_WASM__ARRAYBUFFER_LENGTH>)
  23. #else
  24. #define AsmJsVirtualAllocator Js::ArrayBuffer::BadAllocCall
  25. #define WasmVirtualAllocator Js::ArrayBuffer::BadAllocCall
  26. static void* __cdecl BadAllocCall(DECLSPEC_GUARD_OVERFLOW size_t length)
  27. {
  28. // This allocator should never be used
  29. Js::Throw::FatalInternalError();
  30. }
  31. #endif
  32. #ifdef _WIN32
  33. static void* __cdecl AllocWrapper(DECLSPEC_GUARD_OVERFLOW size_t length, size_t MaxVirtualSize)
  34. {
  35. LPVOID address = VirtualAlloc(nullptr, MaxVirtualSize, MEM_RESERVE, PAGE_NOACCESS);
  36. //throw out of memory
  37. if (!address)
  38. {
  39. return nullptr;
  40. }
  41. if (length == 0)
  42. {
  43. return address;
  44. }
  45. LPVOID arrayAddress = VirtualAlloc(address, length, MEM_COMMIT, PAGE_READWRITE);
  46. if (!arrayAddress)
  47. {
  48. VirtualFree(address, 0, MEM_RELEASE);
  49. return nullptr;
  50. }
  51. return arrayAddress;
  52. }
  53. template<size_t MaxVirtualSize>
  54. static void* __cdecl AllocWrapper(DECLSPEC_GUARD_OVERFLOW size_t length)
  55. {
  56. return AllocWrapper(length, MaxVirtualSize);
  57. }
  58. static void FreeMemAlloc(Var ptr)
  59. {
  60. BOOL fSuccess = VirtualFree((LPVOID)ptr, 0, MEM_RELEASE);
  61. Assert(fSuccess);
  62. }
  63. #else
  64. static void FreeMemAlloc(Var ptr)
  65. {
  66. // This free function should never be used
  67. Js::Throw::FatalInternalError();
  68. }
  69. #endif
  70. public:
  71. DEFINE_VTABLE_CTOR_ABSTRACT(ArrayBufferBase, DynamicObject);
  72. virtual void MarshalToScriptContext(Js::ScriptContext * scriptContext) = 0;
  73. ArrayBufferBase(DynamicType *type) : DynamicObject(type), isDetached(false) { }
  74. bool IsDetached() { return isDetached; }
  75. #if ENABLE_TTD
  76. virtual void MarshalCrossSite_TTDInflate() = 0;
  77. #endif
  78. virtual bool IsArrayBuffer() = 0;
  79. virtual bool IsSharedArrayBuffer() = 0;
  80. virtual bool IsWebAssemblyArrayBuffer() { return false; }
  81. virtual ArrayBuffer * GetAsArrayBuffer() = 0;
  82. virtual SharedArrayBuffer * GetAsSharedArrayBuffer() { return nullptr; }
  83. virtual void AddParent(ArrayBufferParent* parent) { }
  84. virtual uint32 GetByteLength() const = 0;
  85. virtual BYTE* GetBuffer() const = 0;
  86. virtual bool IsValidVirtualBufferLength(uint length) const { return false; };
  87. static int GetIsDetachedOffset() { return offsetof(ArrayBufferBase, isDetached); }
  88. protected:
  89. Field(bool) isDetached;
  90. };
  91. template <> bool VarIsImpl<ArrayBufferBase>(RecyclableObject* obj);
  92. // This encapsulate buffer blob and the refCount.
  93. class RefCountedBuffer
  94. {
  95. private:
  96. FieldNoBarrier(BYTE*) buffer; // Points to a heap allocated RGBA buffer, can be null
  97. // Addref/release counter for current buffer, this is needed hold the current buffer alive
  98. Field(long) refCount;
  99. public:
  100. long AddRef();
  101. long Release();
  102. BYTE* GetBuffer() { return buffer; };
  103. long GetRefCount() { return refCount; }
  104. static int GetBufferOffset() { return offsetof(RefCountedBuffer, buffer); }
  105. RefCountedBuffer(BYTE* b)
  106. : buffer(b), refCount(1)
  107. { }
  108. };
  109. class ArrayBuffer : public ArrayBufferBase
  110. {
  111. public:
  112. // we need to install cross-site thunk on the nested array buffer when marshaling
  113. // typed array.
  114. DEFINE_VTABLE_CTOR_ABSTRACT(ArrayBuffer, ArrayBufferBase);
  115. private:
  116. void DetachBufferFromParent(ArrayBufferParent* parent);
  117. public:
  118. template <typename FreeFN>
  119. class ArrayBufferDetachedState : public ArrayBufferDetachedStateBase
  120. {
  121. public:
  122. FreeFN* freeFunction;
  123. Recycler* recycler;
  124. ArrayBufferDetachedState(RefCountedBuffer* buffer, uint32 bufferLength, FreeFN* freeFunction, Recycler* r, ArrayBufferAllocationType allocationType)
  125. : ArrayBufferDetachedStateBase(TypeIds_ArrayBuffer, buffer, bufferLength, allocationType),
  126. recycler(r),
  127. freeFunction(freeFunction)
  128. {}
  129. virtual void ClearSelfOnly() override
  130. {
  131. HeapDelete(this);
  132. }
  133. virtual void DiscardState() override
  134. {
  135. DiscardStateBase(freeFunction);
  136. }
  137. virtual void Discard() override
  138. {
  139. ClearSelfOnly();
  140. }
  141. };
  142. template <typename Allocator>
  143. ArrayBuffer(DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type, Allocator allocator);
  144. ArrayBuffer(byte* buffer, DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type, bool isExternal = false);
  145. ArrayBuffer(RefCountedBuffer* buffContent, DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type);
  146. class EntryInfo
  147. {
  148. public:
  149. static FunctionInfo NewInstance;
  150. static FunctionInfo Slice;
  151. static FunctionInfo IsView;
  152. static FunctionInfo GetterByteLength;
  153. static FunctionInfo GetterSymbolSpecies;
  154. #if ENABLE_DEBUG_CONFIG_OPTIONS
  155. static FunctionInfo Detach;
  156. #endif
  157. };
  158. static Var NewInstance(RecyclableObject* function, CallInfo callInfo, ...);
  159. static Var EntrySlice(RecyclableObject* function, CallInfo callInfo, ...);
  160. static Var EntryIsView(RecyclableObject* function, CallInfo callInfo, ...);
  161. static Var EntryGetterByteLength(RecyclableObject* function, CallInfo callInfo, ...);
  162. static Var EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...);
  163. #if ENABLE_DEBUG_CONFIG_OPTIONS
  164. static Var EntryDetach(RecyclableObject* function, CallInfo callInfo, ...);
  165. #endif
  166. static ArrayBuffer* NewFromDetachedState(DetachedStateBase* state, JavascriptLibrary *library);
  167. virtual BOOL GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext) override;
  168. virtual BOOL GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext) override;
  169. ArrayBufferDetachedStateBase* DetachAndGetState(bool queueForDelayFree = true);
  170. virtual uint32 GetByteLength() const override;
  171. virtual BYTE* GetBuffer() const override;
  172. RefCountedBuffer *GetBufferContent() { return bufferContent; }
  173. static int GetBufferContentsOffset() { return offsetof(ArrayBuffer, bufferContent); }
  174. static int GetByteLengthOffset() { return offsetof(ArrayBuffer, bufferLength); }
  175. virtual void AddParent(ArrayBufferParent* parent) override;
  176. #if defined(TARGET_64)
  177. //maximum 2G -1 for amd64
  178. static const uint32 MaxArrayBufferLength = 0x7FFFFFFF;
  179. #else
  180. // maximum 1G to avoid arithmetic overflow.
  181. static const uint32 MaxArrayBufferLength = 1 << 30;
  182. #endif
  183. static const uint32 ParentsCleanupThreshold = 1000;
  184. virtual bool IsValidAsmJsBufferLength(uint length, bool forceCheck = false) { return false; }
  185. virtual bool IsArrayBuffer() override { return true; }
  186. virtual bool IsSharedArrayBuffer() override { return false; }
  187. virtual ArrayBuffer * GetAsArrayBuffer() override;
  188. virtual ArrayBufferContentForDelayedFreeBase* CopyBufferContentForDelayedFree(RefCountedBuffer * content, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength);
  189. static uint32 ToIndex(Var value, int32 errorCode, ScriptContext *scriptContext, uint32 MaxAllowedLength, bool checkSameValueZero = true);
  190. protected:
  191. virtual void ReportExternalMemoryFree();
  192. void Detach();
  193. typedef void __cdecl FreeFn(void* ptr);
  194. virtual ArrayBufferDetachedStateBase* CreateDetachedState(RefCountedBuffer * content, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength) = 0;
  195. // This function will be called from External buffer and projection buffer as they pass the buffer
  196. virtual void ReleaseBufferContent();
  197. //In most cases, the ArrayBuffer will only have one parent
  198. Field(RecyclerWeakReference<ArrayBufferParent>*) primaryParent;
  199. struct OtherParents :public SList<RecyclerWeakReference<ArrayBufferParent>*, Recycler>
  200. {
  201. OtherParents(Recycler* recycler)
  202. :SList<RecyclerWeakReference<ArrayBufferParent>*, Recycler>(recycler), increasedCount(0)
  203. {
  204. }
  205. Field(uint) increasedCount;
  206. };
  207. Field(OtherParents*) otherParents;
  208. FieldNoBarrier(RefCountedBuffer *) bufferContent;
  209. Field(uint32) bufferLength; // Number of bytes allocated
  210. };
  211. template <> inline bool VarIsImpl<ArrayBuffer>(RecyclableObject* obj)
  212. {
  213. return JavascriptOperators::GetTypeId(obj) == TypeIds_ArrayBuffer;
  214. }
  215. class ArrayBufferParent : public ArrayObject
  216. {
  217. friend ArrayBuffer;
  218. friend ArrayBufferBase;
  219. private:
  220. Field(ArrayBufferBase*) arrayBuffer;
  221. protected:
  222. DEFINE_VTABLE_CTOR_ABSTRACT(ArrayBufferParent, ArrayObject);
  223. ArrayBufferParent(DynamicType * type, uint32 length, ArrayBufferBase* arrayBuffer)
  224. : ArrayObject(type, /*initSlots*/true, length),
  225. arrayBuffer(arrayBuffer)
  226. {
  227. arrayBuffer->AddParent(this);
  228. }
  229. public:
  230. ArrayBufferBase* GetArrayBuffer() const
  231. {
  232. return this->arrayBuffer;
  233. }
  234. #if ENABLE_TTD
  235. public:
  236. virtual void MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor) override;
  237. virtual void ProcessCorePaths() override;
  238. #endif
  239. };
  240. // Normally we use malloc/free; for ArrayBuffer created from projection we need to use different allocator.
  241. class JavascriptArrayBuffer : public ArrayBuffer
  242. {
  243. protected:
  244. DEFINE_VTABLE_CTOR(JavascriptArrayBuffer, ArrayBuffer);
  245. DEFINE_MARSHAL_OBJECT_TO_SCRIPT_CONTEXT(JavascriptArrayBuffer);
  246. public:
  247. static JavascriptArrayBuffer* Create(DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type);
  248. static JavascriptArrayBuffer* Create(byte* buffer, DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type);
  249. static JavascriptArrayBuffer* Create(RefCountedBuffer* buffer, DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type);
  250. virtual void Dispose(bool isShutdown) override;
  251. virtual void Finalize(bool isShutdown) override;
  252. static bool IsValidAsmJsBufferLengthAlgo(uint length, bool forceCheck);
  253. virtual bool IsValidAsmJsBufferLength(uint length, bool forceCheck = false) override;
  254. virtual bool IsValidVirtualBufferLength(uint length) const override;
  255. protected:
  256. JavascriptArrayBuffer(DynamicType * type);
  257. virtual ArrayBufferDetachedStateBase* CreateDetachedState(RefCountedBuffer * content, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength) override;
  258. template<typename Allocator>
  259. JavascriptArrayBuffer(uint32 length, DynamicType * type, Allocator allocator): ArrayBuffer(length, type, allocator){}
  260. JavascriptArrayBuffer(uint32 length, DynamicType * type);
  261. JavascriptArrayBuffer(byte* buffer, uint32 length, DynamicType * type);
  262. JavascriptArrayBuffer(RefCountedBuffer* buffer, uint32 length, DynamicType * type);
  263. #if ENABLE_TTD
  264. public:
  265. virtual TTD::NSSnapObjects::SnapObjectType GetSnapTag_TTD() const override;
  266. virtual void ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc) override;
  267. #endif
  268. };
  269. #ifdef ENABLE_WASM
  270. class WebAssemblyArrayBuffer : public JavascriptArrayBuffer
  271. {
  272. template<typename Allocator>
  273. WebAssemblyArrayBuffer(uint32 length, DynamicType * type, Allocator allocator);
  274. WebAssemblyArrayBuffer(uint32 length, DynamicType * type);
  275. WebAssemblyArrayBuffer(byte* buffer, uint32 length, DynamicType * type);
  276. protected:
  277. DEFINE_VTABLE_CTOR(WebAssemblyArrayBuffer, JavascriptArrayBuffer);
  278. DEFINE_MARSHAL_OBJECT_TO_SCRIPT_CONTEXT(WebAssemblyArrayBuffer);
  279. public:
  280. static WebAssemblyArrayBuffer* Create(byte* buffer, DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type);
  281. WebAssemblyArrayBuffer* GrowMemory(uint32 newBufferLength);
  282. virtual bool IsValidVirtualBufferLength(uint length) const override;
  283. virtual bool IsWebAssemblyArrayBuffer() override { return true; }
  284. protected:
  285. virtual ArrayBufferDetachedStateBase* CreateDetachedState(RefCountedBuffer * content, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength) override;
  286. };
  287. #endif
  288. // the memory must be allocated via CoTaskMemAlloc.
  289. class ProjectionArrayBuffer : public ArrayBuffer
  290. {
  291. protected:
  292. DEFINE_VTABLE_CTOR(ProjectionArrayBuffer, ArrayBuffer);
  293. DEFINE_MARSHAL_OBJECT_TO_SCRIPT_CONTEXT(ProjectionArrayBuffer);
  294. typedef void __stdcall FreeFn(LPVOID ptr);
  295. virtual ArrayBufferDetachedStateBase* CreateDetachedState(RefCountedBuffer * content, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength) override
  296. {
  297. return HeapNew(ArrayBufferDetachedState<FreeFn>, content, bufferLength, CoTaskMemFree, GetScriptContext()->GetRecycler(), ArrayBufferAllocationType::CoTask);
  298. }
  299. public:
  300. // Create constructor. script engine creates a buffer allocated via CoTaskMemAlloc.
  301. static ProjectionArrayBuffer* Create(DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type);
  302. // take over ownership. a CoTaskMemAlloc'ed buffer passed in via projection.
  303. static ProjectionArrayBuffer* Create(byte* buffer, DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type);
  304. static ProjectionArrayBuffer* Create(RefCountedBuffer* buffer, DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type);
  305. virtual ArrayBufferContentForDelayedFreeBase* CopyBufferContentForDelayedFree(RefCountedBuffer * content, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength) override;
  306. virtual void Dispose(bool isShutdown) override;
  307. virtual void Finalize(bool isShutdown) override;
  308. private:
  309. ProjectionArrayBuffer(uint32 length, DynamicType * type);
  310. ProjectionArrayBuffer(byte* buffer, uint32 length, DynamicType * type);
  311. ProjectionArrayBuffer(RefCountedBuffer* buffer, uint32 length, DynamicType * type);
  312. };
  313. // non-owning ArrayBuffer used for wrapping external data
  314. class ExternalArrayBuffer : public ArrayBuffer
  315. {
  316. protected:
  317. DEFINE_VTABLE_CTOR(ExternalArrayBuffer, ArrayBuffer);
  318. DEFINE_MARSHAL_OBJECT_TO_SCRIPT_CONTEXT(ExternalArrayBuffer);
  319. public:
  320. ExternalArrayBuffer(byte *buffer, DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType *type);
  321. ExternalArrayBuffer(RefCountedBuffer *buffer, DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType *type);
  322. static ExternalArrayBuffer* Create(RefCountedBuffer* buffer, DECLSPEC_GUARD_OVERFLOW uint32 length, DynamicType * type);
  323. protected:
  324. virtual ArrayBufferDetachedStateBase* CreateDetachedState(RefCountedBuffer* buffer, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength) override;
  325. virtual void ReportExternalMemoryFree() override;
  326. #if ENABLE_TTD
  327. public:
  328. virtual TTD::NSSnapObjects::SnapObjectType GetSnapTag_TTD() const override;
  329. virtual void ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc) override;
  330. #endif
  331. };
  332. class ExternalArrayBufferDetachedState : public ArrayBufferDetachedStateBase
  333. {
  334. public:
  335. ExternalArrayBufferDetachedState(RefCountedBuffer* buffer, uint32 bufferLength);
  336. virtual void ClearSelfOnly() override;
  337. virtual void DiscardState() override;
  338. virtual void Discard() override;
  339. virtual ArrayBuffer* Create(JavascriptLibrary* library);
  340. };
  341. }