ArrayBuffer.cpp 48 KB

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