test-api-array-buffer.cc 31.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "test/cctest/test-api.h"

#include "src/api/api-inl.h"

using ::v8::Array;
using ::v8::Context;
using ::v8::Local;
using ::v8::Value;

namespace {

void CheckDataViewIsDetached(v8::Local<v8::DataView> dv) {
  CHECK_EQ(0, static_cast<int>(dv->ByteLength()));
  CHECK_EQ(0, static_cast<int>(dv->ByteOffset()));
}

void CheckIsDetached(v8::Local<v8::TypedArray> ta) {
  CHECK_EQ(0, static_cast<int>(ta->ByteLength()));
  CHECK_EQ(0, static_cast<int>(ta->Length()));
  CHECK_EQ(0, static_cast<int>(ta->ByteOffset()));
}

void CheckIsTypedArrayVarDetached(const char* name) {
  i::ScopedVector<char> source(1024);
  i::SNPrintF(source,
              "%s.byteLength == 0 && %s.byteOffset == 0 && %s.length == 0",
              name, name, name);
  CHECK(CompileRun(source.begin())->IsTrue());
  v8::Local<v8::TypedArray> ta =
      v8::Local<v8::TypedArray>::Cast(CompileRun(name));
  CheckIsDetached(ta);
}

template <typename TypedArray, int kElementSize>
Local<TypedArray> CreateAndCheck(Local<v8::ArrayBuffer> ab, int byteOffset,
                                 int length) {
  v8::Local<TypedArray> ta = TypedArray::New(ab, byteOffset, length);
  CheckInternalFieldsAreZero<v8::ArrayBufferView>(ta);
  CHECK_EQ(byteOffset, static_cast<int>(ta->ByteOffset()));
  CHECK_EQ(length, static_cast<int>(ta->Length()));
  CHECK_EQ(length * kElementSize, static_cast<int>(ta->ByteLength()));
  return ta;
}

49 50
std::shared_ptr<v8::BackingStore> Externalize(Local<v8::ArrayBuffer> ab) {
  std::shared_ptr<v8::BackingStore> backing_store = ab->GetBackingStore();
51 52 53 54 55
  // Keep the tests until the deprecated functions are removed.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
56 57
  ab->Externalize(backing_store);
  CHECK(ab->IsExternal());
58 59 60
#if __clang__
#pragma clang diagnostic pop
#endif
61 62 63 64 65
  return backing_store;
}

std::shared_ptr<v8::BackingStore> Externalize(Local<v8::SharedArrayBuffer> ab) {
  std::shared_ptr<v8::BackingStore> backing_store = ab->GetBackingStore();
66 67 68 69 70
  // Keep the tests until the deprecated functions are removed.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
71 72
  ab->Externalize(backing_store);
  CHECK(ab->IsExternal());
73 74 75
#if __clang__
#pragma clang diagnostic pop
#endif
76 77 78
  return backing_store;
}

79 80 81 82 83 84 85 86 87
}  // namespace

THREADED_TEST(ArrayBuffer_ApiInternalToExternal) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, 1024);
  CheckInternalFieldsAreZero(ab);
88
  CHECK_EQ(1024, ab->ByteLength());
89 90
  CcTest::CollectAllGarbage();

91 92
  std::shared_ptr<v8::BackingStore> backing_store = Externalize(ab);
  CHECK_EQ(1024, backing_store->ByteLength());
93

94
  uint8_t* data = static_cast<uint8_t*>(backing_store->Data());
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
  CHECK_NOT_NULL(data);
  CHECK(env->Global()->Set(env.local(), v8_str("ab"), ab).FromJust());

  v8::Local<v8::Value> result = CompileRun("ab.byteLength");
  CHECK_EQ(1024, result->Int32Value(env.local()).FromJust());

  result = CompileRun(
      "var u8 = new Uint8Array(ab);"
      "u8[0] = 0xFF;"
      "u8[1] = 0xAA;"
      "u8.length");
  CHECK_EQ(1024, result->Int32Value(env.local()).FromJust());
  CHECK_EQ(0xFF, data[0]);
  CHECK_EQ(0xAA, data[1]);
  data[0] = 0xCC;
  data[1] = 0x11;
  result = CompileRun("u8[0] + u8[1]");
  CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}

THREADED_TEST(ArrayBuffer_JSInternalToExternal) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  v8::Local<v8::Value> result = CompileRun(
      "var ab1 = new ArrayBuffer(2);"
      "var u8_a = new Uint8Array(ab1);"
      "u8_a[0] = 0xAA;"
      "u8_a[1] = 0xFF; u8_a.buffer");
  Local<v8::ArrayBuffer> ab1 = Local<v8::ArrayBuffer>::Cast(result);
  CheckInternalFieldsAreZero(ab1);
127 128
  CHECK_EQ(2, ab1->ByteLength());
  std::shared_ptr<v8::BackingStore> backing_store = Externalize(ab1);
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

  result = CompileRun("ab1.byteLength");
  CHECK_EQ(2, result->Int32Value(env.local()).FromJust());
  result = CompileRun("u8_a[0]");
  CHECK_EQ(0xAA, result->Int32Value(env.local()).FromJust());
  result = CompileRun("u8_a[1]");
  CHECK_EQ(0xFF, result->Int32Value(env.local()).FromJust());
  result = CompileRun(
      "var u8_b = new Uint8Array(ab1);"
      "u8_b[0] = 0xBB;"
      "u8_a[0]");
  CHECK_EQ(0xBB, result->Int32Value(env.local()).FromJust());
  result = CompileRun("u8_b[1]");
  CHECK_EQ(0xFF, result->Int32Value(env.local()).FromJust());

144 145
  CHECK_EQ(2, backing_store->ByteLength());
  uint8_t* ab1_data = static_cast<uint8_t*>(backing_store->Data());
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  CHECK_EQ(0xBB, ab1_data[0]);
  CHECK_EQ(0xFF, ab1_data[1]);
  ab1_data[0] = 0xCC;
  ab1_data[1] = 0x11;
  result = CompileRun("u8_a[0] + u8_a[1]");
  CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}

THREADED_TEST(ArrayBuffer_External) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  i::ScopedVector<uint8_t> my_data(100);
  memset(my_data.begin(), 0, 100);
161 162 163 164 165
  // Keep the tests until the deprecated functions are removed.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
166 167 168
  Local<v8::ArrayBuffer> ab3 =
      v8::ArrayBuffer::New(isolate, my_data.begin(), 100);
  CheckInternalFieldsAreZero(ab3);
169
  CHECK_EQ(100, ab3->ByteLength());
170
  CHECK(ab3->IsExternal());
171 172 173
#if __clang__
#pragma clang diagnostic pop
#endif
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

  CHECK(env->Global()->Set(env.local(), v8_str("ab3"), ab3).FromJust());

  v8::Local<v8::Value> result = CompileRun("ab3.byteLength");
  CHECK_EQ(100, result->Int32Value(env.local()).FromJust());

  result = CompileRun(
      "var u8_b = new Uint8Array(ab3);"
      "u8_b[0] = 0xBB;"
      "u8_b[1] = 0xCC;"
      "u8_b.length");
  CHECK_EQ(100, result->Int32Value(env.local()).FromJust());
  CHECK_EQ(0xBB, my_data[0]);
  CHECK_EQ(0xCC, my_data[1]);
  my_data[0] = 0xCC;
  my_data[1] = 0x11;
  result = CompileRun("u8_b[0] + u8_b[1]");
  CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}

THREADED_TEST(ArrayBuffer_DisableDetach) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

199
  Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, 100);
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
  CHECK(ab->IsDetachable());

  i::Handle<i::JSArrayBuffer> buf = v8::Utils::OpenHandle(*ab);
  buf->set_is_detachable(false);

  CHECK(!ab->IsDetachable());
}

THREADED_TEST(ArrayBuffer_DetachingApi) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  v8::Local<v8::ArrayBuffer> buffer = v8::ArrayBuffer::New(isolate, 1024);

  v8::Local<v8::Uint8Array> u8a =
      CreateAndCheck<v8::Uint8Array, 1>(buffer, 1, 1023);
  v8::Local<v8::Uint8ClampedArray> u8c =
      CreateAndCheck<v8::Uint8ClampedArray, 1>(buffer, 1, 1023);
  v8::Local<v8::Int8Array> i8a =
      CreateAndCheck<v8::Int8Array, 1>(buffer, 1, 1023);

  v8::Local<v8::Uint16Array> u16a =
      CreateAndCheck<v8::Uint16Array, 2>(buffer, 2, 511);
  v8::Local<v8::Int16Array> i16a =
      CreateAndCheck<v8::Int16Array, 2>(buffer, 2, 511);

  v8::Local<v8::Uint32Array> u32a =
      CreateAndCheck<v8::Uint32Array, 4>(buffer, 4, 255);
  v8::Local<v8::Int32Array> i32a =
      CreateAndCheck<v8::Int32Array, 4>(buffer, 4, 255);

  v8::Local<v8::Float32Array> f32a =
      CreateAndCheck<v8::Float32Array, 4>(buffer, 4, 255);
  v8::Local<v8::Float64Array> f64a =
      CreateAndCheck<v8::Float64Array, 8>(buffer, 8, 127);

  v8::Local<v8::DataView> dv = v8::DataView::New(buffer, 1, 1023);
  CheckInternalFieldsAreZero<v8::ArrayBufferView>(dv);
239 240
  CHECK_EQ(1, dv->ByteOffset());
  CHECK_EQ(1023, dv->ByteLength());
241

242
  Externalize(buffer);
243
  buffer->Detach();
244
  CHECK_EQ(0, buffer->ByteLength());
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  CheckIsDetached(u8a);
  CheckIsDetached(u8c);
  CheckIsDetached(i8a);
  CheckIsDetached(u16a);
  CheckIsDetached(i16a);
  CheckIsDetached(u32a);
  CheckIsDetached(i32a);
  CheckIsDetached(f32a);
  CheckIsDetached(f64a);
  CheckDataViewIsDetached(dv);
}

THREADED_TEST(ArrayBuffer_DetachingScript) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  CompileRun(
      "var ab = new ArrayBuffer(1024);"
      "var u8a = new Uint8Array(ab, 1, 1023);"
      "var u8c = new Uint8ClampedArray(ab, 1, 1023);"
      "var i8a = new Int8Array(ab, 1, 1023);"
      "var u16a = new Uint16Array(ab, 2, 511);"
      "var i16a = new Int16Array(ab, 2, 511);"
      "var u32a = new Uint32Array(ab, 4, 255);"
      "var i32a = new Int32Array(ab, 4, 255);"
      "var f32a = new Float32Array(ab, 4, 255);"
      "var f64a = new Float64Array(ab, 8, 127);"
      "var dv = new DataView(ab, 1, 1023);");

  v8::Local<v8::ArrayBuffer> ab =
      Local<v8::ArrayBuffer>::Cast(CompileRun("ab"));

  v8::Local<v8::DataView> dv = v8::Local<v8::DataView>::Cast(CompileRun("dv"));

280
  Externalize(ab);
281
  ab->Detach();
282
  CHECK_EQ(0, ab->ByteLength());
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  CHECK_EQ(0, v8_run_int32value(v8_compile("ab.byteLength")));

  CheckIsTypedArrayVarDetached("u8a");
  CheckIsTypedArrayVarDetached("u8c");
  CheckIsTypedArrayVarDetached("i8a");
  CheckIsTypedArrayVarDetached("u16a");
  CheckIsTypedArrayVarDetached("i16a");
  CheckIsTypedArrayVarDetached("u32a");
  CheckIsTypedArrayVarDetached("i32a");
  CheckIsTypedArrayVarDetached("f32a");
  CheckIsTypedArrayVarDetached("f64a");

  CHECK(CompileRun("dv.byteLength == 0 && dv.byteOffset == 0")->IsTrue());
  CheckDataViewIsDetached(dv);
}

299
// TODO(v8:9380) the Contents data structure should be deprecated.
300 301 302 303 304 305 306
THREADED_TEST(ArrayBuffer_AllocationInformation) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  const size_t ab_size = 1024;
  Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, ab_size);
307 308 309 310
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
311
  v8::ArrayBuffer::Contents contents(ab->GetContents());
312 313 314 315
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

  // Array buffers should have normal allocation mode.
  CHECK_EQ(contents.AllocationMode(),
           v8::ArrayBuffer::Allocator::AllocationMode::kNormal);
  // The allocation must contain the buffer (normally they will be equal, but
  // this is not required by the contract).
  CHECK_NOT_NULL(contents.AllocationBase());
  const uintptr_t alloc =
      reinterpret_cast<uintptr_t>(contents.AllocationBase());
  const uintptr_t data = reinterpret_cast<uintptr_t>(contents.Data());
  CHECK_LE(alloc, data);
  CHECK_LE(data + contents.ByteLength(), alloc + contents.AllocationLength());
}

THREADED_TEST(ArrayBuffer_ExternalizeEmpty) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

335
  Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, 2);
336
  CheckInternalFieldsAreZero(ab);
337
  CHECK_EQ(2, ab->ByteLength());
338 339

  // Externalize the buffer (taking ownership of the backing store memory).
340
  std::shared_ptr<v8::BackingStore> backing_store = Externalize(ab);
341 342 343 344 345 346 347 348

  Local<v8::Uint8Array> u8a = v8::Uint8Array::New(ab, 0, 0);
  // Calling Buffer() will materialize the ArrayBuffer (transitioning it from
  // on-heap to off-heap if need be). This should not affect whether it is
  // marked as is_external or not.
  USE(u8a->Buffer());

  CHECK(ab->IsExternal());
349
  CHECK_EQ(2, backing_store->ByteLength());
350 351 352 353 354 355 356 357 358 359
}

THREADED_TEST(SharedArrayBuffer_ApiInternalToExternal) {
  i::FLAG_harmony_sharedarraybuffer = true;
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  Local<v8::SharedArrayBuffer> ab = v8::SharedArrayBuffer::New(isolate, 1024);
  CheckInternalFieldsAreZero(ab);
360
  CHECK_EQ(1024, ab->ByteLength());
361 362
  CcTest::CollectAllGarbage();

363
  std::shared_ptr<v8::BackingStore> backing_store = Externalize(ab);
364

365 366
  CHECK_EQ(1024, backing_store->ByteLength());
  uint8_t* data = static_cast<uint8_t*>(backing_store->Data());
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
  CHECK_NOT_NULL(data);
  CHECK(env->Global()->Set(env.local(), v8_str("ab"), ab).FromJust());

  v8::Local<v8::Value> result = CompileRun("ab.byteLength");
  CHECK_EQ(1024, result->Int32Value(env.local()).FromJust());

  result = CompileRun(
      "var u8 = new Uint8Array(ab);"
      "u8[0] = 0xFF;"
      "u8[1] = 0xAA;"
      "u8.length");
  CHECK_EQ(1024, result->Int32Value(env.local()).FromJust());
  CHECK_EQ(0xFF, data[0]);
  CHECK_EQ(0xAA, data[1]);
  data[0] = 0xCC;
  data[1] = 0x11;
  result = CompileRun("u8[0] + u8[1]");
  CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
THREADED_TEST(ArrayBuffer_ExternalReused) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  i::ScopedVector<uint8_t> data(100);
  Local<v8::ArrayBuffer> ab1 = v8::ArrayBuffer::New(isolate, data.begin(), 100);
  std::shared_ptr<v8::BackingStore> bs1 = ab1->GetBackingStore();
  ab1->Detach();
  Local<v8::ArrayBuffer> ab2 = v8::ArrayBuffer::New(isolate, data.begin(), 100);
  std::shared_ptr<v8::BackingStore> bs2 = ab2->GetBackingStore();
  CHECK_EQ(bs1->Data(), bs2->Data());
}

THREADED_TEST(SharedArrayBuffer_ExternalReused) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  i::ScopedVector<uint8_t> data(100);
  Local<v8::SharedArrayBuffer> ab1 =
      v8::SharedArrayBuffer::New(isolate, data.begin(), 100);
  std::shared_ptr<v8::BackingStore> bs1 = ab1->GetBackingStore();
  Local<v8::SharedArrayBuffer> ab2 =
      v8::SharedArrayBuffer::New(isolate, data.begin(), 100);
  std::shared_ptr<v8::BackingStore> bs2 = ab2->GetBackingStore();
  CHECK_EQ(bs1->Data(), bs2->Data());
}

416 417 418 419 420 421 422 423 424 425 426 427 428
THREADED_TEST(SharedArrayBuffer_JSInternalToExternal) {
  i::FLAG_harmony_sharedarraybuffer = true;
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  v8::Local<v8::Value> result = CompileRun(
      "var ab1 = new SharedArrayBuffer(2);"
      "var u8_a = new Uint8Array(ab1);"
      "u8_a[0] = 0xAA;"
      "u8_a[1] = 0xFF; u8_a.buffer");
  Local<v8::SharedArrayBuffer> ab1 = Local<v8::SharedArrayBuffer>::Cast(result);
  CheckInternalFieldsAreZero(ab1);
429
  CHECK_EQ(2, ab1->ByteLength());
430
  CHECK(!ab1->IsExternal());
431
  std::shared_ptr<v8::BackingStore> backing_store = Externalize(ab1);
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

  result = CompileRun("ab1.byteLength");
  CHECK_EQ(2, result->Int32Value(env.local()).FromJust());
  result = CompileRun("u8_a[0]");
  CHECK_EQ(0xAA, result->Int32Value(env.local()).FromJust());
  result = CompileRun("u8_a[1]");
  CHECK_EQ(0xFF, result->Int32Value(env.local()).FromJust());
  result = CompileRun(
      "var u8_b = new Uint8Array(ab1);"
      "u8_b[0] = 0xBB;"
      "u8_a[0]");
  CHECK_EQ(0xBB, result->Int32Value(env.local()).FromJust());
  result = CompileRun("u8_b[1]");
  CHECK_EQ(0xFF, result->Int32Value(env.local()).FromJust());

447 448
  CHECK_EQ(2, backing_store->ByteLength());
  uint8_t* ab1_data = static_cast<uint8_t*>(backing_store->Data());
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  CHECK_EQ(0xBB, ab1_data[0]);
  CHECK_EQ(0xFF, ab1_data[1]);
  ab1_data[0] = 0xCC;
  ab1_data[1] = 0x11;
  result = CompileRun("u8_a[0] + u8_a[1]");
  CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}

THREADED_TEST(SharedArrayBuffer_External) {
  i::FLAG_harmony_sharedarraybuffer = true;
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  i::ScopedVector<uint8_t> my_data(100);
  memset(my_data.begin(), 0, 100);
  Local<v8::SharedArrayBuffer> ab3 =
      v8::SharedArrayBuffer::New(isolate, my_data.begin(), 100);
  CheckInternalFieldsAreZero(ab3);
  CHECK_EQ(100, static_cast<int>(ab3->ByteLength()));
  CHECK(ab3->IsExternal());

  CHECK(env->Global()->Set(env.local(), v8_str("ab3"), ab3).FromJust());

  v8::Local<v8::Value> result = CompileRun("ab3.byteLength");
  CHECK_EQ(100, result->Int32Value(env.local()).FromJust());

  result = CompileRun(
      "var u8_b = new Uint8Array(ab3);"
      "u8_b[0] = 0xBB;"
      "u8_b[1] = 0xCC;"
      "u8_b.length");
  CHECK_EQ(100, result->Int32Value(env.local()).FromJust());
  CHECK_EQ(0xBB, my_data[0]);
  CHECK_EQ(0xCC, my_data[1]);
  my_data[0] = 0xCC;
  my_data[1] = 0x11;
  result = CompileRun("u8_b[0] + u8_b[1]");
  CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}

490
// TODO(v8:9380) the Contents data structure should be deprecated.
491 492 493 494 495 496 497 498 499
THREADED_TEST(SharedArrayBuffer_AllocationInformation) {
  i::FLAG_harmony_sharedarraybuffer = true;
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  const size_t ab_size = 1024;
  Local<v8::SharedArrayBuffer> ab =
      v8::SharedArrayBuffer::New(isolate, ab_size);
500
  v8::SharedArrayBuffer::Contents contents(ab->GetContents());
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

  // Array buffers should have normal allocation mode.
  CHECK_EQ(contents.AllocationMode(),
           v8::ArrayBuffer::Allocator::AllocationMode::kNormal);
  // The allocation must contain the buffer (normally they will be equal, but
  // this is not required by the contract).
  CHECK_NOT_NULL(contents.AllocationBase());
  const uintptr_t alloc =
      reinterpret_cast<uintptr_t>(contents.AllocationBase());
  const uintptr_t data = reinterpret_cast<uintptr_t>(contents.Data());
  CHECK_LE(alloc, data);
  CHECK_LE(data + contents.ByteLength(), alloc + contents.AllocationLength());
}

THREADED_TEST(SkipArrayBufferBackingStoreDuringGC) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  // Make sure the pointer looks like a heap object
  uint8_t* store_ptr = reinterpret_cast<uint8_t*>(i::kHeapObjectTag);

  // Create ArrayBuffer with pointer-that-cannot-be-visited in the backing store
  Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, store_ptr, 8);

  // Should not crash
  CcTest::CollectGarbage(i::NEW_SPACE);  // in survivor space now
  CcTest::CollectGarbage(i::NEW_SPACE);  // in old gen now
  CcTest::CollectAllGarbage();
  CcTest::CollectAllGarbage();

  // Should not move the pointer
533
  CHECK_EQ(ab->GetBackingStore()->Data(), store_ptr);
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
}

THREADED_TEST(SkipArrayBufferDuringScavenge) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  // Make sure the pointer looks like a heap object
  Local<v8::Object> tmp = v8::Object::New(isolate);
  uint8_t* store_ptr =
      reinterpret_cast<uint8_t*>(*reinterpret_cast<uintptr_t*>(*tmp));

  // Make `store_ptr` point to from space
  CcTest::CollectGarbage(i::NEW_SPACE);

  // Create ArrayBuffer with pointer-that-cannot-be-visited in the backing store
  Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, store_ptr, 8);

  // Should not crash,
  // i.e. backing store pointer should not be treated as a heap object pointer
  CcTest::CollectGarbage(i::NEW_SPACE);  // in survivor space now
  CcTest::CollectGarbage(i::NEW_SPACE);  // in old gen now

  // Use `ab` to silence compiler warning
558
  CHECK_EQ(ab->GetBackingStore()->Data(), store_ptr);
559
}
560 561 562 563 564 565 566 567 568 569 570

THREADED_TEST(Regress1006600) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);

  Local<v8::Value> ab = CompileRunChecked(isolate, "new ArrayBuffer()");
  for (int i = 0; i < v8::ArrayBuffer::kEmbedderFieldCount; i++) {
    CHECK_NULL(ab.As<v8::Object>()->GetAlignedPointerFromInternalField(i));
  }
}
571 572 573 574 575 576 577

THREADED_TEST(ArrayBuffer_NewBackingStore) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  std::shared_ptr<v8::BackingStore> backing_store =
      v8::ArrayBuffer::NewBackingStore(isolate, 100);
578
  CHECK(!backing_store->IsShared());
579 580 581 582 583 584 585 586 587 588
  Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, backing_store);
  CHECK_EQ(backing_store.get(), ab->GetBackingStore().get());
}

THREADED_TEST(SharedArrayBuffer_NewBackingStore) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  std::shared_ptr<v8::BackingStore> backing_store =
      v8::SharedArrayBuffer::NewBackingStore(isolate, 100);
589
  CHECK(backing_store->IsShared());
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
  Local<v8::SharedArrayBuffer> ab =
      v8::SharedArrayBuffer::New(isolate, backing_store);
  CHECK_EQ(backing_store.get(), ab->GetBackingStore().get());
}

static void* backing_store_custom_data = nullptr;
static size_t backing_store_custom_length = 0;
static bool backing_store_custom_called = false;
const intptr_t backing_store_custom_deleter_data = 1234567;

static void BackingStoreCustomDeleter(void* data, size_t length,
                                      void* deleter_data) {
  CHECK(!backing_store_custom_called);
  CHECK_EQ(backing_store_custom_data, data);
  CHECK_EQ(backing_store_custom_length, length);
  CHECK_EQ(backing_store_custom_deleter_data,
           reinterpret_cast<intptr_t>(deleter_data));
  free(data);
  backing_store_custom_called = true;
}

TEST(ArrayBuffer_NewBackingStore_CustomDeleter) {
  {
    // Create and destroy a backing store.
    backing_store_custom_called = false;
    backing_store_custom_data = malloc(100);
    backing_store_custom_length = 100;
    v8::ArrayBuffer::NewBackingStore(
        backing_store_custom_data, backing_store_custom_length,
        BackingStoreCustomDeleter,
        reinterpret_cast<void*>(backing_store_custom_deleter_data));
  }
  CHECK(backing_store_custom_called);
}

TEST(SharedArrayBuffer_NewBackingStore_CustomDeleter) {
  {
    // Create and destroy a backing store.
    backing_store_custom_called = false;
    backing_store_custom_data = malloc(100);
    backing_store_custom_length = 100;
    v8::SharedArrayBuffer::NewBackingStore(
        backing_store_custom_data, backing_store_custom_length,
        BackingStoreCustomDeleter,
        reinterpret_cast<void*>(backing_store_custom_deleter_data));
  }
  CHECK(backing_store_custom_called);
}
638

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
TEST(ArrayBuffer_NewBackingStore_EmptyDeleter) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  char static_buffer[100];
  std::unique_ptr<v8::BackingStore> backing_store =
      v8::ArrayBuffer::NewBackingStore(static_buffer, sizeof(static_buffer),
                                       v8::BackingStore::EmptyDeleter, nullptr);
  uint64_t external_memory_before =
      isolate->AdjustAmountOfExternalAllocatedMemory(0);
  v8::ArrayBuffer::New(isolate, std::move(backing_store));
  uint64_t external_memory_after =
      isolate->AdjustAmountOfExternalAllocatedMemory(0);
  // The ArrayBuffer constructor does not increase the external memory counter.
  // The counter may decrease however if the allocation triggers GC.
  CHECK_GE(external_memory_before, external_memory_after);
}

TEST(SharedArrayBuffer_NewBackingStore_EmptyDeleter) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  char static_buffer[100];
  std::unique_ptr<v8::BackingStore> backing_store =
      v8::SharedArrayBuffer::NewBackingStore(
          static_buffer, sizeof(static_buffer), v8::BackingStore::EmptyDeleter,
          nullptr);
  uint64_t external_memory_before =
      isolate->AdjustAmountOfExternalAllocatedMemory(0);
  v8::SharedArrayBuffer::New(isolate, std::move(backing_store));
  uint64_t external_memory_after =
      isolate->AdjustAmountOfExternalAllocatedMemory(0);
  // The SharedArrayBuffer constructor does not increase the external memory
  // counter. The counter may decrease however if the allocation triggers GC.
  CHECK_GE(external_memory_before, external_memory_after);
}

676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
THREADED_TEST(BackingStore_NotShared) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, 8);
  CHECK(!ab->GetBackingStore()->IsShared());
  CHECK(!v8::ArrayBuffer::NewBackingStore(isolate, 8)->IsShared());
  backing_store_custom_called = false;
  backing_store_custom_data = malloc(100);
  backing_store_custom_length = 100;
  CHECK(!v8::ArrayBuffer::NewBackingStore(
             backing_store_custom_data, backing_store_custom_length,
             BackingStoreCustomDeleter,
             reinterpret_cast<void*>(backing_store_custom_deleter_data))
             ->IsShared());
}

THREADED_TEST(BackingStore_Shared) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  Local<v8::SharedArrayBuffer> ab = v8::SharedArrayBuffer::New(isolate, 8);
  CHECK(ab->GetBackingStore()->IsShared());
  CHECK(v8::SharedArrayBuffer::NewBackingStore(isolate, 8)->IsShared());
  backing_store_custom_called = false;
  backing_store_custom_data = malloc(100);
  backing_store_custom_length = 100;
  CHECK(v8::SharedArrayBuffer::NewBackingStore(
            backing_store_custom_data, backing_store_custom_length,
            BackingStoreCustomDeleter,
            reinterpret_cast<void*>(backing_store_custom_deleter_data))
            ->IsShared());
}
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800

class DummyAllocator final : public v8::ArrayBuffer::Allocator {
 public:
  DummyAllocator() : allocator_(NewDefaultAllocator()) {}

  ~DummyAllocator() override { CHECK_EQ(allocation_count(), 0); }

  void* Allocate(size_t length) override {
    allocation_count_++;
    return allocator_->Allocate(length);
  }
  void* AllocateUninitialized(size_t length) override {
    allocation_count_++;
    return allocator_->AllocateUninitialized(length);
  }
  void Free(void* data, size_t length) override {
    allocation_count_--;
    allocator_->Free(data, length);
  }

  uint64_t allocation_count() const { return allocation_count_; }

 private:
  std::unique_ptr<v8::ArrayBuffer::Allocator> allocator_;
  uint64_t allocation_count_ = 0;
};

TEST(BackingStore_HoldAllocatorAlive_UntilIsolateShutdown) {
  std::shared_ptr<DummyAllocator> allocator =
      std::make_shared<DummyAllocator>();
  std::weak_ptr<DummyAllocator> allocator_weak(allocator);

  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator_shared = allocator;
  v8::Isolate* isolate = v8::Isolate::New(create_params);
  isolate->Enter();

  allocator.reset();
  create_params.array_buffer_allocator_shared.reset();
  CHECK(!allocator_weak.expired());
  CHECK_EQ(allocator_weak.lock()->allocation_count(), 0);

  {
    // Create an ArrayBuffer and do not garbage collect it. This should make
    // the allocator be released automatically once the Isolate is disposed.
    v8::HandleScope handle_scope(isolate);
    v8::Context::Scope context_scope(Context::New(isolate));
    v8::ArrayBuffer::New(isolate, 8);

    // This should be inside the HandleScope, so that we can be sure that
    // the allocation is not garbage collected yet.
    CHECK(!allocator_weak.expired());
    CHECK_EQ(allocator_weak.lock()->allocation_count(), 1);
  }

  isolate->Exit();
  isolate->Dispose();
  CHECK(allocator_weak.expired());
}

TEST(BackingStore_HoldAllocatorAlive_AfterIsolateShutdown) {
  std::shared_ptr<DummyAllocator> allocator =
      std::make_shared<DummyAllocator>();
  std::weak_ptr<DummyAllocator> allocator_weak(allocator);

  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator_shared = allocator;
  v8::Isolate* isolate = v8::Isolate::New(create_params);
  isolate->Enter();

  allocator.reset();
  create_params.array_buffer_allocator_shared.reset();
  CHECK(!allocator_weak.expired());
  CHECK_EQ(allocator_weak.lock()->allocation_count(), 0);

  std::shared_ptr<v8::BackingStore> backing_store;
  {
    // Create an ArrayBuffer and do not garbage collect it. This should make
    // the allocator be released automatically once the Isolate is disposed.
    v8::HandleScope handle_scope(isolate);
    v8::Context::Scope context_scope(Context::New(isolate));
    v8::Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, 8);
    backing_store = ab->GetBackingStore();
  }

  isolate->Exit();
  isolate->Dispose();
  CHECK(!allocator_weak.expired());
  CHECK_EQ(allocator_weak.lock()->allocation_count(), 1);
  backing_store.reset();
  CHECK(allocator_weak.expired());
}
801

802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
class NullptrAllocator final : public v8::ArrayBuffer::Allocator {
 public:
  void* Allocate(size_t length) override {
    CHECK_EQ(length, 0);
    return nullptr;
  }
  void* AllocateUninitialized(size_t length) override {
    CHECK_EQ(length, 0);
    return nullptr;
  }
  void Free(void* data, size_t length) override { CHECK_EQ(data, nullptr); }
};

TEST(BackingStore_ReleaseAllocator_NullptrBackingStore) {
  std::shared_ptr<NullptrAllocator> allocator =
      std::make_shared<NullptrAllocator>();
  std::weak_ptr<NullptrAllocator> allocator_weak(allocator);

  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator_shared = allocator;
  v8::Isolate* isolate = v8::Isolate::New(create_params);
  isolate->Enter();

  allocator.reset();
  create_params.array_buffer_allocator_shared.reset();
  CHECK(!allocator_weak.expired());

  {
    std::shared_ptr<v8::BackingStore> backing_store =
        v8::ArrayBuffer::NewBackingStore(isolate, 0);
    // This should release a reference to the allocator, even though the
    // buffer is empty/nullptr.
    backing_store.reset();
  }

  isolate->Exit();
  isolate->Dispose();
  CHECK(allocator_weak.expired());
}

842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
TEST(BackingStore_ReallocateExpand) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  std::unique_ptr<v8::BackingStore> backing_store =
      v8::ArrayBuffer::NewBackingStore(isolate, 10);
  {
    uint8_t* data = reinterpret_cast<uint8_t*>(
        reinterpret_cast<uintptr_t>(backing_store->Data()));
    for (uint8_t i = 0; i < 10; i++) {
      data[i] = i;
    }
  }
  std::unique_ptr<v8::BackingStore> new_backing_store =
      v8::BackingStore::Reallocate(isolate, std::move(backing_store), 20);
  CHECK_EQ(new_backing_store->ByteLength(), 20);
  CHECK(!new_backing_store->IsShared());
  {
    uint8_t* data = reinterpret_cast<uint8_t*>(
        reinterpret_cast<uintptr_t>(new_backing_store->Data()));
    for (uint8_t i = 0; i < 10; i++) {
      CHECK_EQ(data[i], i);
    }
    for (uint8_t i = 10; i < 20; i++) {
      CHECK_EQ(data[i], 0);
    }
  }
}

TEST(BackingStore_ReallocateShrink) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  std::unique_ptr<v8::BackingStore> backing_store =
      v8::ArrayBuffer::NewBackingStore(isolate, 20);
  {
    uint8_t* data = reinterpret_cast<uint8_t*>(backing_store->Data());
    for (uint8_t i = 0; i < 20; i++) {
      data[i] = i;
    }
  }
  std::unique_ptr<v8::BackingStore> new_backing_store =
      v8::BackingStore::Reallocate(isolate, std::move(backing_store), 10);
  CHECK_EQ(new_backing_store->ByteLength(), 10);
  CHECK(!new_backing_store->IsShared());
  {
    uint8_t* data = reinterpret_cast<uint8_t*>(new_backing_store->Data());
    for (uint8_t i = 0; i < 10; i++) {
      CHECK_EQ(data[i], i);
    }
  }
}

TEST(BackingStore_ReallocateNotShared) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  std::unique_ptr<v8::BackingStore> backing_store =
      v8::ArrayBuffer::NewBackingStore(isolate, 20);
  std::unique_ptr<v8::BackingStore> new_backing_store =
      v8::BackingStore::Reallocate(isolate, std::move(backing_store), 10);
  CHECK(!new_backing_store->IsShared());
}

TEST(BackingStore_ReallocateShared) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  std::unique_ptr<v8::BackingStore> backing_store =
      v8::SharedArrayBuffer::NewBackingStore(isolate, 20);
  std::unique_ptr<v8::BackingStore> new_backing_store =
      v8::BackingStore::Reallocate(isolate, std::move(backing_store), 10);
  CHECK(new_backing_store->IsShared());
}