ArrayBuffer.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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. namespace Js
  7. {
  8. long RefCountedBuffer::AddRef()
  9. {
  10. long ref = InterlockedIncrement(&refCount);
  11. AssertOrFailFast(ref > 1);
  12. return ref;
  13. }
  14. long RefCountedBuffer::Release()
  15. {
  16. long ref = InterlockedDecrement(&refCount);
  17. AssertOrFailFastMsg(ref >= 0, "Buffer already freed");
  18. return ref;
  19. }
  20. void ArrayBufferDetachedStateBase::AddRefBufferContent()
  21. {
  22. if (buffer != nullptr)
  23. {
  24. buffer->AddRef();
  25. }
  26. }
  27. long ArrayBufferDetachedStateBase::ReleaseRefBufferContent()
  28. {
  29. if (buffer != nullptr)
  30. {
  31. long ref = buffer->Release();
  32. AssertOrFailFast(ref > 0);
  33. return ref;
  34. }
  35. return 0;
  36. }
  37. bool ArrayBufferBase::Is(Var value)
  38. {
  39. return ArrayBuffer::Is(value) || SharedArrayBuffer::Is(value);
  40. }
  41. ArrayBufferBase* ArrayBufferBase::FromVar(Var value)
  42. {
  43. AssertOrFailFast(ArrayBufferBase::Is(value));
  44. return static_cast<ArrayBuffer *> (value);
  45. }
  46. ArrayBufferBase* ArrayBufferBase::UnsafeFromVar(Var value)
  47. {
  48. Assert(ArrayBufferBase::Is(value));
  49. return static_cast<ArrayBuffer *> (value);
  50. }
  51. ArrayBuffer* ArrayBuffer::NewFromDetachedState(DetachedStateBase* state, JavascriptLibrary *library)
  52. {
  53. ArrayBufferDetachedStateBase* arrayBufferState = (ArrayBufferDetachedStateBase *)state;
  54. ArrayBuffer *toReturn = nullptr;
  55. switch (arrayBufferState->allocationType)
  56. {
  57. case ArrayBufferAllocationType::CoTask:
  58. toReturn = library->CreateProjectionArraybuffer(arrayBufferState->buffer, arrayBufferState->bufferLength);
  59. break;
  60. case ArrayBufferAllocationType::Heap:
  61. case ArrayBufferAllocationType::MemAlloc:
  62. toReturn = library->CreateArrayBuffer(arrayBufferState->buffer, arrayBufferState->bufferLength);
  63. break;
  64. case ArrayBufferAllocationType::External:
  65. toReturn = static_cast<ExternalArrayBufferDetachedState*>(state)->Create(library);
  66. break;
  67. default:
  68. AssertMsg(false, "Unknown allocationType of ArrayBufferDetachedStateBase ");
  69. }
  70. return toReturn;
  71. }
  72. uint32 ArrayBuffer::GetByteLength() const
  73. {
  74. return this->bufferLength;
  75. }
  76. BYTE* ArrayBuffer::GetBuffer() const
  77. {
  78. return this->bufferContent != nullptr ? this->bufferContent->GetBuffer() : nullptr;
  79. }
  80. void ArrayBuffer::DetachBufferFromParent(ArrayBufferParent* parent)
  81. {
  82. if (parent == nullptr)
  83. {
  84. return;
  85. }
  86. switch (JavascriptOperators::GetTypeId(parent))
  87. {
  88. case TypeIds_Int8Array:
  89. if (Int8VirtualArray::Is(parent))
  90. {
  91. if (VirtualTableInfo<Int8VirtualArray>::HasVirtualTable(parent))
  92. {
  93. VirtualTableInfo<Int8Array>::SetVirtualTable(parent);
  94. }
  95. else
  96. {
  97. Assert(VirtualTableInfo<CrossSiteObject<Int8VirtualArray>>::HasVirtualTable(parent));
  98. VirtualTableInfo<CrossSiteObject<Int8Array>>::SetVirtualTable(parent);
  99. }
  100. }
  101. TypedArrayBase::UnsafeFromVar(parent)->ClearLengthAndBufferOnDetach();
  102. break;
  103. case TypeIds_Uint8Array:
  104. if (Uint8VirtualArray::Is(parent))
  105. {
  106. if (VirtualTableInfo<Uint8VirtualArray>::HasVirtualTable(parent))
  107. {
  108. VirtualTableInfo<Uint8Array>::SetVirtualTable(parent);
  109. }
  110. else
  111. {
  112. Assert(VirtualTableInfo<CrossSiteObject<Uint8VirtualArray>>::HasVirtualTable(parent));
  113. VirtualTableInfo<CrossSiteObject<Uint8Array>>::SetVirtualTable(parent);
  114. }
  115. }
  116. TypedArrayBase::UnsafeFromVar(parent)->ClearLengthAndBufferOnDetach();
  117. break;
  118. case TypeIds_Uint8ClampedArray:
  119. if (Uint8ClampedVirtualArray::Is(parent))
  120. {
  121. if (VirtualTableInfo<Uint8ClampedVirtualArray>::HasVirtualTable(parent))
  122. {
  123. VirtualTableInfo<Uint8ClampedArray>::SetVirtualTable(parent);
  124. }
  125. else
  126. {
  127. Assert(VirtualTableInfo<CrossSiteObject<Uint8ClampedVirtualArray>>::HasVirtualTable(parent));
  128. VirtualTableInfo<CrossSiteObject<Uint8ClampedArray>>::SetVirtualTable(parent);
  129. }
  130. }
  131. TypedArrayBase::UnsafeFromVar(parent)->ClearLengthAndBufferOnDetach();
  132. break;
  133. case TypeIds_Int16Array:
  134. if (Int16VirtualArray::Is(parent))
  135. {
  136. if (VirtualTableInfo<Int16VirtualArray>::HasVirtualTable(parent))
  137. {
  138. VirtualTableInfo<Int16Array>::SetVirtualTable(parent);
  139. }
  140. else
  141. {
  142. Assert(VirtualTableInfo<CrossSiteObject<Int16VirtualArray>>::HasVirtualTable(parent));
  143. VirtualTableInfo<CrossSiteObject<Int16Array>>::SetVirtualTable(parent);
  144. }
  145. }
  146. TypedArrayBase::UnsafeFromVar(parent)->ClearLengthAndBufferOnDetach();
  147. break;
  148. case TypeIds_Uint16Array:
  149. if (Uint16VirtualArray::Is(parent))
  150. {
  151. if (VirtualTableInfo<Uint16VirtualArray>::HasVirtualTable(parent))
  152. {
  153. VirtualTableInfo<Uint16Array>::SetVirtualTable(parent);
  154. }
  155. else
  156. {
  157. Assert(VirtualTableInfo<CrossSiteObject<Uint16VirtualArray>>::HasVirtualTable(parent));
  158. VirtualTableInfo<CrossSiteObject<Uint16Array>>::SetVirtualTable(parent);
  159. }
  160. }
  161. TypedArrayBase::UnsafeFromVar(parent)->ClearLengthAndBufferOnDetach();
  162. break;
  163. case TypeIds_Int32Array:
  164. if (Int32VirtualArray::Is(parent))
  165. {
  166. if (VirtualTableInfo<Int32VirtualArray>::HasVirtualTable(parent))
  167. {
  168. VirtualTableInfo<Int32Array>::SetVirtualTable(parent);
  169. }
  170. else
  171. {
  172. Assert(VirtualTableInfo<CrossSiteObject<Int32VirtualArray>>::HasVirtualTable(parent));
  173. VirtualTableInfo<CrossSiteObject<Int32Array>>::SetVirtualTable(parent);
  174. }
  175. }
  176. TypedArrayBase::UnsafeFromVar(parent)->ClearLengthAndBufferOnDetach();
  177. break;
  178. case TypeIds_Uint32Array:
  179. if (Uint32VirtualArray::Is(parent))
  180. {
  181. if (VirtualTableInfo<Uint32VirtualArray>::HasVirtualTable(parent))
  182. {
  183. VirtualTableInfo<Uint32Array>::SetVirtualTable(parent);
  184. }
  185. else
  186. {
  187. Assert(VirtualTableInfo<CrossSiteObject<Uint32VirtualArray>>::HasVirtualTable(parent));
  188. VirtualTableInfo<CrossSiteObject<Uint32Array>>::SetVirtualTable(parent);
  189. }
  190. }
  191. TypedArrayBase::UnsafeFromVar(parent)->ClearLengthAndBufferOnDetach();
  192. break;
  193. case TypeIds_Float32Array:
  194. if (Float32VirtualArray::Is(parent))
  195. {
  196. if (VirtualTableInfo<Float32VirtualArray>::HasVirtualTable(parent))
  197. {
  198. VirtualTableInfo<Float32Array>::SetVirtualTable(parent);
  199. }
  200. else
  201. {
  202. Assert(VirtualTableInfo<CrossSiteObject<Float32VirtualArray>>::HasVirtualTable(parent));
  203. VirtualTableInfo<CrossSiteObject<Float32Array>>::SetVirtualTable(parent);
  204. }
  205. }
  206. TypedArrayBase::UnsafeFromVar(parent)->ClearLengthAndBufferOnDetach();
  207. break;
  208. case TypeIds_Float64Array:
  209. if (Float64VirtualArray::Is(parent))
  210. {
  211. if (VirtualTableInfo<Float64VirtualArray>::HasVirtualTable(parent))
  212. {
  213. VirtualTableInfo<Float64Array>::SetVirtualTable(parent);
  214. }
  215. else
  216. {
  217. Assert(VirtualTableInfo<CrossSiteObject<Float64VirtualArray>>::HasVirtualTable(parent));
  218. VirtualTableInfo<CrossSiteObject<Float64Array>>::SetVirtualTable(parent);
  219. }
  220. }
  221. TypedArrayBase::UnsafeFromVar(parent)->ClearLengthAndBufferOnDetach();
  222. break;
  223. case TypeIds_Int64Array:
  224. case TypeIds_Uint64Array:
  225. case TypeIds_CharArray:
  226. case TypeIds_BoolArray:
  227. TypedArrayBase::UnsafeFromVar(parent)->ClearLengthAndBufferOnDetach();
  228. break;
  229. case TypeIds_DataView:
  230. DataView::FromVar(parent)->ClearLengthAndBufferOnDetach();
  231. break;
  232. default:
  233. AssertMsg(false, "We need an explicit case for any parent of ArrayBuffer.");
  234. break;
  235. }
  236. }
  237. void ArrayBuffer::ReportExternalMemoryFree()
  238. {
  239. Recycler* recycler = GetType()->GetLibrary()->GetRecycler();
  240. recycler->ReportExternalMemoryFree(bufferLength);
  241. }
  242. void ArrayBuffer::Detach()
  243. {
  244. Assert(!this->isDetached);
  245. // we are about to lose track of the buffer to another owner
  246. // report that we no longer own the memory
  247. ReportExternalMemoryFree();
  248. this->bufferContent = nullptr;
  249. this->bufferLength = 0;
  250. this->isDetached = true;
  251. if (this->primaryParent != nullptr && this->primaryParent->Get() == nullptr)
  252. {
  253. this->primaryParent = nullptr;
  254. }
  255. if (this->primaryParent != nullptr)
  256. {
  257. this->DetachBufferFromParent(this->primaryParent->Get());
  258. }
  259. if (this->otherParents != nullptr)
  260. {
  261. this->otherParents->Map([&](RecyclerWeakReference<ArrayBufferParent>* item)
  262. {
  263. this->DetachBufferFromParent(item->Get());
  264. });
  265. }
  266. }
  267. ArrayBufferDetachedStateBase* ArrayBuffer::DetachAndGetState(bool queueForDelayFree/* = true*/)
  268. {
  269. // Save the state before detaching
  270. AutoPtr<ArrayBufferDetachedStateBase> arrayBufferState(this->CreateDetachedState(this->bufferContent, this->bufferLength));
  271. Detach();
  272. // Now put this bufferContent to the queue so that we can manage the lifetime of the buffer later.
  273. if (queueForDelayFree && arrayBufferState->buffer != nullptr)
  274. {
  275. DelayedFreeArrayBuffer * local = GetScriptContext()->GetThreadContext()->GetScanStackCallback();
  276. local->Push(this->CopyBufferContentForDelayedFree(arrayBufferState->buffer, arrayBufferState->bufferLength));
  277. }
  278. return arrayBufferState.Detach();
  279. }
  280. void ArrayBuffer::AddParent(ArrayBufferParent* parent)
  281. {
  282. if (this->primaryParent == nullptr || this->primaryParent->Get() == nullptr)
  283. {
  284. this->primaryParent = this->GetRecycler()->CreateWeakReferenceHandle(parent);
  285. }
  286. else
  287. {
  288. if (this->otherParents == nullptr)
  289. {
  290. this->otherParents = RecyclerNew(this->GetRecycler(), OtherParents, this->GetRecycler());
  291. }
  292. if (this->otherParents->increasedCount >= ParentsCleanupThreshold)
  293. {
  294. auto iter = this->otherParents->GetEditingIterator();
  295. while (iter.Next())
  296. {
  297. if (iter.Data()->Get() == nullptr)
  298. {
  299. iter.RemoveCurrent();
  300. }
  301. }
  302. this->otherParents->increasedCount = 0;
  303. }
  304. this->otherParents->PrependNode(this->GetRecycler()->CreateWeakReferenceHandle(parent));
  305. this->otherParents->increasedCount++;
  306. }
  307. }
  308. uint32 ArrayBuffer::ToIndex(Var value, int32 errorCode, ScriptContext *scriptContext, uint32 MaxAllowedLength, bool checkSameValueZero)
  309. {
  310. if (JavascriptOperators::IsUndefined(value))
  311. {
  312. return 0;
  313. }
  314. if (TaggedInt::Is(value))
  315. {
  316. int64 index = TaggedInt::ToInt64(value);
  317. if (index < 0 || index >(int64)MaxAllowedLength)
  318. {
  319. JavascriptError::ThrowRangeError(scriptContext, errorCode);
  320. }
  321. return (uint32)index;
  322. }
  323. // Slower path
  324. double d = JavascriptConversion::ToInteger(value, scriptContext);
  325. if (d < 0.0 || d >(double)MaxAllowedLength)
  326. {
  327. JavascriptError::ThrowRangeError(scriptContext, errorCode);
  328. }
  329. if (checkSameValueZero)
  330. {
  331. Var integerIndex = JavascriptNumber::ToVarNoCheck(d, scriptContext);
  332. Var index = JavascriptNumber::ToVar(JavascriptConversion::ToLength(integerIndex, scriptContext), scriptContext);
  333. if (!JavascriptConversion::SameValueZero(integerIndex, index))
  334. {
  335. JavascriptError::ThrowRangeError(scriptContext, errorCode);
  336. }
  337. }
  338. return (uint32)d;
  339. }
  340. Var ArrayBuffer::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  341. {
  342. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  343. ARGUMENTS(args, callInfo);
  344. ScriptContext* scriptContext = function->GetScriptContext();
  345. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  346. Var newTarget = args.GetNewTarget();
  347. bool isCtorSuperCall = JavascriptOperators::GetAndAssertIsConstructorSuperCall(args);
  348. if (!args.IsNewCall() || (newTarget && JavascriptOperators::IsUndefinedObject(newTarget)))
  349. {
  350. JavascriptError::ThrowTypeError(scriptContext, JSERR_ClassConstructorCannotBeCalledWithoutNew, _u("ArrayBuffer"));
  351. }
  352. uint32 byteLength = 0;
  353. if (args.Info.Count > 1)
  354. {
  355. byteLength = ToIndex(args[1], JSERR_ArrayLengthConstructIncorrect, scriptContext, MaxArrayBufferLength);
  356. }
  357. RecyclableObject* newArr = scriptContext->GetLibrary()->CreateArrayBuffer(byteLength);
  358. Assert(ArrayBuffer::Is(newArr));
  359. if (byteLength > 0 && !ArrayBuffer::FromVar(newArr)->GetByteLength())
  360. {
  361. JavascriptError::ThrowRangeError(scriptContext, JSERR_FunctionArgument_Invalid);
  362. }
  363. #if ENABLE_DEBUG_CONFIG_OPTIONS
  364. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  365. {
  366. newArr = Js::JavascriptProxy::AutoProxyWrapper(newArr);
  367. }
  368. #endif
  369. return isCtorSuperCall ?
  370. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), newArr, nullptr, scriptContext) :
  371. newArr;
  372. }
  373. // ArrayBuffer.prototype.byteLength as described in ES6 draft #20 section 24.1.4.1
  374. Var ArrayBuffer::EntryGetterByteLength(RecyclableObject* function, CallInfo callInfo, ...)
  375. {
  376. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  377. ARGUMENTS(args, callInfo);
  378. ScriptContext* scriptContext = function->GetScriptContext();
  379. Assert(!(callInfo.Flags & CallFlags_New));
  380. if (args.Info.Count == 0 || !ArrayBuffer::Is(args[0]))
  381. {
  382. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject);
  383. }
  384. ArrayBuffer* arrayBuffer = ArrayBuffer::FromVar(args[0]);
  385. if (arrayBuffer->IsDetached())
  386. {
  387. return JavascriptNumber::ToVar(0, scriptContext);
  388. }
  389. return JavascriptNumber::ToVar(arrayBuffer->GetByteLength(), scriptContext);
  390. }
  391. // ArrayBuffer.isView as described in ES6 draft #20 section 24.1.3.1
  392. Var ArrayBuffer::EntryIsView(RecyclableObject* function, CallInfo callInfo, ...)
  393. {
  394. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  395. ARGUMENTS(args, callInfo);
  396. Assert(!(callInfo.Flags & CallFlags_New));
  397. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  398. JavascriptLibrary* library = function->GetScriptContext()->GetLibrary();
  399. Var arg = library->GetUndefined();
  400. if (args.Info.Count > 1)
  401. {
  402. arg = args[1];
  403. }
  404. // Only DataView or any TypedArray objects have [[ViewedArrayBuffer]] internal slots
  405. if (DataView::Is(arg) || TypedArrayBase::Is(arg))
  406. {
  407. return library->GetTrue();
  408. }
  409. return library->GetFalse();
  410. }
  411. #if ENABLE_DEBUG_CONFIG_OPTIONS
  412. Var ArrayBuffer::EntryDetach(RecyclableObject* function, CallInfo callInfo, ...)
  413. {
  414. ScriptContext* scriptContext = function->GetScriptContext();
  415. PROBE_STACK(scriptContext, Js::Constants::MinStackDefault);
  416. ARGUMENTS(args, callInfo);
  417. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  418. Assert(!(callInfo.Flags & CallFlags_New));
  419. if (args.Info.Count < 2 || !ArrayBuffer::Is(args[1]))
  420. {
  421. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject);
  422. }
  423. ArrayBuffer* arrayBuffer = ArrayBuffer::FromVar(args[1]);
  424. if (arrayBuffer->IsDetached())
  425. {
  426. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("ArrayBuffer.detach"));
  427. }
  428. // Discard the buffer
  429. // We are clearing out the buffer now instead of queueing to flush out JIT bugs.
  430. DetachedStateBase* state = arrayBuffer->DetachAndGetState(false /*queueForDelayFree*/);
  431. state->CleanUp();
  432. return scriptContext->GetLibrary()->GetUndefined();
  433. }
  434. #endif
  435. // ArrayBuffer.prototype.slice as described in ES6 draft #19 section 24.1.4.3.
  436. Var ArrayBuffer::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
  437. {
  438. ScriptContext* scriptContext = function->GetScriptContext();
  439. PROBE_STACK(scriptContext, Js::Constants::MinStackDefault);
  440. ARGUMENTS(args, callInfo);
  441. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  442. Assert(!(callInfo.Flags & CallFlags_New));
  443. if (!ArrayBuffer::Is(args[0]))
  444. {
  445. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject);
  446. }
  447. JavascriptLibrary* library = scriptContext->GetLibrary();
  448. ArrayBuffer* arrayBuffer = ArrayBuffer::FromVar(args[0]);
  449. if (arrayBuffer->IsDetached()) // 24.1.4.3: 5. If IsDetachedBuffer(O) is true, then throw a TypeError exception.
  450. {
  451. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("ArrayBuffer.prototype.slice"));
  452. }
  453. int64 len = arrayBuffer->bufferLength;
  454. int64 start = 0, end = 0;
  455. int64 newLen;
  456. // If no start or end arguments, use the entire length
  457. if (args.Info.Count < 2)
  458. {
  459. newLen = len;
  460. }
  461. else
  462. {
  463. start = JavascriptArray::GetIndexFromVar(args[1], len, scriptContext);
  464. // If no end argument, use length as the end
  465. if (args.Info.Count < 3 || args[2] == library->GetUndefined())
  466. {
  467. end = len;
  468. }
  469. else
  470. {
  471. end = JavascriptArray::GetIndexFromVar(args[2], len, scriptContext);
  472. }
  473. newLen = end > start ? end - start : 0;
  474. }
  475. // We can't have allocated an ArrayBuffer with byteLength > MaxArrayBufferLength.
  476. // start and end are clamped to valid indices, so the new length also cannot exceed MaxArrayBufferLength.
  477. // Therefore, should be safe to cast down newLen to uint32.
  478. // TODO: If we ever support allocating ArrayBuffer with byteLength > MaxArrayBufferLength we may need to review this math.
  479. Assert(newLen < MaxArrayBufferLength);
  480. uint32 byteLength = static_cast<uint32>(newLen);
  481. ArrayBuffer* newBuffer = nullptr;
  482. if (scriptContext->GetConfig()->IsES6SpeciesEnabled())
  483. {
  484. JavascriptFunction* defaultConstructor = scriptContext->GetLibrary()->GetArrayBufferConstructor();
  485. RecyclableObject* constructor = JavascriptOperators::SpeciesConstructor(arrayBuffer, defaultConstructor, scriptContext);
  486. AssertOrFailFast(JavascriptOperators::IsConstructor(constructor));
  487. bool isDefaultConstructor = constructor == defaultConstructor;
  488. Js::Var newVar = JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isDefaultConstructor, scriptContext->GetThreadContext(), [=]()->Js::Var
  489. {
  490. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(byteLength, scriptContext) };
  491. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  492. return JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext);
  493. });
  494. if (!ArrayBuffer::Is(newVar)) // 24.1.4.3: 19.If new does not have an [[ArrayBufferData]] internal slot throw a TypeError exception.
  495. {
  496. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject);
  497. }
  498. newBuffer = ArrayBuffer::FromVar(newVar);
  499. if (newBuffer->IsDetached()) // 24.1.4.3: 21. If IsDetachedBuffer(new) is true, then throw a TypeError exception.
  500. {
  501. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("ArrayBuffer.prototype.slice"));
  502. }
  503. if (newBuffer == arrayBuffer) // 24.1.4.3: 22. If SameValue(new, O) is true, then throw a TypeError exception.
  504. {
  505. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject);
  506. }
  507. if (newBuffer->bufferLength < byteLength) // 24.1.4.3: 23.If the value of new's [[ArrayBufferByteLength]] internal slot < newLen, then throw a TypeError exception.
  508. {
  509. JavascriptError::ThrowTypeError(scriptContext, JSERR_ArgumentOutOfRange, _u("ArrayBuffer.prototype.slice"));
  510. }
  511. }
  512. else
  513. {
  514. newBuffer = library->CreateArrayBuffer(byteLength);
  515. }
  516. Assert(newBuffer);
  517. Assert(newBuffer->bufferLength >= byteLength);
  518. if (arrayBuffer->IsDetached()) // 24.1.4.3: 24. NOTE: Side-effects of the above steps may have detached O. 25. If IsDetachedBuffer(O) is true, then throw a TypeError exception.
  519. {
  520. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("ArrayBuffer.prototype.slice"));
  521. }
  522. // Don't bother doing memcpy if we aren't copying any elements
  523. if (byteLength > 0)
  524. {
  525. AssertMsg(arrayBuffer->GetBuffer() != nullptr, "buffer must not be null when we copy from it");
  526. js_memcpy_s(newBuffer->GetBuffer(), byteLength, arrayBuffer->GetBuffer() + start, byteLength);
  527. }
  528. return newBuffer;
  529. }
  530. Var ArrayBuffer::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
  531. {
  532. ARGUMENTS(args, callInfo);
  533. Assert(args.Info.Count > 0);
  534. return args[0];
  535. }
  536. ArrayBuffer* ArrayBuffer::FromVar(Var aValue)
  537. {
  538. AssertOrFailFastMsg(Is(aValue), "var must be an ArrayBuffer");
  539. return static_cast<ArrayBuffer *>(aValue);
  540. }
  541. ArrayBuffer* ArrayBuffer::UnsafeFromVar(Var aValue)
  542. {
  543. AssertMsg(Is(aValue), "var must be an ArrayBuffer");
  544. return static_cast<ArrayBuffer *>(aValue);
  545. }
  546. bool ArrayBuffer::Is(Var aValue)
  547. {
  548. return JavascriptOperators::GetTypeId(aValue) == TypeIds_ArrayBuffer;
  549. }
  550. ArrayBufferContentForDelayedFreeBase* ArrayBuffer::CopyBufferContentForDelayedFree(RefCountedBuffer * content, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength)
  551. {
  552. Assert(content != nullptr);
  553. FreeFn* freeFn = nullptr;
  554. #if ENABLE_FAST_ARRAYBUFFER
  555. if (IsValidVirtualBufferLength(bufferLength))
  556. {
  557. freeFn = FreeMemAlloc;
  558. }
  559. else
  560. #endif
  561. {
  562. freeFn = free;
  563. }
  564. // This heap object will be deleted when the Recycler::DelayedFreeArrayBuffer determines to remove this item
  565. return HeapNew(ArrayBufferContentForDelayedFree<FreeFn>, content, bufferLength, GetScriptContext()->GetRecycler(), freeFn);
  566. }
  567. template <class Allocator>
  568. ArrayBuffer::ArrayBuffer(uint32 length, DynamicType * type, Allocator allocator) :
  569. ArrayBufferBase(type), bufferContent(nullptr), bufferLength(0)
  570. {
  571. if (length > MaxArrayBufferLength)
  572. {
  573. JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_FunctionArgument_Invalid);
  574. }
  575. else if (length > 0)
  576. {
  577. BYTE * buffer = nullptr;
  578. Recycler* recycler = GetType()->GetLibrary()->GetRecycler();
  579. if (recycler->RequestExternalMemoryAllocation(length))
  580. {
  581. buffer = (BYTE*)allocator(length);
  582. if (buffer == nullptr)
  583. {
  584. recycler->ReportExternalMemoryFree(length);
  585. }
  586. }
  587. if (buffer == nullptr)
  588. {
  589. recycler->CollectNow<CollectOnTypedArrayAllocation>();
  590. if (recycler->RequestExternalMemoryAllocation(length))
  591. {
  592. buffer = (BYTE*)allocator(length);
  593. if (buffer == nullptr)
  594. {
  595. recycler->ReportExternalMemoryFailure(length);
  596. }
  597. }
  598. }
  599. if (buffer == nullptr)
  600. {
  601. JavascriptError::ThrowOutOfMemoryError(GetScriptContext());
  602. }
  603. else
  604. {
  605. bufferLength = length;
  606. ZeroMemory(buffer, bufferLength);
  607. RefCountedBuffer* localContent = HeapNew(RefCountedBuffer, buffer);
  608. this->bufferContent = localContent;
  609. }
  610. }
  611. }
  612. ArrayBuffer::ArrayBuffer(RefCountedBuffer* buffContent, uint32 length, DynamicType * type)
  613. : bufferContent(nullptr), bufferLength(length), ArrayBufferBase(type)
  614. {
  615. if (length > MaxArrayBufferLength)
  616. {
  617. JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_FunctionArgument_Invalid);
  618. }
  619. // we take the ownership of the buffer and will have to free it so charge it to our quota.
  620. if (!this->GetRecycler()->RequestExternalMemoryAllocation(length))
  621. {
  622. JavascriptError::ThrowOutOfMemoryError(this->GetScriptContext());
  623. }
  624. this->bufferContent = buffContent;
  625. // The bufferContent can be null as might have detached an ArrayBuffer which does not have bufferContent.
  626. if (this->bufferContent != nullptr)
  627. {
  628. this->bufferContent->AddRef();
  629. }
  630. }
  631. ArrayBuffer::ArrayBuffer(byte* buffer, uint32 length, DynamicType * type, bool isExternal) :
  632. bufferContent(nullptr), bufferLength(length), ArrayBufferBase(type)
  633. {
  634. if (length > MaxArrayBufferLength)
  635. {
  636. JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_FunctionArgument_Invalid);
  637. }
  638. if (!isExternal)
  639. {
  640. // we take the ownership of the buffer and will have to free it so charge it to our quota.
  641. if (!this->GetRecycler()->RequestExternalMemoryAllocation(length))
  642. {
  643. JavascriptError::ThrowOutOfMemoryError(this->GetScriptContext());
  644. }
  645. }
  646. if (buffer != nullptr)
  647. {
  648. RefCountedBuffer* localContent = HeapNew(RefCountedBuffer, buffer);
  649. this->bufferContent = localContent;
  650. }
  651. }
  652. BOOL ArrayBuffer::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  653. {
  654. stringBuilder->AppendCppLiteral(_u("Object, (ArrayBuffer)"));
  655. return TRUE;
  656. }
  657. BOOL ArrayBuffer::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  658. {
  659. stringBuilder->AppendCppLiteral(_u("[object ArrayBuffer]"));
  660. return TRUE;
  661. }
  662. void ArrayBuffer::ReleaseBufferContent()
  663. {
  664. if (this->bufferContent != nullptr && this->bufferContent->GetBuffer() != nullptr)
  665. {
  666. RefCountedBuffer *content = this->bufferContent;
  667. this->bufferContent = nullptr;
  668. long refCount = content->Release();
  669. AssertOrFailFast(refCount == 0);
  670. HeapDelete(content);
  671. }
  672. }
  673. #if ENABLE_TTD
  674. void ArrayBufferParent::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
  675. {
  676. extractor->MarkVisitVar(this->arrayBuffer);
  677. }
  678. void ArrayBufferParent::ProcessCorePaths()
  679. {
  680. this->GetScriptContext()->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, this->arrayBuffer, _u("!buffer"));
  681. }
  682. #endif
  683. JavascriptArrayBuffer::JavascriptArrayBuffer(uint32 length, DynamicType * type) :
  684. ArrayBuffer(length, type, IsValidVirtualBufferLength(length) ? AsmJsVirtualAllocator : malloc)
  685. {
  686. }
  687. JavascriptArrayBuffer::JavascriptArrayBuffer(byte* buffer, uint32 length, DynamicType * type) :
  688. ArrayBuffer(buffer, length, type)
  689. {
  690. }
  691. JavascriptArrayBuffer::JavascriptArrayBuffer(RefCountedBuffer* buffer, uint32 length, DynamicType * type) :
  692. ArrayBuffer(buffer, length, type)
  693. {
  694. }
  695. JavascriptArrayBuffer::JavascriptArrayBuffer(DynamicType * type) : ArrayBuffer(0, type, malloc)
  696. {
  697. }
  698. JavascriptArrayBuffer* JavascriptArrayBuffer::Create(uint32 length, DynamicType * type)
  699. {
  700. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  701. JavascriptArrayBuffer* result = RecyclerNewFinalized(recycler, JavascriptArrayBuffer, length, type);
  702. Assert(result);
  703. recycler->AddExternalMemoryUsage(length);
  704. return result;
  705. }
  706. JavascriptArrayBuffer* JavascriptArrayBuffer::Create(byte* buffer, uint32 length, DynamicType * type)
  707. {
  708. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  709. JavascriptArrayBuffer* result = RecyclerNewFinalized(recycler, JavascriptArrayBuffer, buffer, length, type);
  710. Assert(result);
  711. recycler->AddExternalMemoryUsage(length);
  712. return result;
  713. }
  714. JavascriptArrayBuffer* JavascriptArrayBuffer::Create(RefCountedBuffer* content, uint32 length, DynamicType * type)
  715. {
  716. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  717. JavascriptArrayBuffer* result = RecyclerNewFinalized(recycler, JavascriptArrayBuffer, content, length, type);
  718. Assert(result);
  719. recycler->AddExternalMemoryUsage(length);
  720. return result;
  721. }
  722. ArrayBufferDetachedStateBase* JavascriptArrayBuffer::CreateDetachedState(RefCountedBuffer * content, uint32 bufferLength)
  723. {
  724. FreeFn* freeFn = nullptr;
  725. ArrayBufferAllocationType allocationType;
  726. #if ENABLE_FAST_ARRAYBUFFER
  727. if (IsValidVirtualBufferLength(bufferLength))
  728. {
  729. allocationType = ArrayBufferAllocationType::MemAlloc;
  730. freeFn = FreeMemAlloc;
  731. }
  732. else
  733. #endif
  734. {
  735. allocationType = ArrayBufferAllocationType::Heap;
  736. freeFn = free;
  737. }
  738. return HeapNew(ArrayBufferDetachedState<FreeFn>, content, bufferLength, freeFn, GetScriptContext()->GetRecycler(), allocationType);
  739. }
  740. bool JavascriptArrayBuffer::IsValidAsmJsBufferLengthAlgo(uint length, bool forceCheck)
  741. {
  742. /*
  743. 1. length >= 2^16
  744. 2. length is power of 2 or (length > 2^24 and length is multiple of 2^24)
  745. 3. length is a multiple of 4K
  746. */
  747. const bool isLongEnough = length >= 0x10000;
  748. const bool isPow2 = ::Math::IsPow2(length);
  749. // No need to check for length > 2^24, because it already has to be non zero length
  750. const bool isMultipleOf2e24 = (length & 0xFFFFFF) == 0;
  751. const bool isPageSizeMultiple = (length % AutoSystemInfo::PageSize) == 0;
  752. return (
  753. #ifndef ENABLE_FAST_ARRAYBUFFER
  754. forceCheck &&
  755. #endif
  756. isLongEnough &&
  757. (isPow2 || isMultipleOf2e24) &&
  758. isPageSizeMultiple
  759. );
  760. }
  761. bool JavascriptArrayBuffer::IsValidAsmJsBufferLength(uint length, bool forceCheck)
  762. {
  763. return IsValidAsmJsBufferLengthAlgo(length, forceCheck);
  764. }
  765. bool JavascriptArrayBuffer::IsValidVirtualBufferLength(uint length) const
  766. {
  767. #if ENABLE_FAST_ARRAYBUFFER
  768. return PHASE_FORCE1(Js::TypedArrayVirtualPhase) || (!PHASE_OFF1(Js::TypedArrayVirtualPhase) && IsValidAsmJsBufferLengthAlgo(length, true));
  769. #else
  770. return false;
  771. #endif
  772. }
  773. void JavascriptArrayBuffer::Finalize(bool isShutdown)
  774. {
  775. if (this->bufferContent == nullptr)
  776. {
  777. return;
  778. }
  779. RefCountedBuffer *content = this->bufferContent;
  780. this->bufferContent = nullptr;
  781. long refCount = content->Release();
  782. if (refCount == 0)
  783. {
  784. BYTE * buffer = content->GetBuffer();
  785. if (buffer)
  786. {
  787. // Recycler may not be available at Dispose. We need to
  788. // free the memory and report that it has been freed at the same
  789. // time. Otherwise, AllocationPolicyManager is unable to provide correct feedback
  790. #if ENABLE_FAST_ARRAYBUFFER
  791. //AsmJS Virtual Free
  792. if (buffer && IsValidVirtualBufferLength(this->bufferLength))
  793. {
  794. FreeMemAlloc(buffer);
  795. }
  796. else
  797. {
  798. free(buffer);
  799. }
  800. #else
  801. free(buffer);
  802. #endif
  803. }
  804. Recycler* recycler = GetType()->GetLibrary()->GetRecycler();
  805. recycler->ReportExternalMemoryFree(bufferLength);
  806. HeapDelete(content);
  807. }
  808. bufferLength = 0;
  809. }
  810. void JavascriptArrayBuffer::Dispose(bool isShutdown)
  811. {
  812. /* See JavascriptArrayBuffer::Finalize */
  813. }
  814. #if ENABLE_TTD
  815. TTD::NSSnapObjects::SnapObjectType JavascriptArrayBuffer::GetSnapTag_TTD() const
  816. {
  817. return TTD::NSSnapObjects::SnapObjectType::SnapArrayBufferObject;
  818. }
  819. void JavascriptArrayBuffer::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  820. {
  821. TTD::NSSnapObjects::SnapArrayBufferInfo* sabi = alloc.SlabAllocateStruct<TTD::NSSnapObjects::SnapArrayBufferInfo>();
  822. sabi->Length = this->GetByteLength();
  823. if (sabi->Length == 0)
  824. {
  825. sabi->Buff = nullptr;
  826. }
  827. else
  828. {
  829. sabi->Buff = alloc.SlabAllocateArray<byte>(sabi->Length);
  830. memcpy(sabi->Buff, this->GetBuffer(), sabi->Length);
  831. }
  832. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayBufferInfo*, TTD::NSSnapObjects::SnapObjectType::SnapArrayBufferObject>(objData, sabi);
  833. }
  834. #endif
  835. #ifdef ENABLE_WASM
  836. // Same as realloc but zero newly allocated portion if newSize > oldSize
  837. static BYTE* ReallocZero(BYTE* ptr, size_t oldSize, size_t newSize)
  838. {
  839. BYTE* ptrNew = (BYTE*)realloc(ptr, newSize);
  840. if (ptrNew && newSize > oldSize)
  841. {
  842. ZeroMemory(ptrNew + oldSize, newSize - oldSize);
  843. }
  844. return ptrNew;
  845. }
  846. template<typename Allocator>
  847. Js::WebAssemblyArrayBuffer::WebAssemblyArrayBuffer(uint32 length, DynamicType * type, Allocator allocator):
  848. JavascriptArrayBuffer(length, type, allocator)
  849. {
  850. #ifndef ENABLE_FAST_ARRAYBUFFER
  851. CompileAssert(UNREACHED);
  852. #endif
  853. Assert(allocator == WasmVirtualAllocator);
  854. // Make sure we always have a buffer even if the length is 0
  855. if (bufferContent == nullptr && length == 0)
  856. {
  857. // We want to allocate an empty buffer using virtual memory
  858. BYTE *buffer = (BYTE*)allocator(0);
  859. if (buffer == nullptr)
  860. {
  861. JavascriptError::ThrowOutOfMemoryError(GetScriptContext());
  862. }
  863. RefCountedBuffer* localContent = HeapNew(RefCountedBuffer, buffer);
  864. this->bufferContent = localContent;
  865. }
  866. if (bufferContent == nullptr)
  867. {
  868. JavascriptError::ThrowOutOfMemoryError(GetScriptContext());
  869. }
  870. }
  871. // Treat as a normal JavascriptArrayBuffer
  872. WebAssemblyArrayBuffer::WebAssemblyArrayBuffer(uint32 length, DynamicType * type) :
  873. JavascriptArrayBuffer(length, type, malloc)
  874. {
  875. // Make sure we always have a bufferContent even if the length is 0
  876. if (bufferContent == nullptr && length == 0)
  877. {
  878. bufferContent = HeapNew(RefCountedBuffer, nullptr);
  879. }
  880. if (bufferContent == nullptr)
  881. {
  882. JavascriptError::ThrowOutOfMemoryError(GetScriptContext());
  883. }
  884. }
  885. WebAssemblyArrayBuffer::WebAssemblyArrayBuffer(byte* buffer, uint32 length, DynamicType * type):
  886. JavascriptArrayBuffer(buffer, length, type)
  887. {
  888. #if ENABLE_FAST_ARRAYBUFFER
  889. if (CONFIG_FLAG(WasmFastArray) && buffer == nullptr)
  890. {
  891. JavascriptError::ThrowOutOfMemoryError(GetScriptContext());
  892. }
  893. #endif
  894. }
  895. WebAssemblyArrayBuffer* WebAssemblyArrayBuffer::Create(byte* buffer, uint32 length, DynamicType * type)
  896. {
  897. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  898. WebAssemblyArrayBuffer* result = nullptr;
  899. if (buffer)
  900. {
  901. result = RecyclerNewFinalized(recycler, WebAssemblyArrayBuffer, buffer, length, type);
  902. }
  903. else
  904. {
  905. #if ENABLE_FAST_ARRAYBUFFER
  906. if (CONFIG_FLAG(WasmFastArray))
  907. {
  908. result = RecyclerNewFinalized(recycler, WebAssemblyArrayBuffer, length, type, WasmVirtualAllocator);
  909. }
  910. else
  911. #endif
  912. {
  913. result = RecyclerNewFinalized(recycler, WebAssemblyArrayBuffer, length, type);
  914. }
  915. }
  916. recycler->AddExternalMemoryUsage(length);
  917. Assert(result);
  918. return result;
  919. }
  920. bool WebAssemblyArrayBuffer::IsValidVirtualBufferLength(uint length) const
  921. {
  922. #if ENABLE_FAST_ARRAYBUFFER
  923. return CONFIG_FLAG(WasmFastArray);
  924. #else
  925. return false;
  926. #endif
  927. }
  928. ArrayBufferDetachedStateBase* WebAssemblyArrayBuffer::CreateDetachedState(RefCountedBuffer* buffer, uint32 bufferLength)
  929. {
  930. JavascriptError::ThrowTypeError(GetScriptContext(), WASMERR_CantDetach);
  931. }
  932. WebAssemblyArrayBuffer* WebAssemblyArrayBuffer::GrowMemory(uint32 newBufferLength)
  933. {
  934. if (newBufferLength < this->bufferLength)
  935. {
  936. Assert(UNREACHED);
  937. JavascriptError::ThrowTypeError(GetScriptContext(), WASMERR_BufferGrowOnly);
  938. }
  939. uint32 growSize = newBufferLength - this->bufferLength;
  940. const auto finalizeGrowMemory = [&](WebAssemblyArrayBuffer* newArrayBuffer)
  941. {
  942. AssertOrFailFast(newArrayBuffer && newArrayBuffer->GetByteLength() == newBufferLength);
  943. RefCountedBuffer *local = this->GetBufferContent();
  944. // Detach the buffer from this ArrayBuffer
  945. this->Detach();
  946. if (local != nullptr)
  947. {
  948. HeapDelete(local);
  949. }
  950. return newArrayBuffer;
  951. };
  952. // We're not growing the buffer, just create a new WebAssemblyArrayBuffer and detach this
  953. if (growSize == 0)
  954. {
  955. return finalizeGrowMemory(this->GetLibrary()->CreateWebAssemblyArrayBuffer(this->GetBuffer(), this->bufferLength));
  956. }
  957. #if ENABLE_FAST_ARRAYBUFFER
  958. // 8Gb Array case
  959. if (CONFIG_FLAG(WasmFastArray))
  960. {
  961. AssertOrFailFast(this->GetBuffer());
  962. const auto virtualAllocFunc = [&]
  963. {
  964. return !!VirtualAlloc(this->GetBuffer() + this->bufferLength, growSize, MEM_COMMIT, PAGE_READWRITE);
  965. };
  966. if (!this->GetRecycler()->DoExternalAllocation(growSize, virtualAllocFunc))
  967. {
  968. return nullptr;
  969. }
  970. // We are transferring the buffer to the new owner.
  971. // To avoid double-charge to the allocation quota we will free the "diff" amount here.
  972. this->GetRecycler()->ReportExternalMemoryFree(growSize);
  973. return finalizeGrowMemory(this->GetLibrary()->CreateWebAssemblyArrayBuffer(this->GetBuffer(), newBufferLength));
  974. }
  975. #endif
  976. // No previous buffer case
  977. if (this->GetByteLength() == 0)
  978. {
  979. Assert(newBufferLength == growSize);
  980. // Creating a new buffer will do the external memory allocation report
  981. return finalizeGrowMemory(this->GetLibrary()->CreateWebAssemblyArrayBuffer(newBufferLength));
  982. }
  983. // Regular growing case
  984. {
  985. // Disable Interrupts while doing a ReAlloc to minimize chances to end up in a bad state
  986. AutoDisableInterrupt autoDisableInterrupt(this->GetScriptContext()->GetThreadContext(), false);
  987. byte* newBuffer = nullptr;
  988. const auto reallocFunc = [&]
  989. {
  990. newBuffer = ReallocZero(this->GetBuffer(), this->bufferLength, newBufferLength);
  991. if (newBuffer != nullptr)
  992. {
  993. // Realloc freed this->buffer
  994. // if anything goes wrong before we detach, we can't recover the state and should failfast
  995. autoDisableInterrupt.RequireExplicitCompletion();
  996. }
  997. return !!newBuffer;
  998. };
  999. if (!this->GetRecycler()->DoExternalAllocation(growSize, reallocFunc))
  1000. {
  1001. return nullptr;
  1002. }
  1003. // We are transferring the buffer to the new owner.
  1004. // To avoid double-charge to the allocation quota we will free the "diff" amount here.
  1005. this->GetRecycler()->ReportExternalMemoryFree(growSize);
  1006. WebAssemblyArrayBuffer* newArrayBuffer = finalizeGrowMemory(this->GetLibrary()->CreateWebAssemblyArrayBuffer(newBuffer, newBufferLength));
  1007. // We've successfully Detached this buffer and created a new WebAssemblyArrayBuffer
  1008. autoDisableInterrupt.Completed();
  1009. return newArrayBuffer;
  1010. }
  1011. }
  1012. #endif
  1013. ProjectionArrayBuffer::ProjectionArrayBuffer(uint32 length, DynamicType * type) :
  1014. ArrayBuffer(length, type, CoTaskMemAlloc)
  1015. {
  1016. }
  1017. ProjectionArrayBuffer::ProjectionArrayBuffer(byte* buffer, uint32 length, DynamicType * type) :
  1018. ArrayBuffer(buffer, length, type)
  1019. {
  1020. }
  1021. ProjectionArrayBuffer::ProjectionArrayBuffer(RefCountedBuffer* buffer, uint32 length, DynamicType * type) :
  1022. ArrayBuffer(buffer, length, type)
  1023. {
  1024. }
  1025. ProjectionArrayBuffer* ProjectionArrayBuffer::Create(uint32 length, DynamicType * type)
  1026. {
  1027. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  1028. recycler->AddExternalMemoryUsage(length);
  1029. return RecyclerNewFinalized(recycler, ProjectionArrayBuffer, length, type);
  1030. }
  1031. ProjectionArrayBuffer* ProjectionArrayBuffer::Create(byte* buffer, uint32 length, DynamicType * type)
  1032. {
  1033. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  1034. ProjectionArrayBuffer* result = RecyclerNewFinalized(recycler, ProjectionArrayBuffer, buffer, length, type);
  1035. // This is user passed [in] buffer, user should AddExternalMemoryUsage before calling jscript, but
  1036. // I don't see we ask everyone to do this. Let's add the memory pressure here as well.
  1037. recycler->AddExternalMemoryUsage(length);
  1038. return result;
  1039. }
  1040. ProjectionArrayBuffer* ProjectionArrayBuffer::Create(RefCountedBuffer* buffer, uint32 length, DynamicType * type)
  1041. {
  1042. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  1043. ProjectionArrayBuffer* result = RecyclerNewFinalized(recycler, ProjectionArrayBuffer, buffer, length, type);
  1044. // This is user passed [in] buffer, user should AddExternalMemoryUsage before calling jscript, but
  1045. // I don't see we ask everyone to do this. Let's add the memory pressure here as well.
  1046. recycler->AddExternalMemoryUsage(length);
  1047. return result;
  1048. }
  1049. void ProjectionArrayBuffer::Finalize(bool isShutdown)
  1050. {
  1051. if (this->bufferContent == nullptr || this->bufferContent->GetBuffer() == nullptr)
  1052. {
  1053. return;
  1054. }
  1055. RefCountedBuffer *content = this->bufferContent;
  1056. this->bufferContent = nullptr;
  1057. long refCount = content->Release();
  1058. if (refCount == 0)
  1059. {
  1060. CoTaskMemFree(content->GetBuffer());
  1061. // Recycler may not be available at Dispose. We need to
  1062. // free the memory and report that it has been freed at the same
  1063. // time. Otherwise, AllocationPolicyManager is unable to provide correct feedback
  1064. Recycler* recycler = GetType()->GetLibrary()->GetRecycler();
  1065. recycler->ReportExternalMemoryFree(bufferLength);
  1066. HeapDelete(content);
  1067. }
  1068. }
  1069. void ProjectionArrayBuffer::Dispose(bool isShutdown)
  1070. {
  1071. /* See ProjectionArrayBuffer::Finalize */
  1072. }
  1073. ArrayBufferContentForDelayedFreeBase* ProjectionArrayBuffer::CopyBufferContentForDelayedFree(RefCountedBuffer * content, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength)
  1074. {
  1075. // This heap object will be deleted when the Recycler::DelayedFreeArrayBuffer determines to remove this item
  1076. return HeapNew(ArrayBufferContentForDelayedFree<FreeFn>, content, bufferLength, GetRecycler(), CoTaskMemFree);
  1077. }
  1078. ArrayBuffer* ExternalArrayBufferDetachedState::Create(JavascriptLibrary* library)
  1079. {
  1080. return library->CreateExternalArrayBuffer(buffer, bufferLength);
  1081. }
  1082. ExternalArrayBuffer::ExternalArrayBuffer(byte *buffer, uint32 length, DynamicType *type)
  1083. : ArrayBuffer(buffer, length, type, true)
  1084. {
  1085. }
  1086. ExternalArrayBuffer::ExternalArrayBuffer(RefCountedBuffer *buffer, uint32 length, DynamicType *type)
  1087. : ArrayBuffer(buffer, length, type)
  1088. {
  1089. }
  1090. ExternalArrayBuffer* ExternalArrayBuffer::Create(RefCountedBuffer* buffer, uint32 length, DynamicType * type)
  1091. {
  1092. // This type does not own the external memory, so don't AddExternalMemoryUsage like other ArrayBuffer types do
  1093. return RecyclerNewFinalized(type->GetScriptContext()->GetRecycler(), ExternalArrayBuffer, buffer, length, type);
  1094. }
  1095. ArrayBufferDetachedStateBase* ExternalArrayBuffer::CreateDetachedState(RefCountedBuffer* buffer, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength)
  1096. {
  1097. return HeapNew(ExternalArrayBufferDetachedState, buffer, bufferLength);
  1098. };
  1099. void ExternalArrayBuffer::ReportExternalMemoryFree()
  1100. {
  1101. // This type does not own the external memory, so don't ReportExternalMemoryFree like other ArrayBuffer types do
  1102. }
  1103. #if ENABLE_TTD
  1104. TTD::NSSnapObjects::SnapObjectType ExternalArrayBuffer::GetSnapTag_TTD() const
  1105. {
  1106. //We re-map ExternalArrayBuffers to regular buffers since the 'real' host will be gone when we replay
  1107. return TTD::NSSnapObjects::SnapObjectType::SnapArrayBufferObject;
  1108. }
  1109. void ExternalArrayBuffer::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  1110. {
  1111. TTD::NSSnapObjects::SnapArrayBufferInfo* sabi = alloc.SlabAllocateStruct<TTD::NSSnapObjects::SnapArrayBufferInfo>();
  1112. sabi->Length = this->GetByteLength();
  1113. if(sabi->Length == 0)
  1114. {
  1115. sabi->Buff = nullptr;
  1116. }
  1117. else
  1118. {
  1119. sabi->Buff = alloc.SlabAllocateArray<byte>(sabi->Length);
  1120. memcpy(sabi->Buff, this->GetBuffer(), sabi->Length);
  1121. }
  1122. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayBufferInfo*, TTD::NSSnapObjects::SnapObjectType::SnapArrayBufferObject>(objData, sabi);
  1123. }
  1124. #endif
  1125. ExternalArrayBufferDetachedState::ExternalArrayBufferDetachedState(RefCountedBuffer* buffer, uint32 bufferLength)
  1126. : ArrayBufferDetachedStateBase(TypeIds_ArrayBuffer, buffer, bufferLength, ArrayBufferAllocationType::External)
  1127. {}
  1128. void ExternalArrayBufferDetachedState::ClearSelfOnly()
  1129. {
  1130. HeapDelete(this);
  1131. }
  1132. void NoOpFree(byte* data) { }
  1133. void ExternalArrayBufferDetachedState::DiscardState()
  1134. {
  1135. // Don't actually free the data as it's externally managed, but do the
  1136. // appropriate cleanup for our RefCountedBuffer.
  1137. DiscardStateBase(NoOpFree);
  1138. }
  1139. void ExternalArrayBufferDetachedState::Discard()
  1140. {
  1141. ClearSelfOnly();
  1142. }
  1143. }