WebAssemblyMemory.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. #include "RuntimeLibraryPch.h"
  6. #ifdef ENABLE_WASM
  7. #include "WasmLimits.h"
  8. using namespace Js;
  9. WebAssemblyMemory::WebAssemblyMemory(ArrayBufferBase* buffer, uint32 initial, uint32 maximum, DynamicType * type) :
  10. DynamicObject(type),
  11. m_buffer(buffer),
  12. m_initial(initial),
  13. m_maximum(maximum)
  14. {
  15. Assert(buffer->IsWebAssemblyArrayBuffer());
  16. Assert(m_buffer);
  17. Assert(m_buffer->GetByteLength() >= UInt32Math::Mul<WebAssembly::PageSize>(initial));
  18. }
  19. void WebAssemblyMemory::CheckLimits(ScriptContext * scriptContext, uint32 initial, uint32 maximum)
  20. {
  21. if (maximum < initial)
  22. {
  23. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange);
  24. }
  25. if (initial > Wasm::Limits::GetMaxMemoryInitialPages())
  26. {
  27. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_Invalid, _u("descriptor.initial"));
  28. }
  29. if (maximum > Wasm::Limits::GetMaxMemoryMaximumPages())
  30. {
  31. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_Invalid, _u("descriptor.maximum"));
  32. }
  33. }
  34. void WebAssemblyMemory::CheckLimits(ScriptContext * scriptContext, uint32 initial, uint32 maximum, uint32 bufferLength)
  35. {
  36. CheckLimits(scriptContext, initial, maximum);
  37. // Do the mul after initial checks to avoid potential unneeded OOM exception
  38. const uint32 initBytes = UInt32Math::Mul<WebAssembly::PageSize>(initial);
  39. const uint32 maxBytes = UInt32Math::Mul<WebAssembly::PageSize>(maximum);
  40. if (initBytes > bufferLength || bufferLength > maxBytes)
  41. {
  42. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_Invalid);
  43. }
  44. }
  45. Var
  46. WebAssemblyMemory::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  47. {
  48. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  49. ARGUMENTS(args, callInfo);
  50. ScriptContext* scriptContext = function->GetScriptContext();
  51. AssertMsg(args.HasArg(), "Should always have implicit 'this'");
  52. Var newTarget = args.GetNewTarget();
  53. JavascriptOperators::GetAndAssertIsConstructorSuperCall(args);
  54. if (!(callInfo.Flags & CallFlags_New) || (newTarget && JavascriptOperators::IsUndefinedObject(newTarget)))
  55. {
  56. JavascriptError::ThrowTypeError(scriptContext, JSERR_ClassConstructorCannotBeCalledWithoutNew, _u("WebAssembly.Memory"));
  57. }
  58. if (args.Info.Count < 2 || !JavascriptOperators::IsObject(args[1]))
  59. {
  60. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject, _u("descriptor"));
  61. }
  62. DynamicObject * memoryDescriptor = VarTo<DynamicObject>(args[1]);
  63. Var initVar = JavascriptOperators::OP_GetProperty(memoryDescriptor, PropertyIds::initial, scriptContext);
  64. if (Js::JavascriptOperators::IsUndefined(initVar))
  65. {
  66. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedNumber, _u("descriptor.initial"));
  67. }
  68. uint32 initial = WebAssembly::ToNonWrappingUint32(initVar, scriptContext);
  69. uint32 maximum = Wasm::Limits::GetMaxMemoryMaximumPages();
  70. bool hasMaximum = false;
  71. Var maxVar = JavascriptOperators::OP_GetProperty(memoryDescriptor, PropertyIds::maximum, scriptContext);
  72. if (!Js::JavascriptOperators::IsUndefined(maxVar))
  73. {
  74. hasMaximum = true;
  75. maximum = WebAssembly::ToNonWrappingUint32(maxVar, scriptContext);
  76. }
  77. bool isShared = false;
  78. if (Wasm::Threads::IsEnabled())
  79. {
  80. Var sharedVar = JavascriptOperators::OP_GetProperty(memoryDescriptor, PropertyIds::shared, scriptContext);
  81. if (!Js::JavascriptOperators::IsUndefined(sharedVar))
  82. {
  83. isShared = JavascriptConversion::ToBool(sharedVar, scriptContext);
  84. if (!hasMaximum)
  85. {
  86. JavascriptError::ThrowTypeError(scriptContext, WASMERR_SharedNoMaximum);
  87. }
  88. }
  89. }
  90. return CreateMemoryObject(initial, maximum, isShared, scriptContext);
  91. }
  92. Var
  93. WebAssemblyMemory::EntryGrow(RecyclableObject* function, CallInfo callInfo, ...)
  94. {
  95. ScriptContext* scriptContext = function->GetScriptContext();
  96. PROBE_STACK(scriptContext, Js::Constants::MinStackDefault);
  97. ARGUMENTS(args, callInfo);
  98. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  99. Assert(!(callInfo.Flags & CallFlags_New));
  100. if (!VarIs<WebAssemblyMemory>(args[0]))
  101. {
  102. JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedMemoryObject);
  103. }
  104. WebAssemblyMemory* memory = VarTo<WebAssemblyMemory>(args[0]);
  105. Assert(VarIsCorrectType(memory->m_buffer));
  106. Var deltaVar = scriptContext->GetLibrary()->GetUndefined();
  107. if (args.Info.Count >= 2)
  108. {
  109. deltaVar = args[1];
  110. }
  111. uint32 deltaPages = WebAssembly::ToNonWrappingUint32(deltaVar, scriptContext);
  112. if (memory->m_buffer->IsDetached())
  113. {
  114. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray);
  115. }
  116. int32 oldPageCount = memory->GrowInternal(deltaPages);
  117. if (oldPageCount == -1)
  118. {
  119. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange);
  120. }
  121. return JavascriptNumber::ToVar(oldPageCount, scriptContext);
  122. }
  123. int32
  124. WebAssemblyMemory::GrowInternal(uint32 deltaPages)
  125. {
  126. const uint64 deltaBytes = (uint64)deltaPages * WebAssembly::PageSize;
  127. if (deltaBytes > ArrayBuffer::MaxArrayBufferLength)
  128. {
  129. return -1;
  130. }
  131. const uint32 oldBytes = m_buffer->GetByteLength();
  132. const uint64 newBytesLong = deltaBytes + oldBytes;
  133. if (newBytesLong > ArrayBuffer::MaxArrayBufferLength)
  134. {
  135. return -1;
  136. }
  137. CompileAssert(ArrayBuffer::MaxArrayBufferLength <= UINT32_MAX);
  138. const uint32 newBytes = (uint32)newBytesLong;
  139. const uint32 oldPageCount = oldBytes / WebAssembly::PageSize;
  140. Assert(oldBytes % WebAssembly::PageSize == 0);
  141. const uint32 newPageCount = oldPageCount + deltaPages;
  142. if (newPageCount > m_maximum)
  143. {
  144. return -1;
  145. }
  146. AssertOrFailFast(m_buffer->IsWebAssemblyArrayBuffer());
  147. #ifdef ENABLE_WASM_THREADS
  148. if (m_buffer->IsSharedArrayBuffer())
  149. {
  150. AssertOrFailFast(Wasm::Threads::IsEnabled());
  151. if (!((WebAssemblySharedArrayBuffer*)GetBuffer())->GrowMemory(newBytes))
  152. {
  153. return -1;
  154. }
  155. }
  156. else
  157. #endif
  158. {
  159. JavascriptExceptionObject* caughtExceptionObject = nullptr;
  160. try
  161. {
  162. WebAssemblyArrayBuffer* newBuffer = ((WebAssemblyArrayBuffer*)GetBuffer())->GrowMemory(newBytes);
  163. if (newBuffer == nullptr)
  164. {
  165. return -1;
  166. }
  167. m_buffer = newBuffer;
  168. }
  169. catch (const JavascriptException& err)
  170. {
  171. caughtExceptionObject = err.GetAndClear();
  172. Assert(caughtExceptionObject && caughtExceptionObject == ThreadContext::GetContextForCurrentThread()->GetPendingOOMErrorObject());
  173. return -1;
  174. }
  175. }
  176. CompileAssert(ArrayBuffer::MaxArrayBufferLength / WebAssembly::PageSize <= INT32_MAX);
  177. return (int32)oldPageCount;
  178. }
  179. int32
  180. WebAssemblyMemory::GrowHelper(WebAssemblyMemory * mem, uint32 deltaPages)
  181. {
  182. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(Op_GrowWasmMemory);
  183. return mem->GrowInternal(deltaPages);
  184. JIT_HELPER_END(Op_GrowWasmMemory);
  185. }
  186. #if DBG
  187. void WebAssemblyMemory::TraceMemWrite(WebAssemblyMemory* mem, uint32 index, uint32 offset, Js::ArrayBufferView::ViewType viewType, uint32 bytecodeOffset, ScriptContext* context)
  188. {
  189. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(Op_WasmMemoryTraceWrite);
  190. // Must call after the write
  191. Assert(mem);
  192. Output::Print(_u("#%04x "), bytecodeOffset);
  193. uint64 bigIndex = (uint64)index + (uint64)offset;
  194. if (index >= mem->m_buffer->GetByteLength())
  195. {
  196. Output::Print(_u("WasmMemoryTrace:: Writing out of bounds. %llu >= %u\n"), bigIndex, mem->m_buffer->GetByteLength());
  197. }
  198. if (offset)
  199. {
  200. Output::Print(_u("WasmMemoryTrace:: buf[%u + %u (%llu)]"), index, offset, bigIndex);
  201. }
  202. else
  203. {
  204. Output::Print(_u("WasmMemoryTrace:: buf[%u]"), index);
  205. }
  206. BYTE* buffer = mem->m_buffer->GetBuffer();
  207. switch (viewType)
  208. {
  209. case ArrayBufferView::ViewType::TYPE_INT8_TO_INT64:
  210. case ArrayBufferView::ViewType::TYPE_INT8: Output::Print(_u(".int8 = %d\n"), *(int8*)(buffer + bigIndex)); break;
  211. case ArrayBufferView::ViewType::TYPE_UINT8_TO_INT64:
  212. case ArrayBufferView::ViewType::TYPE_UINT8: Output::Print(_u(".uint8 = %u\n"), *(uint8*)(buffer + bigIndex)); break;
  213. case ArrayBufferView::ViewType::TYPE_INT16_TO_INT64:
  214. case ArrayBufferView::ViewType::TYPE_INT16: Output::Print(_u(".int16 = %d\n"), *(int16*)(buffer + bigIndex)); break;
  215. case ArrayBufferView::ViewType::TYPE_UINT16_TO_INT64:
  216. case ArrayBufferView::ViewType::TYPE_UINT16: Output::Print(_u(".uint16 = %u\n"), *(uint16*)(buffer + bigIndex)); break;
  217. case ArrayBufferView::ViewType::TYPE_INT32_TO_INT64:
  218. case ArrayBufferView::ViewType::TYPE_INT32: Output::Print(_u(".int32 = %d\n"), *(int32*)(buffer + bigIndex)); break;
  219. case ArrayBufferView::ViewType::TYPE_UINT32_TO_INT64:
  220. case ArrayBufferView::ViewType::TYPE_UINT32: Output::Print(_u(".uint32 = %u\n"), *(uint32*)(buffer + bigIndex)); break;
  221. case ArrayBufferView::ViewType::TYPE_FLOAT32: Output::Print(_u(".f32 = %.4f\n"), *(float*)(buffer + bigIndex)); break;
  222. case ArrayBufferView::ViewType::TYPE_FLOAT64: Output::Print(_u(".f64 = %.8f\n"), *(double*)(buffer + bigIndex)); break;
  223. case ArrayBufferView::ViewType::TYPE_INT64: Output::Print(_u(".int64 = %lld\n"), *(int64*)(buffer + bigIndex)); break;
  224. default:
  225. CompileAssert(ArrayBufferView::ViewType::TYPE_COUNT == 15);
  226. Assert(UNREACHED);
  227. }
  228. return;
  229. JIT_HELPER_END(Op_WasmMemoryTraceWrite);
  230. }
  231. #endif
  232. Var
  233. WebAssemblyMemory::EntryGetterBuffer(RecyclableObject* function, CallInfo callInfo, ...)
  234. {
  235. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  236. ARGUMENTS(args, callInfo);
  237. ScriptContext* scriptContext = function->GetScriptContext();
  238. Assert(!(callInfo.Flags & CallFlags_New));
  239. if (args.Info.Count == 0 || !VarIs<WebAssemblyMemory>(args[0]))
  240. {
  241. JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedMemoryObject);
  242. }
  243. WebAssemblyMemory* memory = VarTo<WebAssemblyMemory>(args[0]);
  244. Assert(VarIsCorrectType(memory->m_buffer));
  245. return CrossSite::MarshalVar(scriptContext, memory->m_buffer);
  246. }
  247. WebAssemblyMemory *
  248. WebAssemblyMemory::CreateMemoryObject(uint32 initial, uint32 maximum, bool isShared, ScriptContext * scriptContext)
  249. {
  250. CheckLimits(scriptContext, initial, maximum);
  251. uint32 byteLength = UInt32Math::Mul<WebAssembly::PageSize>(initial);
  252. ArrayBufferBase* buffer = nullptr;
  253. #ifdef ENABLE_WASM_THREADS
  254. if (isShared)
  255. {
  256. Assert(Wasm::Threads::IsEnabled());
  257. uint32 maxByteLength = UInt32Math::Mul<WebAssembly::PageSize>(maximum);
  258. buffer = scriptContext->GetLibrary()->CreateWebAssemblySharedArrayBuffer(byteLength, maxByteLength);
  259. }
  260. else
  261. #endif
  262. {
  263. buffer = scriptContext->GetLibrary()->CreateWebAssemblyArrayBuffer(byteLength);
  264. }
  265. Assert(buffer);
  266. if (byteLength > 0 && buffer->GetByteLength() == 0)
  267. {
  268. // Failed to allocate buffer
  269. return nullptr;
  270. }
  271. return RecyclerNewFinalized(scriptContext->GetRecycler(), WebAssemblyMemory, buffer, initial, maximum, scriptContext->GetLibrary()->GetWebAssemblyMemoryType());
  272. }
  273. WebAssemblyMemory * WebAssemblyMemory::CreateForExistingBuffer(uint32 initial, uint32 maximum, uint32 currentByteLength, ScriptContext * scriptContext)
  274. {
  275. CheckLimits(scriptContext, initial, maximum, currentByteLength);
  276. ArrayBufferBase* buffer = scriptContext->GetLibrary()->CreateWebAssemblyArrayBuffer(currentByteLength);
  277. Assert(buffer);
  278. if (currentByteLength > 0 && buffer->GetByteLength() == 0)
  279. {
  280. // Failed to allocate buffer
  281. return nullptr;
  282. }
  283. return RecyclerNewFinalized(scriptContext->GetRecycler(), WebAssemblyMemory, buffer, initial, maximum, scriptContext->GetLibrary()->GetWebAssemblyMemoryType());
  284. }
  285. #ifdef ENABLE_WASM_THREADS
  286. WebAssemblyMemory * WebAssemblyMemory::CreateFromSharedContents(uint32 initial, uint32 maximum, SharedContents* sharedContents, ScriptContext * scriptContext)
  287. {
  288. if (!sharedContents)
  289. {
  290. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_Invalid);
  291. }
  292. CheckLimits(scriptContext, initial, maximum, sharedContents->bufferLength);
  293. ArrayBufferBase* buffer = scriptContext->GetLibrary()->CreateWebAssemblySharedArrayBuffer(sharedContents);
  294. return RecyclerNewFinalized(scriptContext->GetRecycler(), WebAssemblyMemory, buffer, initial, maximum, scriptContext->GetLibrary()->GetWebAssemblyMemoryType());
  295. }
  296. #endif
  297. ArrayBufferBase*
  298. WebAssemblyMemory::GetBuffer() const
  299. {
  300. return m_buffer;
  301. }
  302. uint
  303. WebAssemblyMemory::GetInitialLength() const
  304. {
  305. return m_initial;
  306. }
  307. uint
  308. WebAssemblyMemory::GetMaximumLength() const
  309. {
  310. return m_maximum;
  311. }
  312. uint
  313. WebAssemblyMemory::GetCurrentMemoryPages() const
  314. {
  315. return m_buffer->GetByteLength() / WebAssembly::PageSize;
  316. }
  317. #ifdef ENABLE_WASM_THREADS
  318. bool WebAssemblyMemory::IsSharedMemory() const
  319. {
  320. return VarIs<WebAssemblySharedArrayBuffer>(m_buffer);
  321. }
  322. #endif
  323. #endif // ENABLE_WASM