ArrayBuffer.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  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. if (scriptContext->GetConfig()->IsES6SpeciesEnabled())
  478. {
  479. JavascriptFunction* defaultConstructor = scriptContext->GetLibrary()->GetArrayBufferConstructor();
  480. RecyclableObject* constructor = JavascriptOperators::SpeciesConstructor(arrayBuffer, defaultConstructor, scriptContext);
  481. AssertOrFailFast(JavascriptOperators::IsConstructor(constructor));
  482. bool isDefaultConstructor = constructor == defaultConstructor;
  483. Js::Var newVar = JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isDefaultConstructor, scriptContext->GetThreadContext(), [=]()->Js::Var
  484. {
  485. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(byteLength, scriptContext) };
  486. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  487. return JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext);
  488. });
  489. if (!VarIs<ArrayBuffer>(newVar)) // 24.1.4.3: 19.If new does not have an [[ArrayBufferData]] internal slot throw a TypeError exception.
  490. {
  491. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject);
  492. }
  493. newBuffer = VarTo<ArrayBuffer>(newVar);
  494. if (newBuffer->IsDetached()) // 24.1.4.3: 21. If IsDetachedBuffer(new) is true, then throw a TypeError exception.
  495. {
  496. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("ArrayBuffer.prototype.slice"));
  497. }
  498. if (newBuffer == arrayBuffer) // 24.1.4.3: 22. If SameValue(new, O) is true, then throw a TypeError exception.
  499. {
  500. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject);
  501. }
  502. if (newBuffer->bufferLength < byteLength) // 24.1.4.3: 23.If the value of new's [[ArrayBufferByteLength]] internal slot < newLen, then throw a TypeError exception.
  503. {
  504. JavascriptError::ThrowTypeError(scriptContext, JSERR_ArgumentOutOfRange, _u("ArrayBuffer.prototype.slice"));
  505. }
  506. }
  507. else
  508. {
  509. newBuffer = library->CreateArrayBuffer(byteLength);
  510. }
  511. Assert(newBuffer);
  512. Assert(newBuffer->bufferLength >= byteLength);
  513. 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.
  514. {
  515. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("ArrayBuffer.prototype.slice"));
  516. }
  517. // Don't bother doing memcpy if we aren't copying any elements
  518. if (byteLength > 0)
  519. {
  520. AssertMsg(arrayBuffer->GetBuffer() != nullptr, "buffer must not be null when we copy from it");
  521. js_memcpy_s(newBuffer->GetBuffer(), byteLength, arrayBuffer->GetBuffer() + start, byteLength);
  522. }
  523. return newBuffer;
  524. }
  525. Var ArrayBuffer::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
  526. {
  527. ARGUMENTS(args, callInfo);
  528. Assert(args.Info.Count > 0);
  529. return args[0];
  530. }
  531. ArrayBufferContentForDelayedFreeBase* ArrayBuffer::CopyBufferContentForDelayedFree(RefCountedBuffer * content, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength)
  532. {
  533. Assert(content != nullptr);
  534. FreeFn* freeFn = nullptr;
  535. #if ENABLE_FAST_ARRAYBUFFER
  536. if (IsValidVirtualBufferLength(bufferLength))
  537. {
  538. freeFn = FreeMemAlloc;
  539. }
  540. else
  541. #endif
  542. {
  543. freeFn = free;
  544. }
  545. // This heap object will be deleted when the Recycler::DelayedFreeArrayBuffer determines to remove this item
  546. return HeapNew(ArrayBufferContentForDelayedFree<FreeFn>, content, bufferLength, GetScriptContext()->GetRecycler(), freeFn);
  547. }
  548. template <class Allocator>
  549. ArrayBuffer::ArrayBuffer(uint32 length, DynamicType * type, Allocator allocator) :
  550. ArrayBufferBase(type), bufferContent(nullptr), bufferLength(0)
  551. {
  552. if (length > MaxArrayBufferLength)
  553. {
  554. JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_FunctionArgument_Invalid);
  555. }
  556. else if (length > 0)
  557. {
  558. BYTE * buffer = nullptr;
  559. Recycler* recycler = GetType()->GetLibrary()->GetRecycler();
  560. if (recycler->RequestExternalMemoryAllocation(length))
  561. {
  562. buffer = (BYTE*)allocator(length);
  563. if (buffer == nullptr)
  564. {
  565. recycler->ReportExternalMemoryFree(length);
  566. }
  567. }
  568. if (buffer == nullptr)
  569. {
  570. recycler->CollectNow<CollectOnTypedArrayAllocation>();
  571. if (recycler->RequestExternalMemoryAllocation(length))
  572. {
  573. buffer = (BYTE*)allocator(length);
  574. if (buffer == nullptr)
  575. {
  576. recycler->ReportExternalMemoryFailure(length);
  577. }
  578. }
  579. }
  580. if (buffer == nullptr)
  581. {
  582. JavascriptError::ThrowOutOfMemoryError(GetScriptContext());
  583. }
  584. else
  585. {
  586. bufferLength = length;
  587. ZeroMemory(buffer, bufferLength);
  588. RefCountedBuffer* localContent = HeapNew(RefCountedBuffer, buffer);
  589. this->bufferContent = localContent;
  590. }
  591. }
  592. }
  593. ArrayBuffer::ArrayBuffer(RefCountedBuffer* buffContent, uint32 length, DynamicType * type)
  594. : bufferContent(nullptr), bufferLength(length), ArrayBufferBase(type)
  595. {
  596. if (length > MaxArrayBufferLength)
  597. {
  598. JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_FunctionArgument_Invalid);
  599. }
  600. // we take the ownership of the buffer and will have to free it so charge it to our quota.
  601. if (!this->GetRecycler()->RequestExternalMemoryAllocation(length))
  602. {
  603. JavascriptError::ThrowOutOfMemoryError(this->GetScriptContext());
  604. }
  605. this->bufferContent = buffContent;
  606. // The bufferContent can be null as might have detached an ArrayBuffer which does not have bufferContent.
  607. if (this->bufferContent != nullptr)
  608. {
  609. this->bufferContent->AddRef();
  610. }
  611. }
  612. ArrayBuffer::ArrayBuffer(byte* buffer, uint32 length, DynamicType * type, bool isExternal) :
  613. bufferContent(nullptr), bufferLength(length), ArrayBufferBase(type)
  614. {
  615. if (length > MaxArrayBufferLength)
  616. {
  617. JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_FunctionArgument_Invalid);
  618. }
  619. if (!isExternal)
  620. {
  621. // we take the ownership of the buffer and will have to free it so charge it to our quota.
  622. if (!this->GetRecycler()->RequestExternalMemoryAllocation(length))
  623. {
  624. JavascriptError::ThrowOutOfMemoryError(this->GetScriptContext());
  625. }
  626. }
  627. if (buffer != nullptr)
  628. {
  629. RefCountedBuffer* localContent = HeapNew(RefCountedBuffer, buffer);
  630. this->bufferContent = localContent;
  631. }
  632. }
  633. BOOL ArrayBuffer::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  634. {
  635. stringBuilder->AppendCppLiteral(_u("Object, (ArrayBuffer)"));
  636. return TRUE;
  637. }
  638. BOOL ArrayBuffer::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  639. {
  640. stringBuilder->AppendCppLiteral(_u("[object ArrayBuffer]"));
  641. return TRUE;
  642. }
  643. void ArrayBuffer::ReleaseBufferContent()
  644. {
  645. if (this->bufferContent != nullptr && this->bufferContent->GetBuffer() != nullptr)
  646. {
  647. RefCountedBuffer *content = this->bufferContent;
  648. this->bufferContent = nullptr;
  649. long refCount = content->Release();
  650. AssertOrFailFast(refCount == 0);
  651. HeapDelete(content);
  652. }
  653. }
  654. #if ENABLE_TTD
  655. void ArrayBufferParent::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
  656. {
  657. extractor->MarkVisitVar(this->arrayBuffer);
  658. }
  659. void ArrayBufferParent::ProcessCorePaths()
  660. {
  661. this->GetScriptContext()->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, this->arrayBuffer, _u("!buffer"));
  662. }
  663. #endif
  664. JavascriptArrayBuffer::JavascriptArrayBuffer(uint32 length, DynamicType * type) :
  665. ArrayBuffer(length, type, IsValidVirtualBufferLength(length) ? AsmJsVirtualAllocator : malloc)
  666. {
  667. }
  668. JavascriptArrayBuffer::JavascriptArrayBuffer(byte* buffer, uint32 length, DynamicType * type) :
  669. ArrayBuffer(buffer, length, type)
  670. {
  671. }
  672. JavascriptArrayBuffer::JavascriptArrayBuffer(RefCountedBuffer* buffer, uint32 length, DynamicType * type) :
  673. ArrayBuffer(buffer, length, type)
  674. {
  675. }
  676. JavascriptArrayBuffer::JavascriptArrayBuffer(DynamicType * type) : ArrayBuffer(0, type, malloc)
  677. {
  678. }
  679. JavascriptArrayBuffer* JavascriptArrayBuffer::Create(uint32 length, DynamicType * type)
  680. {
  681. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  682. JavascriptArrayBuffer* result = RecyclerNewFinalized(recycler, JavascriptArrayBuffer, length, type);
  683. Assert(result);
  684. recycler->AddExternalMemoryUsage(length);
  685. return result;
  686. }
  687. JavascriptArrayBuffer* JavascriptArrayBuffer::Create(byte* buffer, uint32 length, DynamicType * type)
  688. {
  689. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  690. JavascriptArrayBuffer* result = RecyclerNewFinalized(recycler, JavascriptArrayBuffer, buffer, length, type);
  691. Assert(result);
  692. recycler->AddExternalMemoryUsage(length);
  693. return result;
  694. }
  695. JavascriptArrayBuffer* JavascriptArrayBuffer::Create(RefCountedBuffer* content, uint32 length, DynamicType * type)
  696. {
  697. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  698. JavascriptArrayBuffer* result = RecyclerNewFinalized(recycler, JavascriptArrayBuffer, content, length, type);
  699. Assert(result);
  700. recycler->AddExternalMemoryUsage(length);
  701. return result;
  702. }
  703. ArrayBufferDetachedStateBase* JavascriptArrayBuffer::CreateDetachedState(RefCountedBuffer * content, uint32 bufferLength)
  704. {
  705. FreeFn* freeFn = nullptr;
  706. ArrayBufferAllocationType allocationType;
  707. #if ENABLE_FAST_ARRAYBUFFER
  708. if (IsValidVirtualBufferLength(bufferLength))
  709. {
  710. allocationType = ArrayBufferAllocationType::MemAlloc;
  711. freeFn = FreeMemAlloc;
  712. }
  713. else
  714. #endif
  715. {
  716. allocationType = ArrayBufferAllocationType::Heap;
  717. freeFn = free;
  718. }
  719. return HeapNew(ArrayBufferDetachedState<FreeFn>, content, bufferLength, freeFn, GetScriptContext()->GetRecycler(), allocationType);
  720. }
  721. bool JavascriptArrayBuffer::IsValidAsmJsBufferLengthAlgo(uint length, bool forceCheck)
  722. {
  723. /*
  724. 1. length >= 2^16
  725. 2. length is power of 2 or (length > 2^24 and length is multiple of 2^24)
  726. 3. length is a multiple of 4K
  727. */
  728. const bool isLongEnough = length >= 0x10000;
  729. const bool isPow2 = ::Math::IsPow2(length);
  730. // No need to check for length > 2^24, because it already has to be non zero length
  731. const bool isMultipleOf2e24 = (length & 0xFFFFFF) == 0;
  732. const bool isPageSizeMultiple = (length % AutoSystemInfo::PageSize) == 0;
  733. return (
  734. #ifndef ENABLE_FAST_ARRAYBUFFER
  735. forceCheck &&
  736. #endif
  737. isLongEnough &&
  738. (isPow2 || isMultipleOf2e24) &&
  739. isPageSizeMultiple
  740. );
  741. }
  742. bool JavascriptArrayBuffer::IsValidAsmJsBufferLength(uint length, bool forceCheck)
  743. {
  744. return IsValidAsmJsBufferLengthAlgo(length, forceCheck);
  745. }
  746. bool JavascriptArrayBuffer::IsValidVirtualBufferLength(uint length) const
  747. {
  748. #if ENABLE_FAST_ARRAYBUFFER
  749. return PHASE_FORCE1(Js::TypedArrayVirtualPhase) || (!PHASE_OFF1(Js::TypedArrayVirtualPhase) && IsValidAsmJsBufferLengthAlgo(length, true));
  750. #else
  751. return false;
  752. #endif
  753. }
  754. void JavascriptArrayBuffer::Finalize(bool isShutdown)
  755. {
  756. if (this->bufferContent == nullptr)
  757. {
  758. return;
  759. }
  760. RefCountedBuffer *content = this->bufferContent;
  761. this->bufferContent = nullptr;
  762. long refCount = content->Release();
  763. if (refCount == 0)
  764. {
  765. BYTE * buffer = content->GetBuffer();
  766. if (buffer)
  767. {
  768. // Recycler may not be available at Dispose. We need to
  769. // free the memory and report that it has been freed at the same
  770. // time. Otherwise, AllocationPolicyManager is unable to provide correct feedback
  771. #if ENABLE_FAST_ARRAYBUFFER
  772. //AsmJS Virtual Free
  773. if (buffer && IsValidVirtualBufferLength(this->bufferLength))
  774. {
  775. FreeMemAlloc(buffer);
  776. }
  777. else
  778. {
  779. free(buffer);
  780. }
  781. #else
  782. free(buffer);
  783. #endif
  784. }
  785. Recycler* recycler = GetType()->GetLibrary()->GetRecycler();
  786. recycler->ReportExternalMemoryFree(bufferLength);
  787. HeapDelete(content);
  788. }
  789. bufferLength = 0;
  790. }
  791. void JavascriptArrayBuffer::Dispose(bool isShutdown)
  792. {
  793. /* See JavascriptArrayBuffer::Finalize */
  794. }
  795. #if ENABLE_TTD
  796. TTD::NSSnapObjects::SnapObjectType JavascriptArrayBuffer::GetSnapTag_TTD() const
  797. {
  798. return TTD::NSSnapObjects::SnapObjectType::SnapArrayBufferObject;
  799. }
  800. void JavascriptArrayBuffer::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  801. {
  802. TTD::NSSnapObjects::SnapArrayBufferInfo* sabi = alloc.SlabAllocateStruct<TTD::NSSnapObjects::SnapArrayBufferInfo>();
  803. sabi->Length = this->GetByteLength();
  804. if (sabi->Length == 0)
  805. {
  806. sabi->Buff = nullptr;
  807. }
  808. else
  809. {
  810. sabi->Buff = alloc.SlabAllocateArray<byte>(sabi->Length);
  811. memcpy(sabi->Buff, this->GetBuffer(), sabi->Length);
  812. }
  813. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayBufferInfo*, TTD::NSSnapObjects::SnapObjectType::SnapArrayBufferObject>(objData, sabi);
  814. }
  815. #endif
  816. #ifdef ENABLE_WASM
  817. // Same as realloc but zero newly allocated portion if newSize > oldSize
  818. static BYTE* ReallocZero(BYTE* ptr, size_t oldSize, size_t newSize)
  819. {
  820. BYTE* ptrNew = (BYTE*)realloc(ptr, newSize);
  821. if (ptrNew && newSize > oldSize)
  822. {
  823. ZeroMemory(ptrNew + oldSize, newSize - oldSize);
  824. }
  825. return ptrNew;
  826. }
  827. template<typename Allocator>
  828. Js::WebAssemblyArrayBuffer::WebAssemblyArrayBuffer(uint32 length, DynamicType * type, Allocator allocator):
  829. JavascriptArrayBuffer(length, type, allocator)
  830. {
  831. #ifndef ENABLE_FAST_ARRAYBUFFER
  832. CompileAssert(UNREACHED);
  833. #endif
  834. Assert(allocator == WasmVirtualAllocator);
  835. // Make sure we always have a buffer even if the length is 0
  836. if (bufferContent == nullptr && length == 0)
  837. {
  838. // We want to allocate an empty buffer using virtual memory
  839. BYTE *buffer = (BYTE*)allocator(0);
  840. if (buffer == nullptr)
  841. {
  842. JavascriptError::ThrowOutOfMemoryError(GetScriptContext());
  843. }
  844. RefCountedBuffer* localContent = HeapNew(RefCountedBuffer, buffer);
  845. this->bufferContent = localContent;
  846. }
  847. if (bufferContent == nullptr)
  848. {
  849. JavascriptError::ThrowOutOfMemoryError(GetScriptContext());
  850. }
  851. }
  852. // Treat as a normal JavascriptArrayBuffer
  853. WebAssemblyArrayBuffer::WebAssemblyArrayBuffer(uint32 length, DynamicType * type) :
  854. JavascriptArrayBuffer(length, type, malloc)
  855. {
  856. // Make sure we always have a bufferContent even if the length is 0
  857. if (bufferContent == nullptr && length == 0)
  858. {
  859. bufferContent = HeapNew(RefCountedBuffer, nullptr);
  860. }
  861. if (bufferContent == nullptr)
  862. {
  863. JavascriptError::ThrowOutOfMemoryError(GetScriptContext());
  864. }
  865. }
  866. WebAssemblyArrayBuffer::WebAssemblyArrayBuffer(byte* buffer, uint32 length, DynamicType * type):
  867. JavascriptArrayBuffer(buffer, length, type)
  868. {
  869. #if ENABLE_FAST_ARRAYBUFFER
  870. if (CONFIG_FLAG(WasmFastArray) && buffer == nullptr)
  871. {
  872. JavascriptError::ThrowOutOfMemoryError(GetScriptContext());
  873. }
  874. #endif
  875. }
  876. WebAssemblyArrayBuffer* WebAssemblyArrayBuffer::Create(byte* buffer, uint32 length, DynamicType * type)
  877. {
  878. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  879. WebAssemblyArrayBuffer* result = nullptr;
  880. if (buffer)
  881. {
  882. result = RecyclerNewFinalized(recycler, WebAssemblyArrayBuffer, buffer, length, type);
  883. }
  884. else
  885. {
  886. #if ENABLE_FAST_ARRAYBUFFER
  887. if (CONFIG_FLAG(WasmFastArray))
  888. {
  889. result = RecyclerNewFinalized(recycler, WebAssemblyArrayBuffer, length, type, WasmVirtualAllocator);
  890. }
  891. else
  892. #endif
  893. {
  894. result = RecyclerNewFinalized(recycler, WebAssemblyArrayBuffer, length, type);
  895. }
  896. }
  897. recycler->AddExternalMemoryUsage(length);
  898. Assert(result);
  899. return result;
  900. }
  901. bool WebAssemblyArrayBuffer::IsValidVirtualBufferLength(uint length) const
  902. {
  903. #if ENABLE_FAST_ARRAYBUFFER
  904. return CONFIG_FLAG(WasmFastArray);
  905. #else
  906. return false;
  907. #endif
  908. }
  909. ArrayBufferDetachedStateBase* WebAssemblyArrayBuffer::CreateDetachedState(RefCountedBuffer* buffer, uint32 bufferLength)
  910. {
  911. JavascriptError::ThrowTypeError(GetScriptContext(), WASMERR_CantDetach);
  912. }
  913. WebAssemblyArrayBuffer* WebAssemblyArrayBuffer::GrowMemory(uint32 newBufferLength)
  914. {
  915. if (newBufferLength < this->bufferLength)
  916. {
  917. Assert(UNREACHED);
  918. JavascriptError::ThrowTypeError(GetScriptContext(), WASMERR_BufferGrowOnly);
  919. }
  920. uint32 growSize = newBufferLength - this->bufferLength;
  921. const auto finalizeGrowMemory = [&](WebAssemblyArrayBuffer* newArrayBuffer)
  922. {
  923. AssertOrFailFast(newArrayBuffer && newArrayBuffer->GetByteLength() == newBufferLength);
  924. RefCountedBuffer *local = this->GetBufferContent();
  925. // Detach the buffer from this ArrayBuffer
  926. this->Detach();
  927. if (local != nullptr)
  928. {
  929. HeapDelete(local);
  930. }
  931. return newArrayBuffer;
  932. };
  933. // We're not growing the buffer, just create a new WebAssemblyArrayBuffer and detach this
  934. if (growSize == 0)
  935. {
  936. return finalizeGrowMemory(this->GetLibrary()->CreateWebAssemblyArrayBuffer(this->GetBuffer(), this->bufferLength));
  937. }
  938. #if ENABLE_FAST_ARRAYBUFFER
  939. // 8Gb Array case
  940. if (CONFIG_FLAG(WasmFastArray))
  941. {
  942. AssertOrFailFast(this->GetBuffer());
  943. const auto virtualAllocFunc = [&]
  944. {
  945. return !!VirtualAlloc(this->GetBuffer() + this->bufferLength, growSize, MEM_COMMIT, PAGE_READWRITE);
  946. };
  947. if (!this->GetRecycler()->DoExternalAllocation(growSize, virtualAllocFunc))
  948. {
  949. return nullptr;
  950. }
  951. // We are transferring the buffer to the new owner.
  952. // To avoid double-charge to the allocation quota we will free the "diff" amount here.
  953. this->GetRecycler()->ReportExternalMemoryFree(growSize);
  954. return finalizeGrowMemory(this->GetLibrary()->CreateWebAssemblyArrayBuffer(this->GetBuffer(), newBufferLength));
  955. }
  956. #endif
  957. // No previous buffer case
  958. if (this->GetByteLength() == 0)
  959. {
  960. Assert(newBufferLength == growSize);
  961. // Creating a new buffer will do the external memory allocation report
  962. return finalizeGrowMemory(this->GetLibrary()->CreateWebAssemblyArrayBuffer(newBufferLength));
  963. }
  964. // Regular growing case
  965. {
  966. // Disable Interrupts while doing a ReAlloc to minimize chances to end up in a bad state
  967. AutoDisableInterrupt autoDisableInterrupt(this->GetScriptContext()->GetThreadContext(), false);
  968. byte* newBuffer = nullptr;
  969. const auto reallocFunc = [&]
  970. {
  971. newBuffer = ReallocZero(this->GetBuffer(), this->bufferLength, newBufferLength);
  972. if (newBuffer != nullptr)
  973. {
  974. // Realloc freed this->buffer
  975. // if anything goes wrong before we detach, we can't recover the state and should failfast
  976. autoDisableInterrupt.RequireExplicitCompletion();
  977. }
  978. return !!newBuffer;
  979. };
  980. if (!this->GetRecycler()->DoExternalAllocation(growSize, reallocFunc))
  981. {
  982. return nullptr;
  983. }
  984. // We are transferring the buffer to the new owner.
  985. // To avoid double-charge to the allocation quota we will free the "diff" amount here.
  986. this->GetRecycler()->ReportExternalMemoryFree(growSize);
  987. WebAssemblyArrayBuffer* newArrayBuffer = finalizeGrowMemory(this->GetLibrary()->CreateWebAssemblyArrayBuffer(newBuffer, newBufferLength));
  988. // We've successfully Detached this buffer and created a new WebAssemblyArrayBuffer
  989. autoDisableInterrupt.Completed();
  990. return newArrayBuffer;
  991. }
  992. }
  993. #endif
  994. ProjectionArrayBuffer::ProjectionArrayBuffer(uint32 length, DynamicType * type) :
  995. ArrayBuffer(length, type, CoTaskMemAlloc)
  996. {
  997. }
  998. ProjectionArrayBuffer::ProjectionArrayBuffer(byte* buffer, uint32 length, DynamicType * type) :
  999. ArrayBuffer(buffer, length, type)
  1000. {
  1001. }
  1002. ProjectionArrayBuffer::ProjectionArrayBuffer(RefCountedBuffer* buffer, uint32 length, DynamicType * type) :
  1003. ArrayBuffer(buffer, length, type)
  1004. {
  1005. }
  1006. ProjectionArrayBuffer* ProjectionArrayBuffer::Create(uint32 length, DynamicType * type)
  1007. {
  1008. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  1009. recycler->AddExternalMemoryUsage(length);
  1010. return RecyclerNewFinalized(recycler, ProjectionArrayBuffer, length, type);
  1011. }
  1012. ProjectionArrayBuffer* ProjectionArrayBuffer::Create(byte* buffer, uint32 length, DynamicType * type)
  1013. {
  1014. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  1015. ProjectionArrayBuffer* result = RecyclerNewFinalized(recycler, ProjectionArrayBuffer, buffer, length, type);
  1016. // This is user passed [in] buffer, user should AddExternalMemoryUsage before calling jscript, but
  1017. // I don't see we ask everyone to do this. Let's add the memory pressure here as well.
  1018. recycler->AddExternalMemoryUsage(length);
  1019. return result;
  1020. }
  1021. ProjectionArrayBuffer* ProjectionArrayBuffer::Create(RefCountedBuffer* buffer, uint32 length, DynamicType * type)
  1022. {
  1023. Recycler* recycler = type->GetScriptContext()->GetRecycler();
  1024. ProjectionArrayBuffer* result = RecyclerNewFinalized(recycler, ProjectionArrayBuffer, buffer, length, type);
  1025. // This is user passed [in] buffer, user should AddExternalMemoryUsage before calling jscript, but
  1026. // I don't see we ask everyone to do this. Let's add the memory pressure here as well.
  1027. recycler->AddExternalMemoryUsage(length);
  1028. return result;
  1029. }
  1030. void ProjectionArrayBuffer::Finalize(bool isShutdown)
  1031. {
  1032. if (this->bufferContent == nullptr || this->bufferContent->GetBuffer() == nullptr)
  1033. {
  1034. return;
  1035. }
  1036. RefCountedBuffer *content = this->bufferContent;
  1037. this->bufferContent = nullptr;
  1038. long refCount = content->Release();
  1039. if (refCount == 0)
  1040. {
  1041. CoTaskMemFree(content->GetBuffer());
  1042. // Recycler may not be available at Dispose. We need to
  1043. // free the memory and report that it has been freed at the same
  1044. // time. Otherwise, AllocationPolicyManager is unable to provide correct feedback
  1045. Recycler* recycler = GetType()->GetLibrary()->GetRecycler();
  1046. recycler->ReportExternalMemoryFree(bufferLength);
  1047. HeapDelete(content);
  1048. }
  1049. }
  1050. void ProjectionArrayBuffer::Dispose(bool isShutdown)
  1051. {
  1052. /* See ProjectionArrayBuffer::Finalize */
  1053. }
  1054. ArrayBufferContentForDelayedFreeBase* ProjectionArrayBuffer::CopyBufferContentForDelayedFree(RefCountedBuffer * content, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength)
  1055. {
  1056. // This heap object will be deleted when the Recycler::DelayedFreeArrayBuffer determines to remove this item
  1057. return HeapNew(ArrayBufferContentForDelayedFree<FreeFn>, content, bufferLength, GetRecycler(), CoTaskMemFree);
  1058. }
  1059. ArrayBuffer* ExternalArrayBufferDetachedState::Create(JavascriptLibrary* library)
  1060. {
  1061. return library->CreateExternalArrayBuffer(buffer, bufferLength);
  1062. }
  1063. ExternalArrayBuffer::ExternalArrayBuffer(byte *buffer, uint32 length, DynamicType *type)
  1064. : ArrayBuffer(buffer, length, type, true)
  1065. {
  1066. }
  1067. ExternalArrayBuffer::ExternalArrayBuffer(RefCountedBuffer *buffer, uint32 length, DynamicType *type)
  1068. : ArrayBuffer(buffer, length, type)
  1069. {
  1070. }
  1071. ExternalArrayBuffer* ExternalArrayBuffer::Create(RefCountedBuffer* buffer, uint32 length, DynamicType * type)
  1072. {
  1073. // This type does not own the external memory, so don't AddExternalMemoryUsage like other ArrayBuffer types do
  1074. return RecyclerNewFinalized(type->GetScriptContext()->GetRecycler(), ExternalArrayBuffer, buffer, length, type);
  1075. }
  1076. ArrayBufferDetachedStateBase* ExternalArrayBuffer::CreateDetachedState(RefCountedBuffer* buffer, DECLSPEC_GUARD_OVERFLOW uint32 bufferLength)
  1077. {
  1078. return HeapNew(ExternalArrayBufferDetachedState, buffer, bufferLength);
  1079. };
  1080. void ExternalArrayBuffer::ReportExternalMemoryFree()
  1081. {
  1082. // This type does not own the external memory, so don't ReportExternalMemoryFree like other ArrayBuffer types do
  1083. }
  1084. #if ENABLE_TTD
  1085. TTD::NSSnapObjects::SnapObjectType ExternalArrayBuffer::GetSnapTag_TTD() const
  1086. {
  1087. //We re-map ExternalArrayBuffers to regular buffers since the 'real' host will be gone when we replay
  1088. return TTD::NSSnapObjects::SnapObjectType::SnapArrayBufferObject;
  1089. }
  1090. void ExternalArrayBuffer::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  1091. {
  1092. TTD::NSSnapObjects::SnapArrayBufferInfo* sabi = alloc.SlabAllocateStruct<TTD::NSSnapObjects::SnapArrayBufferInfo>();
  1093. sabi->Length = this->GetByteLength();
  1094. if(sabi->Length == 0)
  1095. {
  1096. sabi->Buff = nullptr;
  1097. }
  1098. else
  1099. {
  1100. sabi->Buff = alloc.SlabAllocateArray<byte>(sabi->Length);
  1101. memcpy(sabi->Buff, this->GetBuffer(), sabi->Length);
  1102. }
  1103. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayBufferInfo*, TTD::NSSnapObjects::SnapObjectType::SnapArrayBufferObject>(objData, sabi);
  1104. }
  1105. #endif
  1106. ExternalArrayBufferDetachedState::ExternalArrayBufferDetachedState(RefCountedBuffer* buffer, uint32 bufferLength)
  1107. : ArrayBufferDetachedStateBase(TypeIds_ArrayBuffer, buffer, bufferLength, ArrayBufferAllocationType::External)
  1108. {}
  1109. void ExternalArrayBufferDetachedState::ClearSelfOnly()
  1110. {
  1111. HeapDelete(this);
  1112. }
  1113. void NoOpFree(byte* data) { }
  1114. void ExternalArrayBufferDetachedState::DiscardState()
  1115. {
  1116. // Don't actually free the data as it's externally managed, but do the
  1117. // appropriate cleanup for our RefCountedBuffer.
  1118. DiscardStateBase(NoOpFree);
  1119. }
  1120. void ExternalArrayBufferDetachedState::Discard()
  1121. {
  1122. ClearSelfOnly();
  1123. }
  1124. }