ArrayBuffer.cpp 40 KB

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