global-handles.cc 33.5 KB
Newer Older
1
// Copyright 2009 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/global-handles.h"
6

7
#include "src/api.h"
marja's avatar
marja committed
8
#include "src/cancelable-task.h"
9
#include "src/objects-inl.h"
10
#include "src/v8.h"
11
#include "src/visitors.h"
12
#include "src/vm-state-inl.h"
13

14 15
namespace v8 {
namespace internal {
16

17
class GlobalHandles::Node {
18
 public:
19 20 21
  // State transition diagram:
  // FREE -> NORMAL <-> WEAK -> PENDING -> NEAR_DEATH -> { NORMAL, WEAK, FREE }
  enum State {
22
    FREE = 0,
23 24 25 26 27
    NORMAL,      // Normal global handle.
    WEAK,        // Flagged as weak but not yet finalized.
    PENDING,     // Has been recognized as only reachable by weak handles.
    NEAR_DEATH,  // Callback has informed the handle is near death.
    NUMBER_OF_NODE_STATES
28
  };
29

30 31
  // Maps handle location (slot) to the containing node.
  static Node* FromLocation(Object** location) {
32
    DCHECK(offsetof(Node, object_) == 0);
33
    return reinterpret_cast<Node*>(location);
34 35
  }

36
  Node() {
37 38
    DCHECK(offsetof(Node, class_id_) == Internals::kNodeClassIdOffset);
    DCHECK(offsetof(Node, flags_) == Internals::kNodeFlagsOffset);
39 40 41
    STATIC_ASSERT(static_cast<int>(NodeState::kMask) ==
                  Internals::kNodeStateMask);
    STATIC_ASSERT(WEAK == Internals::kNodeStateIsWeakValue);
42
    STATIC_ASSERT(PENDING == Internals::kNodeStateIsPendingValue);
43 44 45
    STATIC_ASSERT(NEAR_DEATH == Internals::kNodeStateIsNearDeathValue);
    STATIC_ASSERT(static_cast<int>(IsIndependent::kShift) ==
                  Internals::kNodeIsIndependentShift);
46 47
    STATIC_ASSERT(static_cast<int>(IsActive::kShift) ==
                  Internals::kNodeIsActiveShift);
48
  }
49

50
#ifdef ENABLE_HANDLE_ZAPPING
51 52
  ~Node() {
    // TODO(1428): if it's a weak handle we should have invoked its callback.
53
    // Zap the values for eager trapping.
54
    object_ = reinterpret_cast<Object*>(kGlobalHandleZapValue);
55 56
    class_id_ = v8::HeapProfiler::kPersistentHandleNoClassId;
    index_ = 0;
57
    set_independent(false);
58
    set_active(false);
59
    set_in_new_space_list(false);
60
    parameter_or_next_free_.next_free = NULL;
61
    weak_callback_ = NULL;
62
  }
63
#endif
64

65
  void Initialize(int index, Node** first_free) {
66
    object_ = reinterpret_cast<Object*>(kGlobalHandleZapValue);
67
    index_ = static_cast<uint8_t>(index);
68
    DCHECK(static_cast<int>(index_) == index);
69 70
    set_state(FREE);
    set_in_new_space_list(false);
71 72
    parameter_or_next_free_.next_free = *first_free;
    *first_free = this;
73 74
  }

75
  void Acquire(Object* object) {
76
    DCHECK(state() == FREE);
77 78
    object_ = object;
    class_id_ = v8::HeapProfiler::kPersistentHandleNoClassId;
79
    set_independent(false);
80
    set_active(false);
81
    set_state(NORMAL);
82
    parameter_or_next_free_.parameter = NULL;
83
    weak_callback_ = NULL;
84
    IncreaseBlockUses();
85 86
  }

87 88 89 90 91 92
  void Zap() {
    DCHECK(IsInUse());
    // Zap the values for eager trapping.
    object_ = reinterpret_cast<Object*>(kGlobalHandleZapValue);
  }

93
  void Release() {
94
    DCHECK(IsInUse());
95
    set_state(FREE);
96
    // Zap the values for eager trapping.
97
    object_ = reinterpret_cast<Object*>(kGlobalHandleZapValue);
98 99
    class_id_ = v8::HeapProfiler::kPersistentHandleNoClassId;
    set_independent(false);
100
    set_active(false);
101
    weak_callback_ = NULL;
102
    DecreaseBlockUses();
103 104 105 106 107 108 109 110 111 112 113
  }

  // Object slot accessors.
  Object* object() const { return object_; }
  Object** location() { return &object_; }
  Handle<Object> handle() { return Handle<Object>(location()); }

  // Wrapper class ID accessors.
  bool has_wrapper_class_id() const {
    return class_id_ != v8::HeapProfiler::kPersistentHandleNoClassId;
  }
114

115
  uint16_t wrapper_class_id() const { return class_id_; }
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

  // State and flag accessors.

  State state() const {
    return NodeState::decode(flags_);
  }
  void set_state(State state) {
    flags_ = NodeState::update(flags_, state);
  }

  bool is_independent() {
    return IsIndependent::decode(flags_);
  }
  void set_independent(bool v) {
    flags_ = IsIndependent::update(flags_, v);
131 132
  }

133 134 135 136 137 138 139
  bool is_active() {
    return IsActive::decode(flags_);
  }
  void set_active(bool v) {
    flags_ = IsActive::update(flags_, v);
  }

140 141 142 143 144 145
  bool is_in_new_space_list() {
    return IsInNewSpaceList::decode(flags_);
  }
  void set_in_new_space_list(bool v) {
    flags_ = IsInNewSpaceList::update(flags_, v);
  }
146

147 148
  WeaknessType weakness_type() const {
    return NodeWeaknessType::decode(flags_);
149
  }
150 151
  void set_weakness_type(WeaknessType weakness_type) {
    flags_ = NodeWeaknessType::update(flags_, weakness_type);
152 153
  }

154 155
  bool IsNearDeath() const {
    // Check for PENDING to ensure correct answer when processing callbacks.
156
    return state() == PENDING || state() == NEAR_DEATH;
157 158
  }

159
  bool IsWeak() const { return state() == WEAK; }
160

161 162
  bool IsInUse() const { return state() != FREE; }

163 164 165
  bool IsPendingPhantomCallback() const {
    return state() == PENDING &&
           (weakness_type() == PHANTOM_WEAK ||
166
            weakness_type() == PHANTOM_WEAK_2_EMBEDDER_FIELDS);
167 168 169 170 171 172
  }

  bool IsPendingPhantomResetHandle() const {
    return state() == PENDING && weakness_type() == PHANTOM_WEAK_RESET_HANDLE;
  }

173 174
  bool IsRetainer() const {
    return state() != FREE &&
175
           !(state() == NEAR_DEATH && weakness_type() != FINALIZER_WEAK);
176
  }
177

178
  bool IsStrongRetainer() const { return state() == NORMAL; }
179 180

  bool IsWeakRetainer() const {
181
    return state() == WEAK || state() == PENDING ||
182
           (state() == NEAR_DEATH && weakness_type() == FINALIZER_WEAK);
183 184
  }

185
  void MarkPending() {
186
    DCHECK(state() == WEAK);
187
    set_state(PENDING);
188 189 190 191
  }

  // Independent flag accessors.
  void MarkIndependent() {
192
    DCHECK(IsInUse());
193
    set_independent(true);
194 195 196 197
  }

  // Callback parameter accessors.
  void set_parameter(void* parameter) {
198
    DCHECK(IsInUse());
199 200 201
    parameter_or_next_free_.parameter = parameter;
  }
  void* parameter() const {
202
    DCHECK(IsInUse());
203 204
    return parameter_or_next_free_.parameter;
  }
205 206 207

  // Accessors for next free node in the free list.
  Node* next_free() {
208
    DCHECK(state() == FREE);
209 210 211
    return parameter_or_next_free_.next_free;
  }
  void set_next_free(Node* value) {
212
    DCHECK(state() == FREE);
213 214 215
    parameter_or_next_free_.next_free = value;
  }

216 217 218 219
  void MakeWeak(void* parameter,
                WeakCallbackInfo<void>::Callback phantom_callback,
                v8::WeakCallbackType type) {
    DCHECK(phantom_callback != nullptr);
220
    DCHECK(IsInUse());
221
    CHECK_NE(object_, reinterpret_cast<Object*>(kGlobalHandleZapValue));
222
    set_state(WEAK);
223 224 225 226 227
    switch (type) {
      case v8::WeakCallbackType::kParameter:
        set_weakness_type(PHANTOM_WEAK);
        break;
      case v8::WeakCallbackType::kInternalFields:
228
        set_weakness_type(PHANTOM_WEAK_2_EMBEDDER_FIELDS);
229 230
        break;
      case v8::WeakCallbackType::kFinalizer:
231
        set_weakness_type(FINALIZER_WEAK);
232
        break;
233
    }
234
    set_parameter(parameter);
235
    weak_callback_ = phantom_callback;
236 237
  }

238 239 240 241 242 243 244 245 246
  void MakeWeak(Object*** location_addr) {
    DCHECK(IsInUse());
    CHECK_NE(object_, reinterpret_cast<Object*>(kGlobalHandleZapValue));
    set_state(WEAK);
    set_weakness_type(PHANTOM_WEAK_RESET_HANDLE);
    set_parameter(location_addr);
    weak_callback_ = nullptr;
  }

247
  void* ClearWeakness() {
248
    DCHECK(IsInUse());
249
    void* p = parameter();
250
    set_state(NORMAL);
251
    set_parameter(NULL);
252
    return p;
253 254
  }

255
  void CollectPhantomCallbackData(
256 257
      Isolate* isolate,
      List<PendingPhantomCallback>* pending_phantom_callbacks) {
258
    DCHECK(weakness_type() == PHANTOM_WEAK ||
259
           weakness_type() == PHANTOM_WEAK_2_EMBEDDER_FIELDS);
260
    DCHECK(state() == PENDING);
261
    DCHECK(weak_callback_ != nullptr);
262

263
    void* embedder_fields[v8::kEmbedderFieldsInWeakCallback] = {nullptr,
264 265 266
                                                                nullptr};
    if (weakness_type() != PHANTOM_WEAK && object()->IsJSObject()) {
      auto jsobject = JSObject::cast(object());
267 268
      int field_count = jsobject->GetEmbedderFieldCount();
      for (int i = 0; i < v8::kEmbedderFieldsInWeakCallback; ++i) {
269
        if (field_count == i) break;
270 271
        auto field = jsobject->GetEmbedderField(i);
        if (field->IsSmi()) embedder_fields[i] = field;
272
      }
273
    }
274

275 276
    // Zap with something dangerous.
    *location() = reinterpret_cast<Object*>(0x6057ca11);
277

278 279 280
    typedef v8::WeakCallbackInfo<void> Data;
    auto callback = reinterpret_cast<Data::Callback>(weak_callback_);
    pending_phantom_callbacks->Add(
281
        PendingPhantomCallback(this, callback, parameter(), embedder_fields));
282 283
    DCHECK(IsInUse());
    set_state(NEAR_DEATH);
284 285
  }

286 287 288 289 290 291 292 293 294
  void ResetPhantomHandle() {
    DCHECK(weakness_type() == PHANTOM_WEAK_RESET_HANDLE);
    DCHECK(state() == PENDING);
    DCHECK(weak_callback_ == nullptr);
    Object*** handle = reinterpret_cast<Object***>(parameter());
    *handle = nullptr;
    Release();
  }

295
  bool PostGarbageCollectionProcessing(Isolate* isolate) {
296
    // Handles only weak handles (not phantom) that are dying.
297
    if (state() != Node::PENDING) return false;
298
    if (weak_callback_ == NULL) {
299
      Release();
300 301
      return false;
    }
302
    set_state(NEAR_DEATH);
303

304 305 306 307 308 309
    // Check that we are not passing a finalized external string to
    // the callback.
    DCHECK(!object_->IsExternalOneByteString() ||
           ExternalOneByteString::cast(object_)->resource() != NULL);
    DCHECK(!object_->IsExternalTwoByteString() ||
           ExternalTwoByteString::cast(object_)->resource() != NULL);
310
    if (weakness_type() != FINALIZER_WEAK) {
311 312
      return false;
    }
313

314 315 316
    // Leaving V8.
    VMState<EXTERNAL> vmstate(isolate);
    HandleScope handle_scope(isolate);
317
    void* embedder_fields[v8::kEmbedderFieldsInWeakCallback] = {nullptr,
318 319
                                                                nullptr};
    v8::WeakCallbackInfo<void> data(reinterpret_cast<v8::Isolate*>(isolate),
320
                                    parameter(), embedder_fields, nullptr);
321
    weak_callback_(data);
322

323
    // Absence of explicit cleanup or revival of weak handle
324
    // in most of the cases would lead to memory leak.
325
    CHECK(state() != NEAR_DEATH);
326
    return true;
327 328
  }

329 330
  inline GlobalHandles* GetGlobalHandles();

331 332
 private:
  inline NodeBlock* FindBlock();
333 334
  inline void IncreaseBlockUses();
  inline void DecreaseBlockUses();
335 336 337 338

  // Storage for object pointer.
  // Placed first to avoid offset computation.
  Object* object_;
339

340 341 342 343
  // Next word stores class_id, index, state, and independent.
  // Note: the most aligned fields should go first.

  // Wrapper class ID.
344 345
  uint16_t class_id_;

346 347 348
  // Index in the containing handle block.
  uint8_t index_;

349 350
  // This stores three flags (independent, partially_dependent and
  // in_new_space_list) and a State.
351 352
  class NodeState : public BitField<State, 0, 3> {};
  class IsIndependent : public BitField<bool, 3, 1> {};
353 354
  // The following two fields are mutually exclusive
  class IsActive : public BitField<bool, 4, 1> {};
355 356
  class IsInNewSpaceList : public BitField<bool, 5, 1> {};
  class NodeWeaknessType : public BitField<WeaknessType, 6, 2> {};
357

358
  uint8_t flags_;
359

360
  // Handle specific callback - might be a weak reference in disguise.
361
  WeakCallbackInfo<void>::Callback weak_callback_;
362 363

  // Provided data for callback.  In FREE state, this is used for
364 365 366 367 368 369
  // the free list link.
  union {
    void* parameter;
    Node* next_free;
  } parameter_or_next_free_;

370 371 372
  DISALLOW_COPY_AND_ASSIGN(Node);
};

373

374
class GlobalHandles::NodeBlock {
375 376 377
 public:
  static const int kSize = 256;

378 379 380 381 382 383 384 385
  explicit NodeBlock(GlobalHandles* global_handles, NodeBlock* next)
      : next_(next),
        used_nodes_(0),
        next_used_(NULL),
        prev_used_(NULL),
        global_handles_(global_handles) {}

  void PutNodesOnFreeList(Node** first_free) {
386 387
    for (int i = kSize - 1; i >= 0; --i) {
      nodes_[i].Initialize(i, first_free);
388
    }
389
  }
390

391
  Node* node_at(int index) {
392
    DCHECK(0 <= index && index < kSize);
393 394 395 396
    return &nodes_[index];
  }

  void IncreaseUses() {
397
    DCHECK(used_nodes_ < kSize);
398 399 400 401 402 403 404
    if (used_nodes_++ == 0) {
      NodeBlock* old_first = global_handles_->first_used_block_;
      global_handles_->first_used_block_ = this;
      next_used_ = old_first;
      prev_used_ = NULL;
      if (old_first == NULL) return;
      old_first->prev_used_ = this;
405
    }
406
  }
407

408
  void DecreaseUses() {
409
    DCHECK(used_nodes_ > 0);
410 411 412 413 414 415
    if (--used_nodes_ == 0) {
      if (next_used_ != NULL) next_used_->prev_used_ = prev_used_;
      if (prev_used_ != NULL) prev_used_->next_used_ = next_used_;
      if (this == global_handles_->first_used_block_) {
        global_handles_->first_used_block_ = next_used_;
      }
416
    }
417
  }
418

419 420
  GlobalHandles* global_handles() { return global_handles_; }

421 422
  // Next block in the list of all blocks.
  NodeBlock* next() const { return next_; }
423

424 425 426
  // Next/previous block in the list of blocks with used nodes.
  NodeBlock* next_used() const { return next_used_; }
  NodeBlock* prev_used() const { return prev_used_; }
427

428 429
 private:
  Node nodes_[kSize];
430 431 432 433
  NodeBlock* const next_;
  int used_nodes_;
  NodeBlock* next_used_;
  NodeBlock* prev_used_;
434
  GlobalHandles* global_handles_;
435 436 437
};


438 439
GlobalHandles* GlobalHandles::Node::GetGlobalHandles() {
  return FindBlock()->global_handles();
440 441 442
}


443
GlobalHandles::NodeBlock* GlobalHandles::Node::FindBlock() {
444 445 446
  intptr_t ptr = reinterpret_cast<intptr_t>(this);
  ptr = ptr - index_ * sizeof(Node);
  NodeBlock* block = reinterpret_cast<NodeBlock*>(ptr);
447
  DCHECK(block->node_at(index_) == this);
448 449 450 451 452 453 454 455 456 457
  return block;
}


void GlobalHandles::Node::IncreaseBlockUses() {
  NodeBlock* node_block = FindBlock();
  node_block->IncreaseUses();
  GlobalHandles* global_handles = node_block->global_handles();
  global_handles->isolate()->counters()->global_handles()->Increment();
  global_handles->number_of_global_handles_++;
458 459 460
}


461 462 463 464 465 466 467 468
void GlobalHandles::Node::DecreaseBlockUses() {
  NodeBlock* node_block = FindBlock();
  GlobalHandles* global_handles = node_block->global_handles();
  parameter_or_next_free_.next_free = global_handles->first_free_;
  global_handles->first_free_ = this;
  node_block->DecreaseUses();
  global_handles->isolate()->counters()->global_handles()->Decrement();
  global_handles->number_of_global_handles_--;
469 470 471 472 473 474
}


class GlobalHandles::NodeIterator {
 public:
  explicit NodeIterator(GlobalHandles* global_handles)
475 476
      : block_(global_handles->first_used_block_),
        index_(0) {}
477

478
  bool done() const { return block_ == NULL; }
479 480

  Node* node() const {
481
    DCHECK(!done());
482
    return block_->node_at(index_);
483 484 485
  }

  void Advance() {
486
    DCHECK(!done());
487 488 489
    if (++index_ < NodeBlock::kSize) return;
    index_ = 0;
    block_ = block_->next_used();
490 491 492
  }

 private:
493 494
  NodeBlock* block_;
  int index_;
495 496

  DISALLOW_COPY_AND_ASSIGN(NodeIterator);
497 498
};

499 500
class GlobalHandles::PendingPhantomCallbacksSecondPassTask
    : public v8::internal::CancelableTask {
501 502 503 504 505
 public:
  // Takes ownership of the contents of pending_phantom_callbacks, leaving it in
  // the same state it would be after a call to Clear().
  PendingPhantomCallbacksSecondPassTask(
      List<PendingPhantomCallback>* pending_phantom_callbacks, Isolate* isolate)
506
      : CancelableTask(isolate), isolate_(isolate) {
507 508 509
    pending_phantom_callbacks_.Swap(pending_phantom_callbacks);
  }

510
  void RunInternal() override {
511
    TRACE_EVENT0("v8", "V8.GCPhantomHandleProcessingCallback");
512
    isolate()->heap()->CallGCPrologueCallbacks(
513
        GCType::kGCTypeProcessWeakCallbacks, kNoGCCallbackFlags);
514 515
    InvokeSecondPassPhantomCallbacks(&pending_phantom_callbacks_, isolate());
    isolate()->heap()->CallGCEpilogueCallbacks(
516
        GCType::kGCTypeProcessWeakCallbacks, kNoGCCallbackFlags);
517 518
  }

519 520
  Isolate* isolate() { return isolate_; }

521
 private:
522
  Isolate* isolate_;
523 524 525 526 527
  List<PendingPhantomCallback> pending_phantom_callbacks_;

  DISALLOW_COPY_AND_ASSIGN(PendingPhantomCallbacksSecondPassTask);
};

528 529
GlobalHandles::GlobalHandles(Isolate* isolate)
    : isolate_(isolate),
530
      number_of_global_handles_(0),
531 532 533
      first_block_(NULL),
      first_used_block_(NULL),
      first_free_(NULL),
534
      post_gc_processing_count_(0),
535
      number_of_phantom_handle_resets_(0) {}
536 537

GlobalHandles::~GlobalHandles() {
538 539 540 541 542
  NodeBlock* block = first_block_;
  while (block != NULL) {
    NodeBlock* tmp = block->next();
    delete block;
    block = tmp;
543
  }
544
  first_block_ = NULL;
545
}
546 547


548
Handle<Object> GlobalHandles::Create(Object* value) {
549 550 551 552
  if (first_free_ == NULL) {
    first_block_ = new NodeBlock(this, first_block_);
    first_block_->PutNodesOnFreeList(&first_free_);
  }
553
  DCHECK(first_free_ != NULL);
554 555 556 557
  // Take the first node in the free list.
  Node* result = first_free_;
  first_free_ = result->next_free();
  result->Acquire(value);
558 559 560 561
  if (isolate_->heap()->InNewSpace(value) &&
      !result->is_in_new_space_list()) {
    new_space_nodes_.Add(result);
    result->set_in_new_space_list(true);
562 563 564 565 566
  }
  return result->handle();
}


567
Handle<Object> GlobalHandles::CopyGlobal(Object** location) {
568
  DCHECK(location != NULL);
569 570 571 572
  return Node::FromLocation(location)->GetGlobalHandles()->Create(*location);
}


573
void GlobalHandles::Destroy(Object** location) {
574
  if (location != NULL) Node::FromLocation(location)->Release();
575 576 577
}


578
typedef v8::WeakCallbackInfo<void>::Callback GenericCallback;
579 580


581 582 583 584
void GlobalHandles::MakeWeak(Object** location, void* parameter,
                             GenericCallback phantom_callback,
                             v8::WeakCallbackType type) {
  Node::FromLocation(location)->MakeWeak(parameter, phantom_callback, type);
585 586
}

587 588 589
void GlobalHandles::MakeWeak(Object*** location_addr) {
  Node::FromLocation(*location_addr)->MakeWeak(location_addr);
}
590

591 592
void* GlobalHandles::ClearWeakness(Object** location) {
  return Node::FromLocation(location)->ClearWeakness();
593 594 595
}


596
void GlobalHandles::MarkIndependent(Object** location) {
597
  Node::FromLocation(location)->MarkIndependent();
598 599
}

600 601 602 603 604
bool GlobalHandles::IsIndependent(Object** location) {
  return Node::FromLocation(location)->is_independent();
}


605 606 607 608 609 610 611 612 613
bool GlobalHandles::IsNearDeath(Object** location) {
  return Node::FromLocation(location)->IsNearDeath();
}


bool GlobalHandles::IsWeak(Object** location) {
  return Node::FromLocation(location)->IsWeak();
}

krasin's avatar
krasin committed
614
DISABLE_CFI_PERF
615
void GlobalHandles::IterateWeakRoots(RootVisitor* v) {
616
  for (NodeIterator it(this); !it.done(); it.Advance()) {
617 618
    Node* node = it.node();
    if (node->IsWeakRetainer()) {
619
      // Pending weak phantom handles die immediately. Everything else survives.
620 621 622 623
      if (node->IsPendingPhantomResetHandle()) {
        node->ResetPhantomHandle();
        ++number_of_phantom_handle_resets_;
      } else if (node->IsPendingPhantomCallback()) {
624 625
        node->CollectPhantomCallbackData(isolate(),
                                         &pending_phantom_callbacks_);
626
      } else {
627
        v->VisitRootPointer(Root::kGlobalHandles, node->location());
628 629
      }
    }
630 631 632 633
  }
}


634
void GlobalHandles::IdentifyWeakHandles(WeakSlotCallback f) {
635 636 637
  for (NodeIterator it(this); !it.done(); it.Advance()) {
    if (it.node()->IsWeak() && f(it.node()->location())) {
      it.node()->MarkPending();
638 639 640 641
    }
  }
}

642
void GlobalHandles::IterateNewSpaceStrongAndDependentRoots(RootVisitor* v) {
643 644
  for (int i = 0; i < new_space_nodes_.length(); ++i) {
    Node* node = new_space_nodes_[i];
645 646 647
    if (node->IsStrongRetainer() ||
        (node->IsWeakRetainer() && !node->is_independent() &&
         node->is_active())) {
648
      v->VisitRootPointer(Root::kGlobalHandles, node->location());
649 650 651 652
    }
  }
}

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
void GlobalHandles::IterateNewSpaceStrongAndDependentRootsAndIdentifyUnmodified(
    RootVisitor* v, size_t start, size_t end) {
  for (size_t i = start; i < end; ++i) {
    Node* node = new_space_nodes_[static_cast<int>(i)];
    if (node->IsWeak() && !JSObject::IsUnmodifiedApiObject(node->location())) {
      node->set_active(true);
    }
    if (node->IsStrongRetainer() ||
        (node->IsWeakRetainer() && !node->is_independent() &&
         node->is_active())) {
      v->VisitRootPointer(Root::kGlobalHandles, node->location());
    }
  }
}

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
void GlobalHandles::IdentifyWeakUnmodifiedObjects(
    WeakSlotCallback is_unmodified) {
  for (int i = 0; i < new_space_nodes_.length(); ++i) {
    Node* node = new_space_nodes_[i];
    if (node->IsWeak() && !is_unmodified(node->location())) {
      node->set_active(true);
    }
  }
}


void GlobalHandles::MarkNewSpaceWeakUnmodifiedObjectsPending(
    WeakSlotCallbackWithHeap is_unscavenged) {
  for (int i = 0; i < new_space_nodes_.length(); ++i) {
    Node* node = new_space_nodes_[i];
    DCHECK(node->is_in_new_space_list());
    if ((node->is_independent() || !node->is_active()) && node->IsWeak() &&
        is_unscavenged(isolate_->heap(), node->location())) {
      node->MarkPending();
    }
  }
}

691
void GlobalHandles::IterateNewSpaceWeakUnmodifiedRoots(RootVisitor* v) {
692 693 694 695 696 697
  for (int i = 0; i < new_space_nodes_.length(); ++i) {
    Node* node = new_space_nodes_[i];
    DCHECK(node->is_in_new_space_list());
    if ((node->is_independent() || !node->is_active()) &&
        node->IsWeakRetainer()) {
      // Pending weak phantom handles die immediately. Everything else survives.
698
      if (node->IsPendingPhantomResetHandle()) {
699 700
        node->ResetPhantomHandle();
        ++number_of_phantom_handle_resets_;
701
      } else if (node->IsPendingPhantomCallback()) {
702 703
        node->CollectPhantomCallbackData(isolate(),
                                         &pending_phantom_callbacks_);
704
      } else {
705
        v->VisitRootPointer(Root::kGlobalHandles, node->location());
706 707 708 709 710
      }
    }
  }
}

711 712 713 714 715 716 717 718 719 720 721
void GlobalHandles::InvokeSecondPassPhantomCallbacks(
    List<PendingPhantomCallback>* callbacks, Isolate* isolate) {
  while (callbacks->length() != 0) {
    auto callback = callbacks->RemoveLast();
    DCHECK(callback.node() == nullptr);
    // Fire second pass callback
    callback.Invoke(isolate);
  }
}


722 723
int GlobalHandles::PostScavengeProcessing(
    const int initial_post_gc_processing_count) {
724
  int freed_nodes = 0;
725 726 727 728 729 730 731
  for (int i = 0; i < new_space_nodes_.length(); ++i) {
    Node* node = new_space_nodes_[i];
    DCHECK(node->is_in_new_space_list());
    if (!node->IsRetainer()) {
      // Free nodes do not have weak callbacks. Do not use them to compute
      // the freed_nodes.
      continue;
732
    }
733 734
    // Skip dependent or unmodified handles. Their weak callbacks might expect
    // to be
735 736
    // called between two global garbage collection callbacks which
    // are not called for minor collections.
737 738 739 740 741 742
      if (!node->is_independent() && (node->is_active())) {
        node->set_active(false);
        continue;
      }
      node->set_active(false);

743 744 745 746 747 748 749
    if (node->PostGarbageCollectionProcessing(isolate_)) {
      if (initial_post_gc_processing_count != post_gc_processing_count_) {
        // Weak callback triggered another GC and another round of
        // PostGarbageCollection processing.  The current node might
        // have been deleted in that round, so we need to bail out (or
        // restart the processing).
        return freed_nodes;
750
      }
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    }
    if (!node->IsRetainer()) {
      freed_nodes++;
    }
  }
  return freed_nodes;
}


int GlobalHandles::PostMarkSweepProcessing(
    const int initial_post_gc_processing_count) {
  int freed_nodes = 0;
  for (NodeIterator it(this); !it.done(); it.Advance()) {
    if (!it.node()->IsRetainer()) {
      // Free nodes do not have weak callbacks. Do not use them to compute
      // the freed_nodes.
      continue;
    }
769
    it.node()->set_active(false);
770 771 772 773
    if (it.node()->PostGarbageCollectionProcessing(isolate_)) {
      if (initial_post_gc_processing_count != post_gc_processing_count_) {
        // See the comment above.
        return freed_nodes;
774
      }
775
    }
776 777 778
    if (!it.node()->IsRetainer()) {
      freed_nodes++;
    }
779
  }
780 781 782 783 784
  return freed_nodes;
}


void GlobalHandles::UpdateListOfNewSpaceNodes() {
785 786 787
  int last = 0;
  for (int i = 0; i < new_space_nodes_.length(); ++i) {
    Node* node = new_space_nodes_[i];
788
    DCHECK(node->is_in_new_space_list());
789 790 791
    if (node->IsRetainer()) {
      if (isolate_->heap()->InNewSpace(node->object())) {
        new_space_nodes_[last++] = node;
792
        isolate_->heap()->IncrementNodesCopiedInNewSpace();
793 794
      } else {
        node->set_in_new_space_list(false);
795
        isolate_->heap()->IncrementNodesPromoted();
796
      }
797 798
    } else {
      node->set_in_new_space_list(false);
799
      isolate_->heap()->IncrementNodesDiedInNewSpace();
800
    }
801
  }
802
  new_space_nodes_.Rewind(last);
803
  new_space_nodes_.Trim();
804 805 806
}


807 808
int GlobalHandles::DispatchPendingPhantomCallbacks(
    bool synchronous_second_pass) {
809
  int freed_nodes = 0;
810
  List<PendingPhantomCallback> second_pass_callbacks;
dcarney's avatar
dcarney committed
811 812 813 814 815 816 817 818
  {
    // The initial pass callbacks must simply clear the nodes.
    for (auto i = pending_phantom_callbacks_.begin();
         i != pending_phantom_callbacks_.end(); ++i) {
      auto callback = i;
      // Skip callbacks that have already been processed once.
      if (callback->node() == nullptr) continue;
      callback->Invoke(isolate());
819
      if (callback->callback()) second_pass_callbacks.Add(*callback);
dcarney's avatar
dcarney committed
820 821 822
      freed_nodes++;
    }
  }
823 824
  pending_phantom_callbacks_.Clear();
  if (second_pass_callbacks.length() > 0) {
825
    if (FLAG_optimize_for_size || FLAG_predictable || synchronous_second_pass) {
826 827
      isolate()->heap()->CallGCPrologueCallbacks(
          GCType::kGCTypeProcessWeakCallbacks, kNoGCCallbackFlags);
828
      InvokeSecondPassPhantomCallbacks(&second_pass_callbacks, isolate());
829 830
      isolate()->heap()->CallGCEpilogueCallbacks(
          GCType::kGCTypeProcessWeakCallbacks, kNoGCCallbackFlags);
831
    } else {
832
      auto task = new PendingPhantomCallbacksSecondPassTask(
833
          &second_pass_callbacks, isolate());
834 835 836
      V8::GetCurrentPlatform()->CallOnForegroundThread(
          reinterpret_cast<v8::Isolate*>(isolate()), task);
    }
837 838 839 840 841
  }
  return freed_nodes;
}


dcarney's avatar
dcarney committed
842 843 844 845 846 847 848 849
void GlobalHandles::PendingPhantomCallback::Invoke(Isolate* isolate) {
  Data::Callback* callback_addr = nullptr;
  if (node_ != nullptr) {
    // Initialize for first pass callback.
    DCHECK(node_->state() == Node::NEAR_DEATH);
    callback_addr = &callback_;
  }
  Data data(reinterpret_cast<v8::Isolate*>(isolate), parameter_,
850
            embedder_fields_, callback_addr);
dcarney's avatar
dcarney committed
851 852 853 854 855 856 857 858 859 860 861
  Data::Callback callback = callback_;
  callback_ = nullptr;
  callback(data);
  if (node_ != nullptr) {
    // Transition to second pass state.
    DCHECK(node_->state() == Node::FREE);
    node_ = nullptr;
  }
}


862 863
int GlobalHandles::PostGarbageCollectionProcessing(
    GarbageCollector collector, const v8::GCCallbackFlags gc_callback_flags) {
864 865 866 867 868 869
  // Process weak global handle callbacks. This must be done after the
  // GC is completely done, because the callbacks may invoke arbitrary
  // API functions.
  DCHECK(isolate_->heap()->gc_state() == Heap::NOT_IN_GC);
  const int initial_post_gc_processing_count = ++post_gc_processing_count_;
  int freed_nodes = 0;
870
  bool synchronous_second_pass =
871
      (gc_callback_flags &
872
       (kGCCallbackFlagForced | kGCCallbackFlagCollectAllAvailableGarbage |
873
        kGCCallbackFlagSynchronousPhantomCallbackProcessing)) != 0;
874
  freed_nodes += DispatchPendingPhantomCallbacks(synchronous_second_pass);
875 876 877 878 879
  if (initial_post_gc_processing_count != post_gc_processing_count_) {
    // If the callbacks caused a nested GC, then return.  See comment in
    // PostScavengeProcessing.
    return freed_nodes;
  }
880
  if (Heap::IsYoungGenerationCollector(collector)) {
881
    freed_nodes += PostScavengeProcessing(initial_post_gc_processing_count);
882
  } else {
883
    freed_nodes += PostMarkSweepProcessing(initial_post_gc_processing_count);
884 885 886 887 888 889 890 891 892
  }
  if (initial_post_gc_processing_count != post_gc_processing_count_) {
    // If the callbacks caused a nested GC, then return.  See comment in
    // PostScavengeProcessing.
    return freed_nodes;
  }
  if (initial_post_gc_processing_count == post_gc_processing_count_) {
    UpdateListOfNewSpaceNodes();
  }
893
  return freed_nodes;
894 895
}

896
void GlobalHandles::IterateStrongRoots(RootVisitor* v) {
897 898
  for (NodeIterator it(this); !it.done(); it.Advance()) {
    if (it.node()->IsStrongRetainer()) {
899
      v->VisitRootPointer(Root::kGlobalHandles, it.node()->location());
900 901 902 903
    }
  }
}

904

krasin's avatar
krasin committed
905
DISABLE_CFI_PERF
906
void GlobalHandles::IterateAllRoots(RootVisitor* v) {
907 908
  for (NodeIterator it(this); !it.done(); it.Advance()) {
    if (it.node()->IsRetainer()) {
909
      v->VisitRootPointer(Root::kGlobalHandles, it.node()->location());
910 911 912 913
    }
  }
}

914 915 916 917 918 919 920 921 922
DISABLE_CFI_PERF
void GlobalHandles::IterateAllNewSpaceRoots(RootVisitor* v) {
  for (int i = 0; i < new_space_nodes_.length(); ++i) {
    Node* node = new_space_nodes_[i];
    if (node->IsRetainer()) {
      v->VisitRootPointer(Root::kGlobalHandles, node->location());
    }
  }
}
923

924 925 926 927 928 929 930 931 932 933 934
DISABLE_CFI_PERF
void GlobalHandles::IterateNewSpaceRoots(RootVisitor* v, size_t start,
                                         size_t end) {
  for (size_t i = start; i < end; ++i) {
    Node* node = new_space_nodes_[static_cast<int>(i)];
    if (node->IsRetainer()) {
      v->VisitRootPointer(Root::kGlobalHandles, node->location());
    }
  }
}

krasin's avatar
krasin committed
935
DISABLE_CFI_PERF
936 937 938 939 940 941 942 943 944 945 946
void GlobalHandles::ApplyPersistentHandleVisitor(
    v8::PersistentHandleVisitor* visitor, GlobalHandles::Node* node) {
  v8::Value* value = ToApi<v8::Value>(Handle<Object>(node->location()));
  visitor->VisitPersistentHandle(
      reinterpret_cast<v8::Persistent<v8::Value>*>(&value),
      node->wrapper_class_id());
}

DISABLE_CFI_PERF
void GlobalHandles::IterateAllRootsWithClassIds(
    v8::PersistentHandleVisitor* visitor) {
947
  for (NodeIterator it(this); !it.done(); it.Advance()) {
948
    if (it.node()->IsRetainer() && it.node()->has_wrapper_class_id()) {
949
      ApplyPersistentHandleVisitor(visitor, it.node());
950 951 952 953 954
    }
  }
}


krasin's avatar
krasin committed
955
DISABLE_CFI_PERF
956 957
void GlobalHandles::IterateAllRootsInNewSpaceWithClassIds(
    v8::PersistentHandleVisitor* visitor) {
958 959 960
  for (int i = 0; i < new_space_nodes_.length(); ++i) {
    Node* node = new_space_nodes_[i];
    if (node->IsRetainer() && node->has_wrapper_class_id()) {
961
      ApplyPersistentHandleVisitor(visitor, node);
962 963 964 965 966
    }
  }
}


krasin's avatar
krasin committed
967
DISABLE_CFI_PERF
968 969
void GlobalHandles::IterateWeakRootsInNewSpaceWithClassIds(
    v8::PersistentHandleVisitor* visitor) {
970 971 972
  for (int i = 0; i < new_space_nodes_.length(); ++i) {
    Node* node = new_space_nodes_[i];
    if (node->has_wrapper_class_id() && node->IsWeak()) {
973
      ApplyPersistentHandleVisitor(visitor, node);
974 975 976 977
    }
  }
}

978
void GlobalHandles::RecordStats(HeapStats* stats) {
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
  *stats->global_handle_count = 0;
  *stats->weak_global_handle_count = 0;
  *stats->pending_global_handle_count = 0;
  *stats->near_death_global_handle_count = 0;
  *stats->free_global_handle_count = 0;
  for (NodeIterator it(this); !it.done(); it.Advance()) {
    *stats->global_handle_count += 1;
    if (it.node()->state() == Node::WEAK) {
      *stats->weak_global_handle_count += 1;
    } else if (it.node()->state() == Node::PENDING) {
      *stats->pending_global_handle_count += 1;
    } else if (it.node()->state() == Node::NEAR_DEATH) {
      *stats->near_death_global_handle_count += 1;
    } else if (it.node()->state() == Node::FREE) {
      *stats->free_global_handle_count += 1;
    }
  }
996 997
}

998 999 1000
#ifdef DEBUG

void GlobalHandles::PrintStats() {
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
  int total = 0;
  int weak = 0;
  int pending = 0;
  int near_death = 0;
  int destroyed = 0;

  for (NodeIterator it(this); !it.done(); it.Advance()) {
    total++;
    if (it.node()->state() == Node::WEAK) weak++;
    if (it.node()->state() == Node::PENDING) pending++;
    if (it.node()->state() == Node::NEAR_DEATH) near_death++;
    if (it.node()->state() == Node::FREE) destroyed++;
  }

1015
  PrintF("Global Handle Statistics:\n");
jfb's avatar
jfb committed
1016
  PrintF("  allocated memory = %" PRIuS "B\n", total * sizeof(Node));
1017 1018 1019 1020
  PrintF("  # weak       = %d\n", weak);
  PrintF("  # pending    = %d\n", pending);
  PrintF("  # near_death = %d\n", near_death);
  PrintF("  # free       = %d\n", destroyed);
1021 1022 1023
  PrintF("  # total      = %d\n", total);
}

1024

1025 1026
void GlobalHandles::Print() {
  PrintF("Global handles:\n");
1027 1028 1029 1030 1031
  for (NodeIterator it(this); !it.done(); it.Advance()) {
    PrintF("  handle %p to %p%s\n",
           reinterpret_cast<void*>(it.node()->location()),
           reinterpret_cast<void*>(it.node()->object()),
           it.node()->IsWeak() ? " (weak)" : "");
1032 1033 1034 1035 1036
  }
}

#endif

1037
void GlobalHandles::TearDown() {}
1038

1039
EternalHandles::EternalHandles() : size_(0) {
1040
  for (unsigned i = 0; i < arraysize(singleton_handles_); i++) {
1041 1042 1043 1044 1045 1046
    singleton_handles_[i] = kInvalidIndex;
  }
}


EternalHandles::~EternalHandles() {
1047
  for (int i = 0; i < blocks_.length(); i++) delete[] blocks_[i];
1048 1049
}

1050
void EternalHandles::IterateAllRoots(RootVisitor* visitor) {
1051 1052
  int limit = size_;
  for (int i = 0; i < blocks_.length(); i++) {
1053
    DCHECK(limit > 0);
1054
    Object** block = blocks_[i];
1055 1056
    visitor->VisitRootPointers(Root::kEternalHandles, block,
                               block + Min(limit, kSize));
1057 1058 1059 1060
    limit -= kSize;
  }
}

1061
void EternalHandles::IterateNewSpaceRoots(RootVisitor* visitor) {
1062
  for (int i = 0; i < new_space_indices_.length(); i++) {
1063 1064
    visitor->VisitRootPointer(Root::kEternalHandles,
                              GetLocation(new_space_indices_[i]));
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
  }
}


void EternalHandles::PostGarbageCollectionProcessing(Heap* heap) {
  int last = 0;
  for (int i = 0; i < new_space_indices_.length(); i++) {
    int index = new_space_indices_[i];
    if (heap->InNewSpace(*GetLocation(index))) {
      new_space_indices_[last++] = index;
    }
  }
  new_space_indices_.Rewind(last);
}


1081
void EternalHandles::Create(Isolate* isolate, Object* object, int* index) {
1082
  DCHECK_EQ(kInvalidIndex, *index);
1083
  if (object == NULL) return;
1084
  DCHECK_NE(isolate->heap()->the_hole_value(), object);
1085 1086 1087 1088 1089 1090 1091 1092 1093
  int block = size_ >> kShift;
  int offset = size_ & kMask;
  // need to resize
  if (offset == 0) {
    Object** next_block = new Object*[kSize];
    Object* the_hole = isolate->heap()->the_hole_value();
    MemsetPointer(next_block, the_hole, kSize);
    blocks_.Add(next_block);
  }
1094
  DCHECK_EQ(isolate->heap()->the_hole_value(), blocks_[block][offset]);
1095 1096 1097 1098
  blocks_[block][offset] = object;
  if (isolate->heap()->InNewSpace(object)) {
    new_space_indices_.Add(size_);
  }
1099
  *index = size_++;
1100 1101 1102
}


1103 1104
}  // namespace internal
}  // namespace v8