test-heap.cc 86.2 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6

#include <stdlib.h>

#include "v8.h"

7
#include "compilation-cache.h"
8 9 10 11
#include "execution.h"
#include "factory.h"
#include "macro-assembler.h"
#include "global-handles.h"
12
#include "stub-cache.h"
13 14 15 16 17 18 19 20 21 22 23 24 25
#include "cctest.h"

using namespace v8::internal;

static v8::Persistent<v8::Context> env;

static void InitializeVM() {
  if (env.IsEmpty()) env = v8::Context::New();
  v8::HandleScope scope;
  env->Enter();
}


26 27 28
// Go through all incremental marking steps in one swoop.
static void SimulateIncrementalMarking() {
  IncrementalMarking* marking = HEAP->incremental_marking();
29 30 31 32
  CHECK(marking->IsMarking() || marking->IsStopped());
  if (marking->IsStopped()) {
    marking->Start();
  }
33 34 35 36 37 38 39 40
  CHECK(marking->IsMarking());
  while (!marking->IsComplete()) {
    marking->Step(MB, IncrementalMarking::NO_GC_VIA_STACK_GUARD);
  }
  CHECK(marking->IsComplete());
}


41 42 43
static void CheckMap(Map* map, int type, int instance_size) {
  CHECK(map->IsHeapObject());
#ifdef DEBUG
44
  CHECK(HEAP->Contains(map));
45
#endif
46
  CHECK_EQ(HEAP->meta_map(), map->map());
47 48 49 50 51 52 53
  CHECK_EQ(type, map->instance_type());
  CHECK_EQ(instance_size, map->instance_size());
}


TEST(HeapMaps) {
  InitializeVM();
54 55 56 57
  CheckMap(HEAP->meta_map(), MAP_TYPE, Map::kSize);
  CheckMap(HEAP->heap_number_map(), HEAP_NUMBER_TYPE, HeapNumber::kSize);
  CheckMap(HEAP->fixed_array_map(), FIXED_ARRAY_TYPE, kVariableSizeSentinel);
  CheckMap(HEAP->string_map(), STRING_TYPE, kVariableSizeSentinel);
58 59 60 61 62 63 64
}


static void CheckOddball(Object* obj, const char* string) {
  CHECK(obj->IsOddball());
  bool exc;
  Object* print_string = *Execution::ToString(Handle<Object>(obj), &exc);
65
  CHECK(String::cast(print_string)->IsUtf8EqualTo(CStrVector(string)));
66 67 68 69 70 71 72
}


static void CheckSmi(int value, const char* string) {
  bool exc;
  Object* print_string =
      *Execution::ToString(Handle<Object>(Smi::FromInt(value)), &exc);
73
  CHECK(String::cast(print_string)->IsUtf8EqualTo(CStrVector(string)));
74 75 76 77
}


static void CheckNumber(double value, const char* string) {
78
  Object* obj = HEAP->NumberFromDouble(value)->ToObjectChecked();
79 80 81
  CHECK(obj->IsNumber());
  bool exc;
  Object* print_string = *Execution::ToString(Handle<Object>(obj), &exc);
82
  CHECK(String::cast(print_string)->IsUtf8EqualTo(CStrVector(string)));
83 84 85 86 87 88 89
}


static void CheckFindCodeObject() {
  // Test FindCodeObject
#define __ assm.

90
  Assembler assm(Isolate::Current(), NULL, 0);
91 92 93 94 95

  __ nop();  // supported on all architectures

  CodeDesc desc;
  assm.GetCode(&desc);
96
  Object* code = HEAP->CreateCode(
97 98
      desc,
      Code::ComputeFlags(Code::STUB),
99
      Handle<Object>(HEAP->undefined_value()))->ToObjectChecked();
100 101 102 103 104 105
  CHECK(code->IsCode());

  HeapObject* obj = HeapObject::cast(code);
  Address obj_addr = obj->address();

  for (int i = 0; i < obj->Size(); i += kPointerSize) {
106
    Object* found = HEAP->FindCodeObject(obj_addr + i);
107 108 109
    CHECK_EQ(code, found);
  }

110
  Object* copy = HEAP->CreateCode(
111 112
      desc,
      Code::ComputeFlags(Code::STUB),
113
      Handle<Object>(HEAP->undefined_value()))->ToObjectChecked();
114 115
  CHECK(copy->IsCode());
  HeapObject* obj_copy = HeapObject::cast(copy);
116
  Object* not_right = HEAP->FindCodeObject(obj_copy->address() +
117 118 119 120 121 122 123 124 125
                                           obj_copy->Size() / 2);
  CHECK(not_right != code);
}


TEST(HeapObjects) {
  InitializeVM();

  v8::HandleScope sc;
126
  Object* value = HEAP->NumberFromDouble(1.000123)->ToObjectChecked();
127 128 129 130
  CHECK(value->IsHeapNumber());
  CHECK(value->IsNumber());
  CHECK_EQ(1.000123, value->Number());

131
  value = HEAP->NumberFromDouble(1.0)->ToObjectChecked();
132 133 134 135
  CHECK(value->IsSmi());
  CHECK(value->IsNumber());
  CHECK_EQ(1.0, value->Number());

136
  value = HEAP->NumberFromInt32(1024)->ToObjectChecked();
137 138 139 140
  CHECK(value->IsSmi());
  CHECK(value->IsNumber());
  CHECK_EQ(1024.0, value->Number());

141
  value = HEAP->NumberFromInt32(Smi::kMinValue)->ToObjectChecked();
142 143 144 145
  CHECK(value->IsSmi());
  CHECK(value->IsNumber());
  CHECK_EQ(Smi::kMinValue, Smi::cast(value)->value());

146
  value = HEAP->NumberFromInt32(Smi::kMaxValue)->ToObjectChecked();
147 148 149 150
  CHECK(value->IsSmi());
  CHECK(value->IsNumber());
  CHECK_EQ(Smi::kMaxValue, Smi::cast(value)->value());

lrn@chromium.org's avatar
lrn@chromium.org committed
151
#ifndef V8_TARGET_ARCH_X64
152
  // TODO(lrn): We need a NumberFromIntptr function in order to test this.
153
  value = HEAP->NumberFromInt32(Smi::kMinValue - 1)->ToObjectChecked();
154 155 156
  CHECK(value->IsHeapNumber());
  CHECK(value->IsNumber());
  CHECK_EQ(static_cast<double>(Smi::kMinValue - 1), value->Number());
157
#endif
158

159
  MaybeObject* maybe_value =
160
      HEAP->NumberFromUint32(static_cast<uint32_t>(Smi::kMaxValue) + 1);
161
  value = maybe_value->ToObjectChecked();
162 163
  CHECK(value->IsHeapNumber());
  CHECK(value->IsNumber());
164 165
  CHECK_EQ(static_cast<double>(static_cast<uint32_t>(Smi::kMaxValue) + 1),
           value->Number());
166

167 168 169 170 171 172 173
  maybe_value = HEAP->NumberFromUint32(static_cast<uint32_t>(1) << 31);
  value = maybe_value->ToObjectChecked();
  CHECK(value->IsHeapNumber());
  CHECK(value->IsNumber());
  CHECK_EQ(static_cast<double>(static_cast<uint32_t>(1) << 31),
           value->Number());

174
  // nan oddball checks
175 176
  CHECK(HEAP->nan_value()->IsNumber());
  CHECK(isnan(HEAP->nan_value()->Number()));
177

178
  Handle<String> s = FACTORY->NewStringFromAscii(CStrVector("fisk hest "));
179 180
  CHECK(s->IsString());
  CHECK_EQ(10, s->length());
181

182 183
  String* object_symbol = String::cast(HEAP->Object_symbol());
  CHECK(
184 185
      Isolate::Current()->context()->global_object()->HasLocalProperty(
          object_symbol));
186 187

  // Check ToString for oddballs
188 189 190 191
  CheckOddball(HEAP->true_value(), "true");
  CheckOddball(HEAP->false_value(), "false");
  CheckOddball(HEAP->null_value(), "null");
  CheckOddball(HEAP->undefined_value(), "undefined");
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

  // Check ToString for Smis
  CheckSmi(0, "0");
  CheckSmi(42, "42");
  CheckSmi(-42, "-42");

  // Check ToString for Numbers
  CheckNumber(1.1, "1.1");

  CheckFindCodeObject();
}


TEST(Tagging) {
  InitializeVM();
207
  int request = 24;
208
  CHECK_EQ(request, static_cast<int>(OBJECT_POINTER_ALIGN(request)));
209
  CHECK(Smi::FromInt(42)->IsSmi());
210
  CHECK(Failure::RetryAfterGC(NEW_SPACE)->IsFailure());
211
  CHECK_EQ(NEW_SPACE,
212
           Failure::RetryAfterGC(NEW_SPACE)->allocation_space());
213
  CHECK_EQ(OLD_POINTER_SPACE,
214
           Failure::RetryAfterGC(OLD_POINTER_SPACE)->allocation_space());
215 216 217 218 219 220 221 222 223 224
  CHECK(Failure::Exception()->IsFailure());
  CHECK(Smi::FromInt(Smi::kMinValue)->IsSmi());
  CHECK(Smi::FromInt(Smi::kMaxValue)->IsSmi());
}


TEST(GarbageCollection) {
  InitializeVM();

  v8::HandleScope sc;
225
  // Check GC.
226
  HEAP->CollectGarbage(NEW_SPACE);
227

228 229 230 231
  Handle<String> name = FACTORY->LookupUtf8Symbol("theFunction");
  Handle<String> prop_name = FACTORY->LookupUtf8Symbol("theSlot");
  Handle<String> prop_namex = FACTORY->LookupUtf8Symbol("theSlotx");
  Handle<String> obj_name = FACTORY->LookupUtf8Symbol("theObject");
232 233 234 235 236

  {
    v8::HandleScope inner_scope;
    // Allocate a function and keep it in global object's property.
    Handle<JSFunction> function =
237
        FACTORY->NewFunction(name, FACTORY->undefined_value());
238
    Handle<Map> initial_map =
239
        FACTORY->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
240
    function->set_initial_map(*initial_map);
241
    Isolate::Current()->context()->global_object()->SetProperty(
242
        *name, *function, NONE, kNonStrictMode)->ToObjectChecked();
243
    // Allocate an object.  Unrooted after leaving the scope.
244
    Handle<JSObject> obj = FACTORY->NewJSObject(function);
245 246 247 248
    obj->SetProperty(
        *prop_name, Smi::FromInt(23), NONE, kNonStrictMode)->ToObjectChecked();
    obj->SetProperty(
        *prop_namex, Smi::FromInt(24), NONE, kNonStrictMode)->ToObjectChecked();
249 250 251 252

    CHECK_EQ(Smi::FromInt(23), obj->GetProperty(*prop_name));
    CHECK_EQ(Smi::FromInt(24), obj->GetProperty(*prop_namex));
  }
253

254
  HEAP->CollectGarbage(NEW_SPACE);
255

256
  // Function should be alive.
257 258
  CHECK(Isolate::Current()->context()->global_object()->
        HasLocalProperty(*name));
259
  // Check function is retained.
260
  Object* func_value = Isolate::Current()->context()->global_object()->
261
      GetProperty(*name)->ToObjectChecked();
262
  CHECK(func_value->IsJSFunction());
263 264 265 266 267
  Handle<JSFunction> function(JSFunction::cast(func_value));

  {
    HandleScope inner_scope;
    // Allocate another object, make it reachable from global.
268
    Handle<JSObject> obj = FACTORY->NewJSObject(function);
269
    Isolate::Current()->context()->global_object()->SetProperty(
270 271 272
        *obj_name, *obj, NONE, kNonStrictMode)->ToObjectChecked();
    obj->SetProperty(
        *prop_name, Smi::FromInt(23), NONE, kNonStrictMode)->ToObjectChecked();
273
  }
274

275
  // After gc, it should survive.
276
  HEAP->CollectGarbage(NEW_SPACE);
277

278 279 280
  CHECK(Isolate::Current()->context()->global_object()->
        HasLocalProperty(*obj_name));
  CHECK(Isolate::Current()->context()->global_object()->
281
        GetProperty(*obj_name)->ToObjectChecked()->IsJSObject());
282
  Object* obj = Isolate::Current()->context()->global_object()->
283
      GetProperty(*obj_name)->ToObjectChecked();
284 285
  JSObject* js_obj = JSObject::cast(obj);
  CHECK_EQ(Smi::FromInt(23), js_obj->GetProperty(*prop_name));
286 287 288 289
}


static void VerifyStringAllocation(const char* string) {
290
  v8::HandleScope scope;
291
  Handle<String> s = FACTORY->NewStringFromUtf8(CStrVector(string));
292
  CHECK_EQ(StrLength(string), s->length());
293
  for (int index = 0; index < s->length(); index++) {
294 295
    CHECK_EQ(static_cast<uint16_t>(string[index]), s->Get(index));
  }
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
}


TEST(String) {
  InitializeVM();

  VerifyStringAllocation("a");
  VerifyStringAllocation("ab");
  VerifyStringAllocation("abc");
  VerifyStringAllocation("abcd");
  VerifyStringAllocation("fiskerdrengen er paa havet");
}


TEST(LocalHandles) {
  InitializeVM();

  v8::HandleScope scope;
  const char* name = "Kasper the spunky";
315
  Handle<String> string = FACTORY->NewStringFromAscii(CStrVector(name));
316
  CHECK_EQ(StrLength(name), string->length());
317 318 319 320 321
}


TEST(GlobalHandles) {
  InitializeVM();
322
  GlobalHandles* global_handles = Isolate::Current()->global_handles();
323

324 325 326 327 328 329 330
  Handle<Object> h1;
  Handle<Object> h2;
  Handle<Object> h3;
  Handle<Object> h4;

  {
    HandleScope scope;
331

332 333
    Handle<Object> i = FACTORY->NewStringFromAscii(CStrVector("fisk"));
    Handle<Object> u = FACTORY->NewNumber(1.12344);
334

335 336 337 338
    h1 = global_handles->Create(*i);
    h2 = global_handles->Create(*u);
    h3 = global_handles->Create(*i);
    h4 = global_handles->Create(*u);
339
  }
340 341

  // after gc, it should survive
342
  HEAP->CollectGarbage(NEW_SPACE);
343 344 345 346 347 348 349

  CHECK((*h1)->IsString());
  CHECK((*h2)->IsHeapNumber());
  CHECK((*h3)->IsString());
  CHECK((*h4)->IsHeapNumber());

  CHECK_EQ(*h3, *h1);
350 351
  global_handles->Destroy(h1.location());
  global_handles->Destroy(h3.location());
352 353

  CHECK_EQ(*h4, *h2);
354 355
  global_handles->Destroy(h2.location());
  global_handles->Destroy(h4.location());
356 357 358 359 360
}


static bool WeakPointerCleared = false;

361
static void TestWeakGlobalHandleCallback(v8::Persistent<v8::Value> handle,
362
                                         void* id) {
363
  if (1234 == reinterpret_cast<intptr_t>(id)) WeakPointerCleared = true;
364
  handle.Dispose();
365 366 367 368 369
}


TEST(WeakGlobalHandlesScavenge) {
  InitializeVM();
370
  GlobalHandles* global_handles = Isolate::Current()->global_handles();
371 372 373

  WeakPointerCleared = false;

374 375 376 377 378
  Handle<Object> h1;
  Handle<Object> h2;

  {
    HandleScope scope;
379

380 381
    Handle<Object> i = FACTORY->NewStringFromAscii(CStrVector("fisk"));
    Handle<Object> u = FACTORY->NewNumber(1.12344);
382

383 384
    h1 = global_handles->Create(*i);
    h2 = global_handles->Create(*u);
385
  }
386

387 388 389
  global_handles->MakeWeak(h2.location(),
                           reinterpret_cast<void*>(1234),
                           &TestWeakGlobalHandleCallback);
390 391

  // Scavenge treats weak pointers as normal roots.
392
  HEAP->PerformScavenge();
393 394 395 396 397

  CHECK((*h1)->IsString());
  CHECK((*h2)->IsHeapNumber());

  CHECK(!WeakPointerCleared);
398 399
  CHECK(!global_handles->IsNearDeath(h2.location()));
  CHECK(!global_handles->IsNearDeath(h1.location()));
400

401 402
  global_handles->Destroy(h1.location());
  global_handles->Destroy(h2.location());
403 404 405 406 407
}


TEST(WeakGlobalHandlesMark) {
  InitializeVM();
408
  GlobalHandles* global_handles = Isolate::Current()->global_handles();
409 410 411

  WeakPointerCleared = false;

412 413 414 415 416
  Handle<Object> h1;
  Handle<Object> h2;

  {
    HandleScope scope;
417

418 419
    Handle<Object> i = FACTORY->NewStringFromAscii(CStrVector("fisk"));
    Handle<Object> u = FACTORY->NewNumber(1.12344);
420

421 422
    h1 = global_handles->Create(*i);
    h2 = global_handles->Create(*u);
423
  }
424

425
  // Make sure the objects are promoted.
426 427
  HEAP->CollectGarbage(OLD_POINTER_SPACE);
  HEAP->CollectGarbage(NEW_SPACE);
428
  CHECK(!HEAP->InNewSpace(*h1) && !HEAP->InNewSpace(*h2));
429

430 431 432
  global_handles->MakeWeak(h2.location(),
                           reinterpret_cast<void*>(1234),
                           &TestWeakGlobalHandleCallback);
433 434 435
  CHECK(!GlobalHandles::IsNearDeath(h1.location()));
  CHECK(!GlobalHandles::IsNearDeath(h2.location()));

436 437
  // Incremental marking potentially marked handles before they turned weak.
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
438 439 440 441 442 443

  CHECK((*h1)->IsString());

  CHECK(WeakPointerCleared);
  CHECK(!GlobalHandles::IsNearDeath(h1.location()));

444
  global_handles->Destroy(h1.location());
445 446
}

447

448 449
TEST(DeleteWeakGlobalHandle) {
  InitializeVM();
450
  GlobalHandles* global_handles = Isolate::Current()->global_handles();
451 452 453

  WeakPointerCleared = false;

454 455 456 457 458
  Handle<Object> h;

  {
    HandleScope scope;

459 460
    Handle<Object> i = FACTORY->NewStringFromAscii(CStrVector("fisk"));
    h = global_handles->Create(*i);
461
  }
462

463 464 465
  global_handles->MakeWeak(h.location(),
                           reinterpret_cast<void*>(1234),
                           &TestWeakGlobalHandleCallback);
466 467

  // Scanvenge does not recognize weak reference.
468
  HEAP->PerformScavenge();
469 470 471 472

  CHECK(!WeakPointerCleared);

  // Mark-compact treats weak reference properly.
473
  HEAP->CollectGarbage(OLD_POINTER_SPACE);
474 475 476 477

  CHECK(WeakPointerCleared);
}

478

479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 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 533 534 535 536 537 538 539 540 541 542 543 544
static const char* not_so_random_string_table[] = {
  "abstract",
  "boolean",
  "break",
  "byte",
  "case",
  "catch",
  "char",
  "class",
  "const",
  "continue",
  "debugger",
  "default",
  "delete",
  "do",
  "double",
  "else",
  "enum",
  "export",
  "extends",
  "false",
  "final",
  "finally",
  "float",
  "for",
  "function",
  "goto",
  "if",
  "implements",
  "import",
  "in",
  "instanceof",
  "int",
  "interface",
  "long",
  "native",
  "new",
  "null",
  "package",
  "private",
  "protected",
  "public",
  "return",
  "short",
  "static",
  "super",
  "switch",
  "synchronized",
  "this",
  "throw",
  "throws",
  "transient",
  "true",
  "try",
  "typeof",
  "var",
  "void",
  "volatile",
  "while",
  "with",
  0
};


static void CheckSymbols(const char** strings) {
  for (const char* string = *strings; *strings != 0; string = *strings++) {
545
    Object* a;
546 547
    MaybeObject* maybe_a = HEAP->LookupUtf8Symbol(string);
    // LookupUtf8Symbol may return a failure if a GC is needed.
548
    if (!maybe_a->ToObject(&a)) continue;
549
    CHECK(a->IsSymbol());
550
    Object* b;
551
    MaybeObject* maybe_b = HEAP->LookupUtf8Symbol(string);
552
    if (!maybe_b->ToObject(&b)) continue;
553
    CHECK_EQ(b, a);
554
    CHECK(String::cast(b)->IsUtf8EqualTo(CStrVector(string)));
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
  }
}


TEST(SymbolTable) {
  InitializeVM();

  CheckSymbols(not_so_random_string_table);
  CheckSymbols(not_so_random_string_table);
}


TEST(FunctionAllocation) {
  InitializeVM();

  v8::HandleScope sc;
571
  Handle<String> name = FACTORY->LookupUtf8Symbol("theFunction");
572
  Handle<JSFunction> function =
573
      FACTORY->NewFunction(name, FACTORY->undefined_value());
574
  Handle<Map> initial_map =
575
      FACTORY->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
576 577
  function->set_initial_map(*initial_map);

578
  Handle<String> prop_name = FACTORY->LookupUtf8Symbol("theSlot");
579
  Handle<JSObject> obj = FACTORY->NewJSObject(function);
580 581
  obj->SetProperty(
      *prop_name, Smi::FromInt(23), NONE, kNonStrictMode)->ToObjectChecked();
582
  CHECK_EQ(Smi::FromInt(23), obj->GetProperty(*prop_name));
583
  // Check that we can add properties to function objects.
584 585
  function->SetProperty(
      *prop_name, Smi::FromInt(24), NONE, kNonStrictMode)->ToObjectChecked();
586
  CHECK_EQ(Smi::FromInt(24), function->GetProperty(*prop_name));
587 588 589 590 591 592 593
}


TEST(ObjectProperties) {
  InitializeVM();

  v8::HandleScope sc;
594
  String* object_symbol = String::cast(HEAP->Object_symbol());
595
  Object* raw_object = Isolate::Current()->context()->global_object()->
596
      GetProperty(object_symbol)->ToObjectChecked();
597
  JSFunction* object_function = JSFunction::cast(raw_object);
598
  Handle<JSFunction> constructor(object_function);
599
  Handle<JSObject> obj = FACTORY->NewJSObject(constructor);
600 601
  Handle<String> first = FACTORY->LookupUtf8Symbol("first");
  Handle<String> second = FACTORY->LookupUtf8Symbol("second");
602 603

  // check for empty
604
  CHECK(!obj->HasLocalProperty(*first));
605 606

  // add first
607 608
  obj->SetProperty(
      *first, Smi::FromInt(1), NONE, kNonStrictMode)->ToObjectChecked();
609
  CHECK(obj->HasLocalProperty(*first));
610 611

  // delete first
612 613
  CHECK(obj->DeleteProperty(*first, JSObject::NORMAL_DELETION));
  CHECK(!obj->HasLocalProperty(*first));
614 615

  // add first and then second
616 617 618 619
  obj->SetProperty(
      *first, Smi::FromInt(1), NONE, kNonStrictMode)->ToObjectChecked();
  obj->SetProperty(
      *second, Smi::FromInt(2), NONE, kNonStrictMode)->ToObjectChecked();
620 621
  CHECK(obj->HasLocalProperty(*first));
  CHECK(obj->HasLocalProperty(*second));
622 623

  // delete first and then second
624 625 626 627 628
  CHECK(obj->DeleteProperty(*first, JSObject::NORMAL_DELETION));
  CHECK(obj->HasLocalProperty(*second));
  CHECK(obj->DeleteProperty(*second, JSObject::NORMAL_DELETION));
  CHECK(!obj->HasLocalProperty(*first));
  CHECK(!obj->HasLocalProperty(*second));
629 630

  // add first and then second
631 632 633 634
  obj->SetProperty(
      *first, Smi::FromInt(1), NONE, kNonStrictMode)->ToObjectChecked();
  obj->SetProperty(
      *second, Smi::FromInt(2), NONE, kNonStrictMode)->ToObjectChecked();
635 636
  CHECK(obj->HasLocalProperty(*first));
  CHECK(obj->HasLocalProperty(*second));
637 638

  // delete second and then first
639 640 641 642 643
  CHECK(obj->DeleteProperty(*second, JSObject::NORMAL_DELETION));
  CHECK(obj->HasLocalProperty(*first));
  CHECK(obj->DeleteProperty(*first, JSObject::NORMAL_DELETION));
  CHECK(!obj->HasLocalProperty(*first));
  CHECK(!obj->HasLocalProperty(*second));
644 645

  // check string and symbol match
646
  const char* string1 = "fisk";
647
  Handle<String> s1 = FACTORY->NewStringFromAscii(CStrVector(string1));
648 649
  obj->SetProperty(
      *s1, Smi::FromInt(1), NONE, kNonStrictMode)->ToObjectChecked();
650
  Handle<String> s1_symbol = FACTORY->LookupUtf8Symbol(string1);
651
  CHECK(obj->HasLocalProperty(*s1_symbol));
652 653

  // check symbol and string match
654
  const char* string2 = "fugl";
655
  Handle<String> s2_symbol = FACTORY->LookupUtf8Symbol(string2);
656 657
  obj->SetProperty(
      *s2_symbol, Smi::FromInt(1), NONE, kNonStrictMode)->ToObjectChecked();
658
  Handle<String> s2 = FACTORY->NewStringFromAscii(CStrVector(string2));
659
  CHECK(obj->HasLocalProperty(*s2));
660 661 662 663 664 665 666
}


TEST(JSObjectMaps) {
  InitializeVM();

  v8::HandleScope sc;
667
  Handle<String> name = FACTORY->LookupUtf8Symbol("theFunction");
668
  Handle<JSFunction> function =
669
      FACTORY->NewFunction(name, FACTORY->undefined_value());
670
  Handle<Map> initial_map =
671
      FACTORY->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
672 673
  function->set_initial_map(*initial_map);

674
  Handle<String> prop_name = FACTORY->LookupUtf8Symbol("theSlot");
675
  Handle<JSObject> obj = FACTORY->NewJSObject(function);
676 677

  // Set a propery
678 679
  obj->SetProperty(
      *prop_name, Smi::FromInt(23), NONE, kNonStrictMode)->ToObjectChecked();
680
  CHECK_EQ(Smi::FromInt(23), obj->GetProperty(*prop_name));
681 682

  // Check the map has changed
683
  CHECK(*initial_map != obj->map());
684 685 686 687 688 689 690
}


TEST(JSArray) {
  InitializeVM();

  v8::HandleScope sc;
691
  Handle<String> name = FACTORY->LookupUtf8Symbol("Array");
692
  Object* raw_object = Isolate::Current()->context()->global_object()->
693
      GetProperty(*name)->ToObjectChecked();
694
  Handle<JSFunction> function = Handle<JSFunction>(
695
      JSFunction::cast(raw_object));
696 697

  // Allocate the object.
698
  Handle<JSObject> object = FACTORY->NewJSObject(function);
699
  Handle<JSArray> array = Handle<JSArray>::cast(object);
700
  // We just initialized the VM, no heap allocation failure yet.
701
  array->Initialize(0)->ToObjectChecked();
702 703

  // Set array length to 0.
704
  array->SetElementsLength(Smi::FromInt(0))->ToObjectChecked();
705
  CHECK_EQ(Smi::FromInt(0), array->length());
706
  // Must be in fast mode.
707
  CHECK(array->HasFastSmiOrObjectElements());
708 709

  // array[length] = name.
710
  array->SetElement(0, *name, NONE, kNonStrictMode)->ToObjectChecked();
711
  CHECK_EQ(Smi::FromInt(1), array->length());
712
  CHECK_EQ(array->GetElement(0), *name);
713

714 715
  // Set array length with larger than smi value.
  Handle<Object> length =
716
      FACTORY->NewNumberFromUint(static_cast<uint32_t>(Smi::kMaxValue) + 1);
717
  array->SetElementsLength(*length)->ToObjectChecked();
718 719

  uint32_t int_length = 0;
720
  CHECK(length->ToArrayIndex(&int_length));
721
  CHECK_EQ(*length, array->length());
722
  CHECK(array->HasDictionaryElements());  // Must be in slow mode.
723 724

  // array[length] = name.
725
  array->SetElement(int_length, *name, NONE, kNonStrictMode)->ToObjectChecked();
726
  uint32_t new_int_length = 0;
727
  CHECK(array->length()->ToArrayIndex(&new_int_length));
728
  CHECK_EQ(static_cast<double>(int_length), new_int_length - 1);
729 730
  CHECK_EQ(array->GetElement(int_length), *name);
  CHECK_EQ(array->GetElement(0), *name);
731 732 733 734 735 736 737
}


TEST(JSObjectCopy) {
  InitializeVM();

  v8::HandleScope sc;
738
  String* object_symbol = String::cast(HEAP->Object_symbol());
739
  Object* raw_object = Isolate::Current()->context()->global_object()->
740
      GetProperty(object_symbol)->ToObjectChecked();
741
  JSFunction* object_function = JSFunction::cast(raw_object);
742
  Handle<JSFunction> constructor(object_function);
743
  Handle<JSObject> obj = FACTORY->NewJSObject(constructor);
744 745
  Handle<String> first = FACTORY->LookupUtf8Symbol("first");
  Handle<String> second = FACTORY->LookupUtf8Symbol("second");
746

747 748 749 750
  obj->SetProperty(
      *first, Smi::FromInt(1), NONE, kNonStrictMode)->ToObjectChecked();
  obj->SetProperty(
      *second, Smi::FromInt(2), NONE, kNonStrictMode)->ToObjectChecked();
751

752 753
  obj->SetElement(0, *first, NONE, kNonStrictMode)->ToObjectChecked();
  obj->SetElement(1, *second, NONE, kNonStrictMode)->ToObjectChecked();
754 755

  // Make the clone.
756 757
  Handle<JSObject> clone = Copy(obj);
  CHECK(!clone.is_identical_to(obj));
758 759 760 761

  CHECK_EQ(obj->GetElement(0), clone->GetElement(0));
  CHECK_EQ(obj->GetElement(1), clone->GetElement(1));

762 763
  CHECK_EQ(obj->GetProperty(*first), clone->GetProperty(*first));
  CHECK_EQ(obj->GetProperty(*second), clone->GetProperty(*second));
764 765

  // Flip the values.
766 767 768 769
  clone->SetProperty(
      *first, Smi::FromInt(2), NONE, kNonStrictMode)->ToObjectChecked();
  clone->SetProperty(
      *second, Smi::FromInt(1), NONE, kNonStrictMode)->ToObjectChecked();
770

771 772
  clone->SetElement(0, *second, NONE, kNonStrictMode)->ToObjectChecked();
  clone->SetElement(1, *first, NONE, kNonStrictMode)->ToObjectChecked();
773 774 775 776

  CHECK_EQ(obj->GetElement(1), clone->GetElement(0));
  CHECK_EQ(obj->GetElement(0), clone->GetElement(1));

777 778
  CHECK_EQ(obj->GetProperty(*second), clone->GetProperty(*first));
  CHECK_EQ(obj->GetProperty(*first), clone->GetProperty(*second));
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
}


TEST(StringAllocation) {
  InitializeVM();


  const unsigned char chars[] = { 0xe5, 0xa4, 0xa7 };
  for (int length = 0; length < 100; length++) {
    v8::HandleScope scope;
    char* non_ascii = NewArray<char>(3 * length + 1);
    char* ascii = NewArray<char>(length + 1);
    non_ascii[3 * length] = 0;
    ascii[length] = 0;
    for (int i = 0; i < length; i++) {
      ascii[i] = 'a';
      non_ascii[3 * i] = chars[0];
      non_ascii[3 * i + 1] = chars[1];
      non_ascii[3 * i + 2] = chars[2];
    }
    Handle<String> non_ascii_sym =
800
        FACTORY->LookupUtf8Symbol(Vector<const char>(non_ascii, 3 * length));
801 802
    CHECK_EQ(length, non_ascii_sym->length());
    Handle<String> ascii_sym =
803
        FACTORY->LookupOneByteSymbol(OneByteVector(ascii, length));
804 805
    CHECK_EQ(length, ascii_sym->length());
    Handle<String> non_ascii_str =
806
        FACTORY->NewStringFromUtf8(Vector<const char>(non_ascii, 3 * length));
807 808 809
    non_ascii_str->Hash();
    CHECK_EQ(length, non_ascii_str->length());
    Handle<String> ascii_str =
810
        FACTORY->NewStringFromUtf8(Vector<const char>(ascii, length));
811 812 813 814 815 816 817 818 819 820 821 822
    ascii_str->Hash();
    CHECK_EQ(length, ascii_str->length());
    DeleteArray(non_ascii);
    DeleteArray(ascii);
  }
}


static int ObjectsFoundInHeap(Handle<Object> objs[], int size) {
  // Count the number of objects found in the heap.
  int found_count = 0;
  HeapIterator iterator;
823
  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
    for (int i = 0; i < size; i++) {
      if (*objs[i] == obj) {
        found_count++;
      }
    }
  }
  return found_count;
}


TEST(Iteration) {
  InitializeVM();
  v8::HandleScope scope;

  // Array of objects to scan haep for.
  const int objs_count = 6;
  Handle<Object> objs[objs_count];
  int next_objs_index = 0;

843
  // Allocate a JS array to OLD_POINTER_SPACE and NEW_SPACE
844
  objs[next_objs_index++] = FACTORY->NewJSArray(10);
845 846 847
  objs[next_objs_index++] = FACTORY->NewJSArray(10,
                                                FAST_HOLEY_ELEMENTS,
                                                TENURED);
848

849
  // Allocate a small string to OLD_DATA_SPACE and NEW_SPACE
850
  objs[next_objs_index++] =
851
      FACTORY->NewStringFromAscii(CStrVector("abcdefghij"));
852
  objs[next_objs_index++] =
853
      FACTORY->NewStringFromAscii(CStrVector("abcdefghij"), TENURED);
854 855

  // Allocate a large string (for large object space).
856
  int large_size = Page::kMaxNonCodeHeapObjectSize + 1;
857 858 859 860
  char* str = new char[large_size];
  for (int i = 0; i < large_size - 1; ++i) str[i] = 'a';
  str[large_size - 1] = '\0';
  objs[next_objs_index++] =
861
      FACTORY->NewStringFromAscii(CStrVector(str), TENURED);
862 863 864 865 866 867 868 869
  delete[] str;

  // Add a Map object to look for.
  objs[next_objs_index++] = Handle<Map>(HeapObject::cast(*objs[0])->map());

  CHECK_EQ(objs_count, next_objs_index);
  CHECK_EQ(objs_count, ObjectsFoundInHeap(objs, objs_count));
}
870 871


872 873 874 875 876 877 878 879 880 881 882 883 884 885
TEST(EmptyHandleEscapeFrom) {
  InitializeVM();

  v8::HandleScope scope;
  Handle<JSObject> runaway;

  {
      v8::HandleScope nested;
      Handle<JSObject> empty;
      runaway = empty.EscapeFrom(&nested);
  }

  CHECK(runaway.is_null());
}
886 887 888 889 890 891 892 893 894 895 896 897


static int LenFromSize(int size) {
  return (size - FixedArray::kHeaderSize) / kPointerSize;
}


TEST(Regression39128) {
  // Test case for crbug.com/39128.
  InitializeVM();

  // Increase the chance of 'bump-the-pointer' allocation in old space.
898
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
899 900 901 902 903

  v8::HandleScope scope;

  // The plan: create JSObject which references objects in new space.
  // Then clone this object (forcing it to go into old space) and check
904
  // that region dirty marks are updated correctly.
905 906

  // Step 1: prepare a map for the object.  We add 1 inobject property to it.
907
  Handle<JSFunction> object_ctor(
908
      Isolate::Current()->native_context()->object_function());
909 910 911
  CHECK(object_ctor->has_initial_map());
  Handle<Map> object_map(object_ctor->initial_map());
  // Create a map with single inobject property.
912
  Handle<Map> my_map = FACTORY->CopyMap(object_map, 1);
913 914 915 916 917 918 919 920 921
  int n_properties = my_map->inobject_properties();
  CHECK_GT(n_properties, 0);

  int object_size = my_map->instance_size();

  // Step 2: allocate a lot of objects so to almost fill new space: we need
  // just enough room to allocate JSObject and thus fill the newspace.

  int allocation_amount = Min(FixedArray::kMaxSize,
922
                              HEAP->MaxObjectSizeInNewSpace());
923
  int allocation_len = LenFromSize(allocation_amount);
924
  NewSpace* new_space = HEAP->new_space();
925 926 927
  Address* top_addr = new_space->allocation_top_address();
  Address* limit_addr = new_space->allocation_limit_address();
  while ((*limit_addr - *top_addr) > allocation_amount) {
928 929 930
    CHECK(!HEAP->always_allocate());
    Object* array = HEAP->AllocateFixedArray(allocation_len)->ToObjectChecked();
    CHECK(!array->IsFailure());
931 932 933 934
    CHECK(new_space->Contains(array));
  }

  // Step 3: now allocate fixed array and JSObject to fill the whole new space.
935
  int to_fill = static_cast<int>(*limit_addr - *top_addr - object_size);
936 937 938
  int fixed_array_len = LenFromSize(to_fill);
  CHECK(fixed_array_len < FixedArray::kMaxLength);

939 940 941
  CHECK(!HEAP->always_allocate());
  Object* array = HEAP->AllocateFixedArray(fixed_array_len)->ToObjectChecked();
  CHECK(!array->IsFailure());
942 943
  CHECK(new_space->Contains(array));

944
  Object* object = HEAP->AllocateJSObjectFromMap(*my_map)->ToObjectChecked();
945 946
  CHECK(new_space->Contains(object));
  JSObject* jsobject = JSObject::cast(object);
947
  CHECK_EQ(0, FixedArray::cast(jsobject->elements())->length());
948 949 950 951
  CHECK_EQ(0, jsobject->properties()->length());
  // Create a reference to object in new space in jsobject.
  jsobject->FastPropertyAtPut(-1, array);

952
  CHECK_EQ(0, static_cast<int>(*limit_addr - *top_addr));
953 954 955

  // Step 4: clone jsobject, but force always allocate first to create a clone
  // in old pointer space.
956
  Address old_pointer_space_top = HEAP->old_pointer_space()->top();
957
  AlwaysAllocateScope aa_scope;
958
  Object* clone_obj = HEAP->CopyJSObject(jsobject)->ToObjectChecked();
959 960 961 962 963
  JSObject* clone = JSObject::cast(clone_obj);
  if (clone->address() != old_pointer_space_top) {
    // Alas, got allocated from free list, we cannot do checks.
    return;
  }
964
  CHECK(HEAP->old_pointer_space()->Contains(clone->address()));
965
}
966

967

968
TEST(TestCodeFlushing) {
969 970
  // If we do not flush code this test is invalid.
  if (!FLAG_flush_code) return;
971
  i::FLAG_allow_natives_syntax = true;
972 973 974 975 976 977 978 979
  InitializeVM();
  v8::HandleScope scope;
  const char* source = "function foo() {"
                       "  var x = 42;"
                       "  var y = 42;"
                       "  var z = x + y;"
                       "};"
                       "foo()";
980
  Handle<String> foo_name = FACTORY->LookupUtf8Symbol("foo");
981 982

  // This compile will add the code to the compilation cache.
983 984 985
  { v8::HandleScope scope;
    CompileRun(source);
  }
986 987

  // Check function is compiled.
988
  Object* func_value = Isolate::Current()->context()->global_object()->
989
      GetProperty(*foo_name)->ToObjectChecked();
990 991 992 993
  CHECK(func_value->IsJSFunction());
  Handle<JSFunction> function(JSFunction::cast(func_value));
  CHECK(function->shared()->is_compiled());

994
  // The code will survive at least two GCs.
995 996
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
997
  CHECK(function->shared()->is_compiled());
998

999 1000 1001 1002 1003
  // Simulate several GCs that use full marking.
  const int kAgingThreshold = 6;
  for (int i = 0; i < kAgingThreshold; i++) {
    HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
  }
1004 1005

  // foo should no longer be in the compilation cache
1006 1007
  CHECK(!function->shared()->is_compiled() || function->IsOptimized());
  CHECK(!function->is_compiled() || function->IsOptimized());
1008 1009 1010
  // Call foo to get it recompiled.
  CompileRun("foo()");
  CHECK(function->shared()->is_compiled());
1011
  CHECK(function->is_compiled());
1012
}
1013 1014


1015 1016
TEST(TestCodeFlushingIncremental) {
  // If we do not flush code this test is invalid.
1017
  if (!FLAG_flush_code || !FLAG_flush_code_incrementally) return;
1018 1019 1020 1021 1022 1023 1024 1025 1026
  i::FLAG_allow_natives_syntax = true;
  InitializeVM();
  v8::HandleScope scope;
  const char* source = "function foo() {"
                       "  var x = 42;"
                       "  var y = 42;"
                       "  var z = x + y;"
                       "};"
                       "foo()";
1027
  Handle<String> foo_name = FACTORY->LookupUtf8Symbol("foo");
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

  // This compile will add the code to the compilation cache.
  { v8::HandleScope scope;
    CompileRun(source);
  }

  // Check function is compiled.
  Object* func_value = Isolate::Current()->context()->global_object()->
      GetProperty(*foo_name)->ToObjectChecked();
  CHECK(func_value->IsJSFunction());
  Handle<JSFunction> function(JSFunction::cast(func_value));
  CHECK(function->shared()->is_compiled());

  // The code will survive at least two GCs.
1042 1043
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
  CHECK(function->shared()->is_compiled());

  // Simulate several GCs that use incremental marking.
  const int kAgingThreshold = 6;
  for (int i = 0; i < kAgingThreshold; i++) {
    SimulateIncrementalMarking();
    HEAP->CollectAllGarbage(Heap::kNoGCFlags);
  }
  CHECK(!function->shared()->is_compiled() || function->IsOptimized());
  CHECK(!function->is_compiled() || function->IsOptimized());

  // This compile will compile the function again.
  { v8::HandleScope scope;
    CompileRun("foo();");
  }

  // Simulate several GCs that use incremental marking but make sure
  // the loop breaks once the function is enqueued as a candidate.
  for (int i = 0; i < kAgingThreshold; i++) {
    SimulateIncrementalMarking();
    if (!function->next_function_link()->IsUndefined()) break;
    HEAP->CollectAllGarbage(Heap::kNoGCFlags);
  }

  // Force optimization while incremental marking is active and while
  // the function is enqueued as a candidate.
  { v8::HandleScope scope;
    CompileRun("%OptimizeFunctionOnNextCall(foo); foo();");
  }

  // Simulate one final GC to make sure the candidate queue is sane.
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
  CHECK(function->shared()->is_compiled() || !function->IsOptimized());
  CHECK(function->is_compiled() || !function->IsOptimized());
}


1081 1082
TEST(TestCodeFlushingIncrementalScavenge) {
  // If we do not flush code this test is invalid.
1083
  if (!FLAG_flush_code || !FLAG_flush_code_incrementally) return;
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
  i::FLAG_allow_natives_syntax = true;
  InitializeVM();
  v8::HandleScope scope;
  const char* source = "var foo = function() {"
                       "  var x = 42;"
                       "  var y = 42;"
                       "  var z = x + y;"
                       "};"
                       "foo();"
                       "var bar = function() {"
                       "  var x = 23;"
                       "};"
                       "bar();";
1097 1098
  Handle<String> foo_name = FACTORY->LookupUtf8Symbol("foo");
  Handle<String> bar_name = FACTORY->LookupUtf8Symbol("bar");
1099 1100

  // Perfrom one initial GC to enable code flushing.
1101
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127

  // This compile will add the code to the compilation cache.
  { v8::HandleScope scope;
    CompileRun(source);
  }

  // Check functions are compiled.
  Object* func_value = Isolate::Current()->context()->global_object()->
      GetProperty(*foo_name)->ToObjectChecked();
  CHECK(func_value->IsJSFunction());
  Handle<JSFunction> function(JSFunction::cast(func_value));
  CHECK(function->shared()->is_compiled());
  Object* func_value2 = Isolate::Current()->context()->global_object()->
      GetProperty(*bar_name)->ToObjectChecked();
  CHECK(func_value2->IsJSFunction());
  Handle<JSFunction> function2(JSFunction::cast(func_value2));
  CHECK(function2->shared()->is_compiled());

  // Clear references to functions so that one of them can die.
  { v8::HandleScope scope;
    CompileRun("foo = 0; bar = 0;");
  }

  // Bump the code age so that flushing is triggered while the function
  // object is still located in new-space.
  const int kAgingThreshold = 6;
1128 1129 1130 1131
  for (int i = 0; i < kAgingThreshold; i++) {
    function->shared()->code()->MakeOlder(static_cast<MarkingParity>(i % 2));
    function2->shared()->code()->MakeOlder(static_cast<MarkingParity>(i % 2));
  }
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

  // Simulate incremental marking so that the functions are enqueued as
  // code flushing candidates. Then kill one of the functions. Finally
  // perform a scavenge while incremental marking is still running.
  SimulateIncrementalMarking();
  *function2.location() = NULL;
  HEAP->CollectGarbage(NEW_SPACE, "test scavenge while marking");

  // Simulate one final GC to make sure the candidate queue is sane.
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
  CHECK(!function->shared()->is_compiled() || function->IsOptimized());
  CHECK(!function->is_compiled() || function->IsOptimized());
}


1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
TEST(TestCodeFlushingIncrementalAbort) {
  // If we do not flush code this test is invalid.
  if (!FLAG_flush_code || !FLAG_flush_code_incrementally) return;
  i::FLAG_allow_natives_syntax = true;
  InitializeVM();
  v8::HandleScope scope;
  const char* source = "function foo() {"
                       "  var x = 42;"
                       "  var y = 42;"
                       "  var z = x + y;"
                       "};"
                       "foo()";
1159
  Handle<String> foo_name = FACTORY->LookupUtf8Symbol("foo");
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

  // This compile will add the code to the compilation cache.
  { v8::HandleScope scope;
    CompileRun(source);
  }

  // Check function is compiled.
  Object* func_value = Isolate::Current()->context()->global_object()->
      GetProperty(*foo_name)->ToObjectChecked();
  CHECK(func_value->IsJSFunction());
  Handle<JSFunction> function(JSFunction::cast(func_value));
  CHECK(function->shared()->is_compiled());

  // The code will survive at least two GCs.
1174 1175
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
1176 1177 1178 1179
  CHECK(function->shared()->is_compiled());

  // Bump the code age so that flushing is triggered.
  const int kAgingThreshold = 6;
1180 1181 1182
  for (int i = 0; i < kAgingThreshold; i++) {
    function->shared()->code()->MakeOlder(static_cast<MarkingParity>(i % 2));
  }
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207

  // Simulate incremental marking so that the function is enqueued as
  // code flushing candidate.
  SimulateIncrementalMarking();

  // Enable the debugger and add a breakpoint while incremental marking
  // is running so that incremental marking aborts and code flushing is
  // disabled.
  int position = 0;
  Handle<Object> breakpoint_object(Smi::FromInt(0));
  ISOLATE->debug()->SetBreakPoint(function, breakpoint_object, &position);
  ISOLATE->debug()->ClearAllBreakPoints();

  // Force optimization now that code flushing is disabled.
  { v8::HandleScope scope;
    CompileRun("%OptimizeFunctionOnNextCall(foo); foo();");
  }

  // Simulate one final GC to make sure the candidate queue is sane.
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
  CHECK(function->shared()->is_compiled() || !function->IsOptimized());
  CHECK(function->is_compiled() || !function->IsOptimized());
}


1208 1209
// Count the number of native contexts in the weak list of native contexts.
int CountNativeContexts() {
1210
  int count = 0;
1211
  Object* object = HEAP->native_contexts_list();
1212 1213 1214 1215 1216 1217 1218 1219
  while (!object->IsUndefined()) {
    count++;
    object = Context::cast(object)->get(Context::NEXT_CONTEXT_LINK);
  }
  return count;
}


1220
// Count the number of user functions in the weak list of optimized
1221
// functions attached to a native context.
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
static int CountOptimizedUserFunctions(v8::Handle<v8::Context> context) {
  int count = 0;
  Handle<Context> icontext = v8::Utils::OpenHandle(*context);
  Object* object = icontext->get(Context::OPTIMIZED_FUNCTIONS_LIST);
  while (object->IsJSFunction() && !JSFunction::cast(object)->IsBuiltin()) {
    count++;
    object = JSFunction::cast(object)->next_function_link();
  }
  return count;
}


1234
TEST(TestInternalWeakLists) {
1235 1236
  v8::V8::Initialize();

1237 1238 1239 1240
  // Some flags turn Scavenge collections into Mark-sweep collections
  // and hence are incompatible with this test case.
  if (FLAG_gc_global || FLAG_stress_compaction) return;

1241 1242 1243 1244 1245
  static const int kNumTestContexts = 10;

  v8::HandleScope scope;
  v8::Persistent<v8::Context> ctx[kNumTestContexts];

1246
  CHECK_EQ(0, CountNativeContexts());
1247 1248 1249 1250

  // Create a number of global contests which gets linked together.
  for (int i = 0; i < kNumTestContexts; i++) {
    ctx[i] = v8::Context::New();
1251

1252
    bool opt = (FLAG_always_opt && i::V8::UseCrankshaft());
1253

1254
    CHECK_EQ(i + 1, CountNativeContexts());
1255 1256

    ctx[i]->Enter();
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283

    // Create a handle scope so no function objects get stuch in the outer
    // handle scope
    v8::HandleScope scope;
    const char* source = "function f1() { };"
                         "function f2() { };"
                         "function f3() { };"
                         "function f4() { };"
                         "function f5() { };";
    CompileRun(source);
    CHECK_EQ(0, CountOptimizedUserFunctions(ctx[i]));
    CompileRun("f1()");
    CHECK_EQ(opt ? 1 : 0, CountOptimizedUserFunctions(ctx[i]));
    CompileRun("f2()");
    CHECK_EQ(opt ? 2 : 0, CountOptimizedUserFunctions(ctx[i]));
    CompileRun("f3()");
    CHECK_EQ(opt ? 3 : 0, CountOptimizedUserFunctions(ctx[i]));
    CompileRun("f4()");
    CHECK_EQ(opt ? 4 : 0, CountOptimizedUserFunctions(ctx[i]));
    CompileRun("f5()");
    CHECK_EQ(opt ? 5 : 0, CountOptimizedUserFunctions(ctx[i]));

    // Remove function f1, and
    CompileRun("f1=null");

    // Scavenge treats these references as strong.
    for (int j = 0; j < 10; j++) {
1284
      HEAP->PerformScavenge();
1285 1286 1287 1288
      CHECK_EQ(opt ? 5 : 0, CountOptimizedUserFunctions(ctx[i]));
    }

    // Mark compact handles the weak references.
1289
    ISOLATE->compilation_cache()->Clear();
1290
    HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1291 1292 1293 1294 1295
    CHECK_EQ(opt ? 4 : 0, CountOptimizedUserFunctions(ctx[i]));

    // Get rid of f3 and f5 in the same way.
    CompileRun("f3=null");
    for (int j = 0; j < 10; j++) {
1296
      HEAP->PerformScavenge();
1297 1298
      CHECK_EQ(opt ? 4 : 0, CountOptimizedUserFunctions(ctx[i]));
    }
1299
    HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1300 1301 1302
    CHECK_EQ(opt ? 3 : 0, CountOptimizedUserFunctions(ctx[i]));
    CompileRun("f5=null");
    for (int j = 0; j < 10; j++) {
1303
      HEAP->PerformScavenge();
1304 1305
      CHECK_EQ(opt ? 3 : 0, CountOptimizedUserFunctions(ctx[i]));
    }
1306
    HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1307 1308
    CHECK_EQ(opt ? 2 : 0, CountOptimizedUserFunctions(ctx[i]));

1309 1310 1311
    ctx[i]->Exit();
  }

1312
  // Force compilation cache cleanup.
1313
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1314

1315
  // Dispose the native contexts one by one.
1316 1317 1318 1319 1320 1321
  for (int i = 0; i < kNumTestContexts; i++) {
    ctx[i].Dispose();
    ctx[i].Clear();

    // Scavenge treats these references as strong.
    for (int j = 0; j < 10; j++) {
1322
      HEAP->PerformScavenge();
1323
      CHECK_EQ(kNumTestContexts - i, CountNativeContexts());
1324 1325 1326
    }

    // Mark compact handles the weak references.
1327
    HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1328
    CHECK_EQ(kNumTestContexts - i - 1, CountNativeContexts());
1329 1330
  }

1331
  CHECK_EQ(0, CountNativeContexts());
1332 1333 1334
}


1335
// Count the number of native contexts in the weak list of native contexts
1336
// causing a GC after the specified number of elements.
1337
static int CountNativeContextsWithGC(int n) {
1338
  int count = 0;
1339
  Handle<Object> object(HEAP->native_contexts_list());
1340 1341
  while (!object->IsUndefined()) {
    count++;
1342
    if (count == n) HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1343 1344 1345 1346 1347 1348 1349
    object =
        Handle<Object>(Context::cast(*object)->get(Context::NEXT_CONTEXT_LINK));
  }
  return count;
}


1350
// Count the number of user functions in the weak list of optimized
1351
// functions attached to a native context causing a GC after the
1352 1353 1354 1355 1356 1357 1358 1359 1360
// specified number of elements.
static int CountOptimizedUserFunctionsWithGC(v8::Handle<v8::Context> context,
                                             int n) {
  int count = 0;
  Handle<Context> icontext = v8::Utils::OpenHandle(*context);
  Handle<Object> object(icontext->get(Context::OPTIMIZED_FUNCTIONS_LIST));
  while (object->IsJSFunction() &&
         !Handle<JSFunction>::cast(object)->IsBuiltin()) {
    count++;
1361
    if (count == n) HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1362 1363 1364 1365 1366 1367 1368
    object = Handle<Object>(
        Object::cast(JSFunction::cast(*object)->next_function_link()));
  }
  return count;
}


1369
TEST(TestInternalWeakListsTraverseWithGC) {
1370 1371
  v8::V8::Initialize();

1372 1373 1374 1375 1376
  static const int kNumTestContexts = 10;

  v8::HandleScope scope;
  v8::Persistent<v8::Context> ctx[kNumTestContexts];

1377
  CHECK_EQ(0, CountNativeContexts());
1378 1379 1380 1381 1382

  // Create an number of contexts and check the length of the weak list both
  // with and without GCs while iterating the list.
  for (int i = 0; i < kNumTestContexts; i++) {
    ctx[i] = v8::Context::New();
1383 1384
    CHECK_EQ(i + 1, CountNativeContexts());
    CHECK_EQ(i + 1, CountNativeContextsWithGC(i / 2 + 1));
1385
  }
1386

1387
  bool opt = (FLAG_always_opt && i::V8::UseCrankshaft());
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415

  // Compile a number of functions the length of the weak list of optimized
  // functions both with and without GCs while iterating the list.
  ctx[0]->Enter();
  const char* source = "function f1() { };"
                       "function f2() { };"
                       "function f3() { };"
                       "function f4() { };"
                       "function f5() { };";
  CompileRun(source);
  CHECK_EQ(0, CountOptimizedUserFunctions(ctx[0]));
  CompileRun("f1()");
  CHECK_EQ(opt ? 1 : 0, CountOptimizedUserFunctions(ctx[0]));
  CHECK_EQ(opt ? 1 : 0, CountOptimizedUserFunctionsWithGC(ctx[0], 1));
  CompileRun("f2()");
  CHECK_EQ(opt ? 2 : 0, CountOptimizedUserFunctions(ctx[0]));
  CHECK_EQ(opt ? 2 : 0, CountOptimizedUserFunctionsWithGC(ctx[0], 1));
  CompileRun("f3()");
  CHECK_EQ(opt ? 3 : 0, CountOptimizedUserFunctions(ctx[0]));
  CHECK_EQ(opt ? 3 : 0, CountOptimizedUserFunctionsWithGC(ctx[0], 1));
  CompileRun("f4()");
  CHECK_EQ(opt ? 4 : 0, CountOptimizedUserFunctions(ctx[0]));
  CHECK_EQ(opt ? 4 : 0, CountOptimizedUserFunctionsWithGC(ctx[0], 2));
  CompileRun("f5()");
  CHECK_EQ(opt ? 5 : 0, CountOptimizedUserFunctions(ctx[0]));
  CHECK_EQ(opt ? 5 : 0, CountOptimizedUserFunctionsWithGC(ctx[0], 4));

  ctx[0]->Exit();
1416
}
1417 1418


1419 1420 1421 1422 1423 1424
TEST(TestSizeOfObjects) {
  v8::V8::Initialize();

  // Get initial heap size after several full GCs, which will stabilize
  // the heap size and return with sweeping finished completely.
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1425
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1426 1427 1428 1429
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
  CHECK(HEAP->old_pointer_space()->IsSweepingComplete());
1430
  int initial_size = static_cast<int>(HEAP->SizeOfObjects());
1431 1432 1433 1434 1435

  {
    // Allocate objects on several different old-space pages so that
    // lazy sweeping kicks in for subsequent GC runs.
    AlwaysAllocateScope always_allocate;
1436
    int filler_size = static_cast<int>(FixedArray::SizeFor(8192));
1437 1438
    for (int i = 1; i <= 100; i++) {
      HEAP->AllocateFixedArray(8192, TENURED)->ToObjectChecked();
1439 1440
      CHECK_EQ(initial_size + i * filler_size,
               static_cast<int>(HEAP->SizeOfObjects()));
1441 1442 1443 1444 1445 1446
    }
  }

  // The heap size should go back to initial size after a full GC, even
  // though sweeping didn't finish yet.
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1447 1448 1449

  // Normally sweeping would not be complete here, but no guarantees.

1450
  CHECK_EQ(initial_size, static_cast<int>(HEAP->SizeOfObjects()));
1451 1452 1453 1454

  // Advancing the sweeper step-wise should not change the heap size.
  while (!HEAP->old_pointer_space()->IsSweepingComplete()) {
    HEAP->old_pointer_space()->AdvanceSweeper(KB);
1455
    CHECK_EQ(initial_size, static_cast<int>(HEAP->SizeOfObjects()));
1456 1457 1458 1459
  }
}


1460 1461
TEST(TestSizeOfObjectsVsHeapIteratorPrecision) {
  InitializeVM();
1462
  HEAP->EnsureHeapIsIterable();
1463
  intptr_t size_of_objects_1 = HEAP->SizeOfObjects();
1464
  HeapIterator iterator;
1465 1466 1467 1468
  intptr_t size_of_objects_2 = 0;
  for (HeapObject* obj = iterator.next();
       obj != NULL;
       obj = iterator.next()) {
1469 1470 1471
    if (!obj->IsFreeSpace()) {
      size_of_objects_2 += obj->Size();
    }
1472
  }
1473 1474 1475 1476
  // Delta must be within 5% of the larger result.
  // TODO(gc): Tighten this up by distinguishing between byte
  // arrays that are real and those that merely mark free space
  // on the heap.
1477 1478 1479 1480 1481 1482
  if (size_of_objects_1 > size_of_objects_2) {
    intptr_t delta = size_of_objects_1 - size_of_objects_2;
    PrintF("Heap::SizeOfObjects: %" V8_PTR_PREFIX "d, "
           "Iterator: %" V8_PTR_PREFIX "d, "
           "delta: %" V8_PTR_PREFIX "d\n",
           size_of_objects_1, size_of_objects_2, delta);
1483
    CHECK_GT(size_of_objects_1 / 20, delta);
1484 1485 1486 1487 1488 1489
  } else {
    intptr_t delta = size_of_objects_2 - size_of_objects_1;
    PrintF("Heap::SizeOfObjects: %" V8_PTR_PREFIX "d, "
           "Iterator: %" V8_PTR_PREFIX "d, "
           "delta: %" V8_PTR_PREFIX "d\n",
           size_of_objects_1, size_of_objects_2, delta);
1490
    CHECK_GT(size_of_objects_2 / 20, delta);
1491 1492
  }
}
1493 1494


1495 1496 1497 1498 1499 1500
static void FillUpNewSpace(NewSpace* new_space) {
  // Fill up new space to the point that it is completely full. Make sure
  // that the scavenger does not undo the filling.
  v8::HandleScope scope;
  AlwaysAllocateScope always_allocate;
  intptr_t available = new_space->EffectiveCapacity() - new_space->Size();
1501
  intptr_t number_of_fillers = (available / FixedArray::SizeFor(32)) - 1;
1502
  for (intptr_t i = 0; i < number_of_fillers; i++) {
1503
    CHECK(HEAP->InNewSpace(*FACTORY->NewFixedArray(32, NOT_TENURED)));
1504 1505 1506 1507
  }
}


1508 1509 1510 1511
TEST(GrowAndShrinkNewSpace) {
  InitializeVM();
  NewSpace* new_space = HEAP->new_space();

1512 1513
  if (HEAP->ReservedSemiSpaceSize() == HEAP->InitialSemiSpaceSize() ||
      HEAP->MaxSemiSpaceSize() == HEAP->InitialSemiSpaceSize()) {
1514 1515 1516 1517 1518 1519
    // The max size cannot exceed the reserved size, since semispaces must be
    // always within the reserved space.  We can't test new space growing and
    // shrinking if the reserved size is the same as the minimum (initial) size.
    return;
  }

1520
  // Explicitly growing should double the space capacity.
1521
  intptr_t old_capacity, new_capacity;
1522 1523 1524
  old_capacity = new_space->Capacity();
  new_space->Grow();
  new_capacity = new_space->Capacity();
1525
  CHECK(2 * old_capacity == new_capacity);
1526

1527
  old_capacity = new_space->Capacity();
1528
  FillUpNewSpace(new_space);
1529
  new_capacity = new_space->Capacity();
1530
  CHECK(old_capacity == new_capacity);
1531 1532 1533 1534 1535

  // Explicitly shrinking should not affect space capacity.
  old_capacity = new_space->Capacity();
  new_space->Shrink();
  new_capacity = new_space->Capacity();
1536
  CHECK(old_capacity == new_capacity);
1537

1538
  // Let the scavenger empty the new space.
1539
  HEAP->CollectGarbage(NEW_SPACE);
1540
  CHECK_LE(new_space->Size(), old_capacity);
1541 1542 1543 1544 1545

  // Explicitly shrinking should halve the space capacity.
  old_capacity = new_space->Capacity();
  new_space->Shrink();
  new_capacity = new_space->Capacity();
1546
  CHECK(old_capacity == 2 * new_capacity);
1547 1548 1549 1550 1551 1552 1553

  // Consecutive shrinking should not affect space capacity.
  old_capacity = new_space->Capacity();
  new_space->Shrink();
  new_space->Shrink();
  new_space->Shrink();
  new_capacity = new_space->Capacity();
1554
  CHECK(old_capacity == new_capacity);
1555
}
1556 1557 1558 1559


TEST(CollectingAllAvailableGarbageShrinksNewSpace) {
  InitializeVM();
1560

1561 1562
  if (HEAP->ReservedSemiSpaceSize() == HEAP->InitialSemiSpaceSize() ||
      HEAP->MaxSemiSpaceSize() == HEAP->InitialSemiSpaceSize()) {
1563 1564 1565 1566 1567 1568
    // The max size cannot exceed the reserved size, since semispaces must be
    // always within the reserved space.  We can't test new space growing and
    // shrinking if the reserved size is the same as the minimum (initial) size.
    return;
  }

1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
  v8::HandleScope scope;
  NewSpace* new_space = HEAP->new_space();
  intptr_t old_capacity, new_capacity;
  old_capacity = new_space->Capacity();
  new_space->Grow();
  new_capacity = new_space->Capacity();
  CHECK(2 * old_capacity == new_capacity);
  FillUpNewSpace(new_space);
  HEAP->CollectAllAvailableGarbage();
  new_capacity = new_space->Capacity();
  CHECK(old_capacity == new_capacity);
}
1581

1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594

static int NumberOfGlobalObjects() {
  int count = 0;
  HeapIterator iterator;
  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
    if (obj->IsGlobalObject()) count++;
  }
  return count;
}


// Test that we don't embed maps from foreign contexts into
// optimized code.
1595
TEST(LeakNativeContextViaMap) {
1596
  i::FLAG_allow_natives_syntax = true;
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
  v8::HandleScope outer_scope;
  v8::Persistent<v8::Context> ctx1 = v8::Context::New();
  v8::Persistent<v8::Context> ctx2 = v8::Context::New();
  ctx1->Enter();

  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(4, NumberOfGlobalObjects());

  {
    v8::HandleScope inner_scope;
    CompileRun("var v = {x: 42}");
    v8::Local<v8::Value> v = ctx1->Global()->Get(v8_str("v"));
    ctx2->Enter();
    ctx2->Global()->Set(v8_str("o"), v);
    v8::Local<v8::Value> res = CompileRun(
        "function f() { return o.x; }"
1613 1614
        "for (var i = 0; i < 10; ++i) f();"
        "%OptimizeFunctionOnNextCall(f);"
1615 1616 1617 1618 1619 1620
        "f();");
    CHECK_EQ(42, res->Int32Value());
    ctx2->Global()->Set(v8_str("o"), v8::Int32::New(0));
    ctx2->Exit();
    ctx1->Exit();
    ctx1.Dispose();
1621
    v8::V8::ContextDisposedNotification();
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
  }
  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(2, NumberOfGlobalObjects());
  ctx2.Dispose();
  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(0, NumberOfGlobalObjects());
}


// Test that we don't embed functions from foreign contexts into
// optimized code.
1633
TEST(LeakNativeContextViaFunction) {
1634
  i::FLAG_allow_natives_syntax = true;
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
  v8::HandleScope outer_scope;
  v8::Persistent<v8::Context> ctx1 = v8::Context::New();
  v8::Persistent<v8::Context> ctx2 = v8::Context::New();
  ctx1->Enter();

  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(4, NumberOfGlobalObjects());

  {
    v8::HandleScope inner_scope;
    CompileRun("var v = function() { return 42; }");
    v8::Local<v8::Value> v = ctx1->Global()->Get(v8_str("v"));
    ctx2->Enter();
    ctx2->Global()->Set(v8_str("o"), v);
    v8::Local<v8::Value> res = CompileRun(
        "function f(x) { return x(); }"
1651 1652
        "for (var i = 0; i < 10; ++i) f(o);"
        "%OptimizeFunctionOnNextCall(f);"
1653 1654 1655 1656 1657 1658
        "f(o);");
    CHECK_EQ(42, res->Int32Value());
    ctx2->Global()->Set(v8_str("o"), v8::Int32::New(0));
    ctx2->Exit();
    ctx1->Exit();
    ctx1.Dispose();
1659
    v8::V8::ContextDisposedNotification();
1660 1661 1662 1663 1664 1665 1666
  }
  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(2, NumberOfGlobalObjects());
  ctx2.Dispose();
  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(0, NumberOfGlobalObjects());
}
1667 1668


1669
TEST(LeakNativeContextViaMapKeyed) {
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope outer_scope;
  v8::Persistent<v8::Context> ctx1 = v8::Context::New();
  v8::Persistent<v8::Context> ctx2 = v8::Context::New();
  ctx1->Enter();

  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(4, NumberOfGlobalObjects());

  {
    v8::HandleScope inner_scope;
    CompileRun("var v = [42, 43]");
    v8::Local<v8::Value> v = ctx1->Global()->Get(v8_str("v"));
    ctx2->Enter();
    ctx2->Global()->Set(v8_str("o"), v);
    v8::Local<v8::Value> res = CompileRun(
        "function f() { return o[0]; }"
        "for (var i = 0; i < 10; ++i) f();"
        "%OptimizeFunctionOnNextCall(f);"
        "f();");
    CHECK_EQ(42, res->Int32Value());
    ctx2->Global()->Set(v8_str("o"), v8::Int32::New(0));
    ctx2->Exit();
    ctx1->Exit();
    ctx1.Dispose();
1695
    v8::V8::ContextDisposedNotification();
1696 1697 1698 1699 1700 1701 1702 1703 1704
  }
  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(2, NumberOfGlobalObjects());
  ctx2.Dispose();
  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(0, NumberOfGlobalObjects());
}


1705
TEST(LeakNativeContextViaMapProto) {
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope outer_scope;
  v8::Persistent<v8::Context> ctx1 = v8::Context::New();
  v8::Persistent<v8::Context> ctx2 = v8::Context::New();
  ctx1->Enter();

  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(4, NumberOfGlobalObjects());

  {
    v8::HandleScope inner_scope;
    CompileRun("var v = { y: 42}");
    v8::Local<v8::Value> v = ctx1->Global()->Get(v8_str("v"));
    ctx2->Enter();
    ctx2->Global()->Set(v8_str("o"), v);
    v8::Local<v8::Value> res = CompileRun(
        "function f() {"
        "  var p = {x: 42};"
        "  p.__proto__ = o;"
        "  return p.x;"
        "}"
        "for (var i = 0; i < 10; ++i) f();"
        "%OptimizeFunctionOnNextCall(f);"
        "f();");
    CHECK_EQ(42, res->Int32Value());
    ctx2->Global()->Set(v8_str("o"), v8::Int32::New(0));
    ctx2->Exit();
    ctx1->Exit();
    ctx1.Dispose();
1735
    v8::V8::ContextDisposedNotification();
1736 1737 1738 1739 1740 1741 1742
  }
  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(2, NumberOfGlobalObjects());
  ctx2.Dispose();
  HEAP->CollectAllAvailableGarbage();
  CHECK_EQ(0, NumberOfGlobalObjects());
}
1743 1744 1745 1746


TEST(InstanceOfStubWriteBarrier) {
  i::FLAG_allow_natives_syntax = true;
1747
#ifdef VERIFY_HEAP
1748
  i::FLAG_verify_heap = true;
1749
#endif
1750

1751
  InitializeVM();
1752
  if (!i::V8::UseCrankshaft()) return;
1753
  if (i::FLAG_force_marking_deque_overflows) return;
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
  v8::HandleScope outer_scope;

  {
    v8::HandleScope scope;
    CompileRun(
        "function foo () { }"
        "function mkbar () { return new (new Function(\"\")) (); }"
        "function f (x) { return (x instanceof foo); }"
        "function g () { f(mkbar()); }"
        "f(new foo()); f(new foo());"
        "%OptimizeFunctionOnNextCall(f);"
        "f(new foo()); g();");
  }

  IncrementalMarking* marking = HEAP->incremental_marking();
  marking->Abort();
  marking->Start();

  Handle<JSFunction> f =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Function>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("f"))));

  CHECK(f->IsOptimized());

  while (!Marking::IsBlack(Marking::MarkBitFrom(f->code())) &&
         !marking->IsStopped()) {
1781 1782 1783
    // Discard any pending GC requests otherwise we will get GC when we enter
    // code below.
    marking->Step(MB, IncrementalMarking::NO_GC_VIA_STACK_GUARD);
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
  }

  CHECK(marking->IsMarking());

  {
    v8::HandleScope scope;
    v8::Handle<v8::Object> global = v8::Context::GetCurrent()->Global();
    v8::Handle<v8::Function> g =
        v8::Handle<v8::Function>::Cast(global->Get(v8_str("g")));
    g->Call(global, 0, NULL);
  }

  HEAP->incremental_marking()->set_should_hurry(true);
  HEAP->CollectGarbage(OLD_POINTER_SPACE);
}
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819


TEST(PrototypeTransitionClearing) {
  InitializeVM();
  v8::HandleScope scope;

  CompileRun(
      "var base = {};"
      "var live = [];"
      "for (var i = 0; i < 10; i++) {"
      "  var object = {};"
      "  var prototype = {};"
      "  object.__proto__ = prototype;"
      "  if (i >= 3) live.push(object, prototype);"
      "}");

  Handle<JSObject> baseObject =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Object>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("base"))));

1820 1821
  // Verify that only dead prototype transitions are cleared.
  CHECK_EQ(10, baseObject->map()->NumberOfProtoTransitions());
1822
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
1823
  const int transitions = 10 - 3;
1824
  CHECK_EQ(transitions, baseObject->map()->NumberOfProtoTransitions());
1825 1826

  // Verify that prototype transitions array was compacted.
1827
  FixedArray* trans = baseObject->map()->GetPrototypeTransitions();
1828
  for (int i = 0; i < transitions; i++) {
1829 1830 1831
    int j = Map::kProtoTransitionHeaderSize +
        i * Map::kProtoTransitionElementsPerEntry;
    CHECK(trans->get(j + Map::kProtoTransitionMapOffset)->IsMap());
1832 1833
    Object* proto = trans->get(j + Map::kProtoTransitionPrototypeOffset);
    CHECK(proto->IsTheHole() || proto->IsJSObject());
1834
  }
1835 1836 1837 1838

  // Make sure next prototype is placed on an old-space evacuation candidate.
  Handle<JSObject> prototype;
  PagedSpace* space = HEAP->old_pointer_space();
1839 1840 1841
  {
    AlwaysAllocateScope always_allocate;
    SimulateFullSpace(space);
1842
    prototype = FACTORY->NewJSArray(32 * KB, FAST_HOLEY_ELEMENTS, TENURED);
1843
  }
1844 1845 1846 1847 1848

  // Add a prototype on an evacuation candidate and verify that transition
  // clearing correctly records slots in prototype transition array.
  i::FLAG_always_compact = true;
  Handle<Map> map(baseObject->map());
1849 1850
  CHECK(!space->LastPage()->Contains(
      map->GetPrototypeTransitions()->address()));
1851 1852 1853 1854 1855
  CHECK(space->LastPage()->Contains(prototype->address()));
  baseObject->SetPrototype(*prototype, false)->ToObjectChecked();
  CHECK(map->GetPrototypeTransition(*prototype)->IsMap());
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
  CHECK(map->GetPrototypeTransition(*prototype)->IsMap());
1856
}
1857 1858 1859 1860


TEST(ResetSharedFunctionInfoCountersDuringIncrementalMarking) {
  i::FLAG_allow_natives_syntax = true;
1861
#ifdef VERIFY_HEAP
1862 1863
  i::FLAG_verify_heap = true;
#endif
1864

1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
  InitializeVM();
  if (!i::V8::UseCrankshaft()) return;
  v8::HandleScope outer_scope;

  {
    v8::HandleScope scope;
    CompileRun(
        "function f () {"
        "  var s = 0;"
        "  for (var i = 0; i < 100; i++)  s += i;"
        "  return s;"
        "}"
        "f(); f();"
        "%OptimizeFunctionOnNextCall(f);"
        "f();");
  }
  Handle<JSFunction> f =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Function>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("f"))));
  CHECK(f->IsOptimized());

  IncrementalMarking* marking = HEAP->incremental_marking();
  marking->Abort();
  marking->Start();

  // The following two calls will increment HEAP->global_ic_age().
  const int kLongIdlePauseInMs = 1000;
  v8::V8::ContextDisposedNotification();
  v8::V8::IdleNotification(kLongIdlePauseInMs);

  while (!marking->IsStopped() && !marking->IsComplete()) {
    marking->Step(1 * MB, IncrementalMarking::NO_GC_VIA_STACK_GUARD);
  }
1899 1900 1901 1902 1903 1904 1905 1906 1907
  if (!marking->IsStopped() || marking->should_hurry()) {
    // We don't normally finish a GC via Step(), we normally finish by
    // setting the stack guard and then do the final steps in the stack
    // guard interrupt.  But here we didn't ask for that, and there is no
    // JS code running to trigger the interrupt, so we explicitly finalize
    // here.
    HEAP->CollectAllGarbage(Heap::kNoGCFlags,
                            "Test finalizing incremental mark-sweep");
  }
1908 1909 1910 1911 1912 1913 1914 1915 1916

  CHECK_EQ(HEAP->global_ic_age(), f->shared()->ic_age());
  CHECK_EQ(0, f->shared()->opt_count());
  CHECK_EQ(0, f->shared()->code()->profiler_ticks());
}


TEST(ResetSharedFunctionInfoCountersDuringMarkSweep) {
  i::FLAG_allow_natives_syntax = true;
1917
#ifdef VERIFY_HEAP
1918 1919
  i::FLAG_verify_heap = true;
#endif
1920

1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
  InitializeVM();
  if (!i::V8::UseCrankshaft()) return;
  v8::HandleScope outer_scope;

  {
    v8::HandleScope scope;
    CompileRun(
        "function f () {"
        "  var s = 0;"
        "  for (var i = 0; i < 100; i++)  s += i;"
        "  return s;"
        "}"
        "f(); f();"
        "%OptimizeFunctionOnNextCall(f);"
        "f();");
  }
  Handle<JSFunction> f =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Function>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("f"))));
  CHECK(f->IsOptimized());

  HEAP->incremental_marking()->Abort();

  // The following two calls will increment HEAP->global_ic_age().
  // Since incremental marking is off, IdleNotification will do full GC.
  const int kLongIdlePauseInMs = 1000;
  v8::V8::ContextDisposedNotification();
  v8::V8::IdleNotification(kLongIdlePauseInMs);

  CHECK_EQ(HEAP->global_ic_age(), f->shared()->ic_age());
  CHECK_EQ(0, f->shared()->opt_count());
  CHECK_EQ(0, f->shared()->code()->profiler_ticks());
}
1955 1956 1957 1958 1959 1960 1961


// Test that HAllocateObject will always return an object in new-space.
TEST(OptimizedAllocationAlwaysInNewSpace) {
  i::FLAG_allow_natives_syntax = true;
  InitializeVM();
  if (!i::V8::UseCrankshaft() || i::FLAG_always_opt) return;
1962
  if (i::FLAG_gc_global || i::FLAG_stress_compaction) return;
1963 1964
  v8::HandleScope scope;

1965
  SimulateFullSpace(HEAP->new_space());
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
  AlwaysAllocateScope always_allocate;
  v8::Local<v8::Value> res = CompileRun(
      "function c(x) {"
      "  this.x = x;"
      "  for (var i = 0; i < 32; i++) {"
      "    this['x' + i] = x;"
      "  }"
      "}"
      "function f(x) { return new c(x); };"
      "f(1); f(2); f(3);"
      "%OptimizeFunctionOnNextCall(f);"
      "f(4);");
1978
  CHECK_EQ(4, res->ToObject()->GetRealNamedProperty(v8_str("x"))->Int32Value());
1979 1980 1981 1982 1983 1984

  Handle<JSObject> o =
      v8::Utils::OpenHandle(*v8::Handle<v8::Object>::Cast(res));

  CHECK(HEAP->InNewSpace(*o));
}
1985 1986 1987


static int CountMapTransitions(Map* map) {
1988
  return map->transitions()->number_of_transitions();
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
}


// Test that map transitions are cleared and maps are collected with
// incremental marking as well.
TEST(Regress1465) {
  i::FLAG_allow_natives_syntax = true;
  i::FLAG_trace_incremental_marking = true;
  InitializeVM();
  v8::HandleScope scope;
1999
  static const int transitions_count = 256;
2000

2001 2002 2003 2004 2005 2006 2007 2008
  {
    AlwaysAllocateScope always_allocate;
    for (int i = 0; i < transitions_count; i++) {
      EmbeddedVector<char, 64> buffer;
      OS::SNPrintF(buffer, "var o = new Object; o.prop%d = %d;", i, i);
      CompileRun(buffer.start());
    }
    CompileRun("var root = new Object;");
2009
  }
2010

2011 2012 2013 2014 2015 2016 2017 2018
  Handle<JSObject> root =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Object>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("root"))));

  // Count number of live transitions before marking.
  int transitions_before = CountMapTransitions(root->map());
  CompileRun("%DebugPrint(root);");
2019
  CHECK_EQ(transitions_count, transitions_before);
2020

2021
  SimulateIncrementalMarking();
2022 2023 2024 2025 2026 2027 2028 2029
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);

  // Count number of live transitions after marking.  Note that one transition
  // is left, because 'o' still holds an instance of one transition target.
  int transitions_after = CountMapTransitions(root->map());
  CompileRun("%DebugPrint(root);");
  CHECK_EQ(1, transitions_after);
}
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043


TEST(Regress2143a) {
  i::FLAG_collect_maps = true;
  i::FLAG_incremental_marking = true;
  InitializeVM();
  v8::HandleScope scope;

  // Prepare a map transition from the root object together with a yet
  // untransitioned root object.
  CompileRun("var root = new Object;"
             "root.foo = 0;"
             "root = new Object;");

2044
  SimulateIncrementalMarking();
2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084

  // Compile a StoreIC that performs the prepared map transition. This
  // will restart incremental marking and should make sure the root is
  // marked grey again.
  CompileRun("function f(o) {"
             "  o.foo = 0;"
             "}"
             "f(new Object);"
             "f(root);");

  // This bug only triggers with aggressive IC clearing.
  HEAP->AgeInlineCaches();

  // Explicitly request GC to perform final marking step and sweeping.
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);

  Handle<JSObject> root =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Object>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("root"))));

  // The root object should be in a sane state.
  CHECK(root->IsJSObject());
  CHECK(root->map()->IsMap());
}


TEST(Regress2143b) {
  i::FLAG_collect_maps = true;
  i::FLAG_incremental_marking = true;
  i::FLAG_allow_natives_syntax = true;
  InitializeVM();
  v8::HandleScope scope;

  // Prepare a map transition from the root object together with a yet
  // untransitioned root object.
  CompileRun("var root = new Object;"
             "root.foo = 0;"
             "root = new Object;");

2085
  SimulateIncrementalMarking();
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113

  // Compile an optimized LStoreNamedField that performs the prepared
  // map transition. This will restart incremental marking and should
  // make sure the root is marked grey again.
  CompileRun("function f(o) {"
             "  o.foo = 0;"
             "}"
             "f(new Object);"
             "f(new Object);"
             "%OptimizeFunctionOnNextCall(f);"
             "f(root);"
             "%DeoptimizeFunction(f);");

  // This bug only triggers with aggressive IC clearing.
  HEAP->AgeInlineCaches();

  // Explicitly request GC to perform final marking step and sweeping.
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);

  Handle<JSObject> root =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Object>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("root"))));

  // The root object should be in a sane state.
  CHECK(root->IsJSObject());
  CHECK(root->map()->IsMap());
}
2114 2115 2116 2117


TEST(ReleaseOverReservedPages) {
  i::FLAG_trace_gc = true;
2118 2119 2120
  // The optimizer can allocate stuff, messing up the test.
  i::FLAG_crankshaft = false;
  i::FLAG_always_opt = false;
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137
  InitializeVM();
  v8::HandleScope scope;
  static const int number_of_test_pages = 20;

  // Prepare many pages with low live-bytes count.
  PagedSpace* old_pointer_space = HEAP->old_pointer_space();
  CHECK_EQ(1, old_pointer_space->CountTotalPages());
  for (int i = 0; i < number_of_test_pages; i++) {
    AlwaysAllocateScope always_allocate;
    SimulateFullSpace(old_pointer_space);
    FACTORY->NewFixedArray(1, TENURED);
  }
  CHECK_EQ(number_of_test_pages + 1, old_pointer_space->CountTotalPages());

  // Triggering one GC will cause a lot of garbage to be discovered but
  // even spread across all allocated pages.
  HEAP->CollectAllGarbage(Heap::kNoGCFlags, "triggered for preparation");
2138
  CHECK_GE(number_of_test_pages + 1, old_pointer_space->CountTotalPages());
2139 2140 2141 2142 2143 2144 2145 2146

  // Triggering subsequent GCs should cause at least half of the pages
  // to be released to the OS after at most two cycles.
  HEAP->CollectAllGarbage(Heap::kNoGCFlags, "triggered by test 1");
  CHECK_GE(number_of_test_pages + 1, old_pointer_space->CountTotalPages());
  HEAP->CollectAllGarbage(Heap::kNoGCFlags, "triggered by test 2");
  CHECK_GE(number_of_test_pages + 1, old_pointer_space->CountTotalPages() * 2);

2147 2148 2149 2150 2151 2152 2153
  // Triggering a last-resort GC should cause all pages to be released to the
  // OS so that other processes can seize the memory.  If we get a failure here
  // where there are 2 pages left instead of 1, then we should increase the
  // size of the first page a little in SizeOfFirstPage in spaces.cc.  The
  // first page should be small in order to reduce memory used when the VM
  // boots, but if the 20 small arrays don't fit on the first page then that's
  // an indication that it is too small.
2154 2155 2156
  HEAP->CollectAllAvailableGarbage("triggered really hard");
  CHECK_EQ(1, old_pointer_space->CountTotalPages());
}
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168


TEST(Regress2237) {
  InitializeVM();
  v8::HandleScope scope;
  Handle<String> slice(HEAP->empty_string());

  {
    // Generate a parent that lives in new-space.
    v8::HandleScope inner_scope;
    const char* c = "This text is long enough to trigger sliced strings.";
    Handle<String> s = FACTORY->NewStringFromAscii(CStrVector(c));
2169
    CHECK(s->IsSeqOneByteString());
2170 2171 2172 2173
    CHECK(HEAP->InNewSpace(*s));

    // Generate a sliced string that is based on the above parent and
    // lives in old-space.
2174
    SimulateFullSpace(HEAP->new_space());
2175
    AlwaysAllocateScope always_allocate;
2176
    Handle<String> t = FACTORY->NewProperSubString(s, 5, 35);
2177 2178 2179 2180 2181
    CHECK(t->IsSlicedString());
    CHECK(!HEAP->InNewSpace(*t));
    *slice.location() = *t.location();
  }

2182
  CHECK(SlicedString::cast(*slice)->parent()->IsSeqOneByteString());
2183
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
2184
  CHECK(SlicedString::cast(*slice)->parent()->IsSeqOneByteString());
2185
}
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203


#ifdef OBJECT_PRINT
TEST(PrintSharedFunctionInfo) {
  InitializeVM();
  v8::HandleScope scope;
  const char* source = "f = function() { return 987654321; }\n"
                       "g = function() { return 123456789; }\n";
  CompileRun(source);
  Handle<JSFunction> g =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Function>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("g"))));

  AssertNoAllocation no_alloc;
  g->shared()->PrintLn();
}
#endif  // OBJECT_PRINT
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236


TEST(Regress2211) {
  InitializeVM();
  v8::HandleScope scope;

  v8::Handle<v8::String> value = v8_str("val string");
  Smi* hash = Smi::FromInt(321);
  Heap* heap = Isolate::Current()->heap();

  for (int i = 0; i < 2; i++) {
    // Store identity hash first and common hidden property second.
    v8::Handle<v8::Object> obj = v8::Object::New();
    Handle<JSObject> internal_obj = v8::Utils::OpenHandle(*obj);
    CHECK(internal_obj->HasFastProperties());

    // In the first iteration, set hidden value first and identity hash second.
    // In the second iteration, reverse the order.
    if (i == 0) obj->SetHiddenValue(v8_str("key string"), value);
    MaybeObject* maybe_obj = internal_obj->SetIdentityHash(hash,
                                                           ALLOW_CREATION);
    CHECK(!maybe_obj->IsFailure());
    if (i == 1) obj->SetHiddenValue(v8_str("key string"), value);

    // Check values.
    CHECK_EQ(hash,
             internal_obj->GetHiddenProperty(heap->identity_hash_symbol()));
    CHECK(value->Equals(obj->GetHiddenValue(v8_str("key string"))));

    // Check size.
    DescriptorArray* descriptors = internal_obj->map()->instance_descriptors();
    ObjectHashTable* hashtable = ObjectHashTable::cast(
        internal_obj->FastPropertyAt(descriptors->GetFieldIndex(0)));
2237 2238
    // HashTable header (5) and 4 initial entries (8).
    CHECK_LE(hashtable->SizeFor(hashtable->length()), 13 * kPointerSize);
2239 2240
  }
}
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261


TEST(IncrementalMarkingClearsTypeFeedbackCells) {
  if (i::FLAG_always_opt) return;
  InitializeVM();
  v8::HandleScope scope;
  v8::Local<v8::Value> fun1, fun2;

  {
    LocalContext env;
    CompileRun("function fun() {};");
    fun1 = env->Global()->Get(v8_str("fun"));
  }

  {
    LocalContext env;
    CompileRun("function fun() {};");
    fun2 = env->Global()->Get(v8_str("fun"));
  }

  // Prepare function f that contains type feedback for closures
2262
  // originating from two different native contexts.
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
  v8::Context::GetCurrent()->Global()->Set(v8_str("fun1"), fun1);
  v8::Context::GetCurrent()->Global()->Set(v8_str("fun2"), fun2);
  CompileRun("function f(a, b) { a(); b(); } f(fun1, fun2);");
  Handle<JSFunction> f =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Function>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("f"))));
  Handle<TypeFeedbackCells> cells(TypeFeedbackInfo::cast(
      f->shared()->code()->type_feedback_info())->type_feedback_cells());

  CHECK_EQ(2, cells->CellCount());
  CHECK(cells->Cell(0)->value()->IsJSFunction());
  CHECK(cells->Cell(1)->value()->IsJSFunction());

2277
  SimulateIncrementalMarking();
2278 2279 2280 2281 2282 2283
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);

  CHECK_EQ(2, cells->CellCount());
  CHECK(cells->Cell(0)->value()->IsTheHole());
  CHECK(cells->Cell(1)->value()->IsTheHole());
}
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307


static Code* FindFirstIC(Code* code, Code::Kind kind) {
  int mask = RelocInfo::ModeMask(RelocInfo::CODE_TARGET) |
             RelocInfo::ModeMask(RelocInfo::CONSTRUCT_CALL) |
             RelocInfo::ModeMask(RelocInfo::CODE_TARGET_WITH_ID) |
             RelocInfo::ModeMask(RelocInfo::CODE_TARGET_CONTEXT);
  for (RelocIterator it(code, mask); !it.done(); it.next()) {
    RelocInfo* info = it.rinfo();
    Code* target = Code::GetCodeFromTargetAddress(info->target_address());
    if (target->is_inline_cache_stub() && target->kind() == kind) {
      return target;
    }
  }
  return NULL;
}


TEST(IncrementalMarkingPreservesMonomorhpicIC) {
  if (i::FLAG_always_opt) return;
  InitializeVM();
  v8::HandleScope scope;

  // Prepare function f that contains a monomorphic IC for object
2308
  // originating from the same native context.
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
  CompileRun("function fun() { this.x = 1; }; var obj = new fun();"
             "function f(o) { return o.x; } f(obj); f(obj);");
  Handle<JSFunction> f =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Function>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("f"))));

  Code* ic_before = FindFirstIC(f->shared()->code(), Code::LOAD_IC);
  CHECK(ic_before->ic_state() == MONOMORPHIC);

2319
  SimulateIncrementalMarking();
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);

  Code* ic_after = FindFirstIC(f->shared()->code(), Code::LOAD_IC);
  CHECK(ic_after->ic_state() == MONOMORPHIC);
}


TEST(IncrementalMarkingClearsMonomorhpicIC) {
  if (i::FLAG_always_opt) return;
  InitializeVM();
  v8::HandleScope scope;
  v8::Local<v8::Value> obj1;

  {
    LocalContext env;
    CompileRun("function fun() { this.x = 1; }; var obj = new fun();");
    obj1 = env->Global()->Get(v8_str("obj"));
  }

  // Prepare function f that contains a monomorphic IC for object
2340
  // originating from a different native context.
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352
  v8::Context::GetCurrent()->Global()->Set(v8_str("obj1"), obj1);
  CompileRun("function f(o) { return o.x; } f(obj1); f(obj1);");
  Handle<JSFunction> f =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Function>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("f"))));

  Code* ic_before = FindFirstIC(f->shared()->code(), Code::LOAD_IC);
  CHECK(ic_before->ic_state() == MONOMORPHIC);

  // Fire context dispose notification.
  v8::V8::ContextDisposedNotification();
2353
  SimulateIncrementalMarking();
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);

  Code* ic_after = FindFirstIC(f->shared()->code(), Code::LOAD_IC);
  CHECK(ic_after->ic_state() == UNINITIALIZED);
}


TEST(IncrementalMarkingClearsPolymorhpicIC) {
  if (i::FLAG_always_opt) return;
  InitializeVM();
  v8::HandleScope scope;
  v8::Local<v8::Value> obj1, obj2;

  {
    LocalContext env;
    CompileRun("function fun() { this.x = 1; }; var obj = new fun();");
    obj1 = env->Global()->Get(v8_str("obj"));
  }

  {
    LocalContext env;
    CompileRun("function fun() { this.x = 2; }; var obj = new fun();");
    obj2 = env->Global()->Get(v8_str("obj"));
  }

  // Prepare function f that contains a polymorphic IC for objects
2380
  // originating from two different native contexts.
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
  v8::Context::GetCurrent()->Global()->Set(v8_str("obj1"), obj1);
  v8::Context::GetCurrent()->Global()->Set(v8_str("obj2"), obj2);
  CompileRun("function f(o) { return o.x; } f(obj1); f(obj1); f(obj2);");
  Handle<JSFunction> f =
      v8::Utils::OpenHandle(
          *v8::Handle<v8::Function>::Cast(
              v8::Context::GetCurrent()->Global()->Get(v8_str("f"))));

  Code* ic_before = FindFirstIC(f->shared()->code(), Code::LOAD_IC);
  CHECK(ic_before->ic_state() == MEGAMORPHIC);

  // Fire context dispose notification.
  v8::V8::ContextDisposedNotification();
2394
  SimulateIncrementalMarking();
2395 2396 2397 2398 2399
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);

  Code* ic_after = FindFirstIC(f->shared()->code(), Code::LOAD_IC);
  CHECK(ic_after->ic_state() == UNINITIALIZED);
}
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423


class SourceResource: public v8::String::ExternalAsciiStringResource {
 public:
  explicit SourceResource(const char* data)
    : data_(data), length_(strlen(data)) { }

  virtual void Dispose() {
    i::DeleteArray(data_);
    data_ = NULL;
  }

  const char* data() const { return data_; }

  size_t length() const { return length_; }

  bool IsDisposed() { return data_ == NULL; }

 private:
  const char* data_;
  size_t length_;
};


2424
void ReleaseStackTraceDataTest(const char* source) {
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
  // Test that the data retained by the Error.stack accessor is released
  // after the first time the accessor is fired.  We use external string
  // to check whether the data is being released since the external string
  // resource's callback is fired when the external string is GC'ed.
  InitializeVM();
  v8::HandleScope scope;
  SourceResource* resource = new SourceResource(i::StrDup(source));
  {
    v8::HandleScope scope;
    v8::Handle<v8::String> source_string = v8::String::NewExternal(resource);
    v8::Script::Compile(source_string)->Run();
    CHECK(!resource->IsDisposed());
  }
  HEAP->CollectAllAvailableGarbage();

  // External source has been released.
  CHECK(resource->IsDisposed());
  delete resource;
}
2444 2445


2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
TEST(ReleaseStackTraceData) {
  static const char* source1 = "var error = null;            "
  /* Normal Error */           "try {                        "
                               "  throw new Error();         "
                               "} catch (e) {                "
                               "  error = e;                 "
                               "}                            ";
  static const char* source2 = "var error = null;            "
  /* Stack overflow */         "try {                        "
                               "  (function f() { f(); })(); "
                               "} catch (e) {                "
                               "  error = e;                 "
                               "}                            ";
  ReleaseStackTraceDataTest(source1);
  ReleaseStackTraceDataTest(source2);
}


2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
TEST(Regression144230) {
  InitializeVM();
  v8::HandleScope scope;

  // First make sure that the uninitialized CallIC stub is on a single page
  // that will later be selected as an evacuation candidate.
  {
    v8::HandleScope inner_scope;
    AlwaysAllocateScope always_allocate;
    SimulateFullSpace(HEAP->code_space());
    ISOLATE->stub_cache()->ComputeCallInitialize(9, RelocInfo::CODE_TARGET);
  }

  // Second compile a CallIC and execute it once so that it gets patched to
  // the pre-monomorphic stub. These code objects are on yet another page.
  {
    v8::HandleScope inner_scope;
    AlwaysAllocateScope always_allocate;
    SimulateFullSpace(HEAP->code_space());
    CompileRun("var o = { f:function(a,b,c,d,e,f,g,h,i) {}};"
               "function call() { o.f(1,2,3,4,5,6,7,8,9); };"
               "call();");
  }

  // Third we fill up the last page of the code space so that it does not get
  // chosen as an evacuation candidate.
  {
    v8::HandleScope inner_scope;
    AlwaysAllocateScope always_allocate;
    CompileRun("for (var i = 0; i < 2000; i++) {"
               "  eval('function f' + i + '() { return ' + i +'; };' +"
               "       'f' + i + '();');"
               "}");
  }
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);

  // Fourth is the tricky part. Make sure the code containing the CallIC is
  // visited first without clearing the IC. The shared function info is then
  // visited later, causing the CallIC to be cleared.
2503
  Handle<String> name = FACTORY->LookupUtf8Symbol("call");
2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
  Handle<GlobalObject> global(ISOLATE->context()->global_object());
  MaybeObject* maybe_call = global->GetProperty(*name);
  JSFunction* call = JSFunction::cast(maybe_call->ToObjectChecked());
  USE(global->SetProperty(*name, Smi::FromInt(0), NONE, kNonStrictMode));
  ISOLATE->compilation_cache()->Clear();
  call->shared()->set_ic_age(HEAP->global_ic_age() + 1);
  Handle<Object> call_code(call->code());
  Handle<Object> call_function(call);

  // Now we are ready to mess up the heap.
  HEAP->CollectAllGarbage(Heap::kReduceMemoryFootprintMask);

  // Either heap verification caught the problem already or we go kaboom once
  // the CallIC is executed the next time.
  USE(global->SetProperty(*name, *call_function, NONE, kNonStrictMode));
  CompileRun("call();");
}
2521 2522 2523 2524 2525 2526 2527 2528 2529


TEST(Regress159140) {
  i::FLAG_allow_natives_syntax = true;
  i::FLAG_flush_code_incrementally = true;
  InitializeVM();
  v8::HandleScope scope;

  // Perform one initial GC to enable code flushing.
2530
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580

  // Prepare several closures that are all eligible for code flushing
  // because all reachable ones are not optimized. Make sure that the
  // optimized code object is directly reachable through a handle so
  // that it is marked black during incremental marking.
  Handle<Code> code;
  {
    HandleScope inner_scope;
    CompileRun("function h(x) {}"
               "function mkClosure() {"
               "  return function(x) { return x + 1; };"
               "}"
               "var f = mkClosure();"
               "var g = mkClosure();"
               "f(1); f(2);"
               "g(1); g(2);"
               "h(1); h(2);"
               "%OptimizeFunctionOnNextCall(f); f(3);"
               "%OptimizeFunctionOnNextCall(h); h(3);");

    Handle<JSFunction> f =
        v8::Utils::OpenHandle(
            *v8::Handle<v8::Function>::Cast(
                v8::Context::GetCurrent()->Global()->Get(v8_str("f"))));
    CHECK(f->is_compiled());
    CompileRun("f = null;");

    Handle<JSFunction> g =
        v8::Utils::OpenHandle(
            *v8::Handle<v8::Function>::Cast(
                v8::Context::GetCurrent()->Global()->Get(v8_str("g"))));
    CHECK(g->is_compiled());
    const int kAgingThreshold = 6;
    for (int i = 0; i < kAgingThreshold; i++) {
      g->code()->MakeOlder(static_cast<MarkingParity>(i % 2));
    }

    code = inner_scope.CloseAndEscape(Handle<Code>(f->code()));
  }

  // Simulate incremental marking so that the functions are enqueued as
  // code flushing candidates. Then optimize one function. Finally
  // finish the GC to complete code flushing.
  SimulateIncrementalMarking();
  CompileRun("%OptimizeFunctionOnNextCall(g); g(3);");
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);

  // Unoptimized code is missing and the deoptimizer will go ballistic.
  CompileRun("g('bozo');");
}
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625


TEST(Regress165495) {
  i::FLAG_allow_natives_syntax = true;
  i::FLAG_flush_code_incrementally = true;
  InitializeVM();
  v8::HandleScope scope;

  // Perform one initial GC to enable code flushing.
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);

  // Prepare an optimized closure that the optimized code map will get
  // populated. Then age the unoptimized code to trigger code flushing
  // but make sure the optimized code is unreachable.
  {
    HandleScope inner_scope;
    CompileRun("function mkClosure() {"
               "  return function(x) { return x + 1; };"
               "}"
               "var f = mkClosure();"
               "f(1); f(2);"
               "%OptimizeFunctionOnNextCall(f); f(3);");

    Handle<JSFunction> f =
        v8::Utils::OpenHandle(
            *v8::Handle<v8::Function>::Cast(
                v8::Context::GetCurrent()->Global()->Get(v8_str("f"))));
    CHECK(f->is_compiled());
    const int kAgingThreshold = 6;
    for (int i = 0; i < kAgingThreshold; i++) {
      f->shared()->code()->MakeOlder(static_cast<MarkingParity>(i % 2));
    }

    CompileRun("f = null;");
  }

  // Simulate incremental marking so that unoptimized code is flushed
  // even though it still is cached in the optimized code map.
  SimulateIncrementalMarking();
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);

  // Make a new closure that will get code installed from the code map.
  // Unoptimized code is missing and the deoptimizer will go ballistic.
  CompileRun("var g = mkClosure(); g('bozo');");
}
2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696


TEST(Regress169209) {
  i::FLAG_allow_natives_syntax = true;
  i::FLAG_flush_code_incrementally = true;
  InitializeVM();
  v8::HandleScope scope;

  // Perform one initial GC to enable code flushing.
  HEAP->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);

  // Prepare a shared function info eligible for code flushing for which
  // the unoptimized code will be replaced during optimization.
  Handle<SharedFunctionInfo> shared1;
  {
    HandleScope inner_scope;
    CompileRun("function f() { return 'foobar'; }"
               "function g(x) { if (x) f(); }"
               "f();"
               "g(false);"
               "g(false);");

    Handle<JSFunction> f =
        v8::Utils::OpenHandle(
            *v8::Handle<v8::Function>::Cast(
                v8::Context::GetCurrent()->Global()->Get(v8_str("f"))));
    CHECK(f->is_compiled());
    const int kAgingThreshold = 6;
    for (int i = 0; i < kAgingThreshold; i++) {
      f->shared()->code()->MakeOlder(static_cast<MarkingParity>(i % 2));
    }

    shared1 = inner_scope.CloseAndEscape(handle(f->shared(), ISOLATE));
  }

  // Prepare a shared function info eligible for code flushing that will
  // represent the dangling tail of the candidate list.
  Handle<SharedFunctionInfo> shared2;
  {
    HandleScope inner_scope;
    CompileRun("function flushMe() { return 0; }"
               "flushMe(1);");

    Handle<JSFunction> f =
        v8::Utils::OpenHandle(
            *v8::Handle<v8::Function>::Cast(
                v8::Context::GetCurrent()->Global()->Get(v8_str("flushMe"))));
    CHECK(f->is_compiled());
    const int kAgingThreshold = 6;
    for (int i = 0; i < kAgingThreshold; i++) {
      f->shared()->code()->MakeOlder(static_cast<MarkingParity>(i % 2));
    }

    shared2 = inner_scope.CloseAndEscape(handle(f->shared(), ISOLATE));
  }

  // Simulate incremental marking and collect code flushing candidates.
  SimulateIncrementalMarking();
  CHECK(shared1->code()->gc_metadata() != NULL);

  // Optimize function and make sure the unoptimized code is replaced.
#ifdef DEBUG
  FLAG_stop_at = "f";
#endif
  CompileRun("%OptimizeFunctionOnNextCall(g);"
             "g(false);");

  // Finish garbage collection cycle.
  HEAP->CollectAllGarbage(Heap::kNoGCFlags);
  CHECK(shared1->code()->gc_metadata() == NULL);
}