Home | History | Annotate | Download | only in src
      1 // Copyright 2011 the V8 project authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef V8_HANDLES_H_
      6 #define V8_HANDLES_H_
      7 
      8 #include "include/v8.h"
      9 #include "src/base/functional.h"
     10 #include "src/base/macros.h"
     11 #include "src/checks.h"
     12 #include "src/globals.h"
     13 #include "src/zone/zone.h"
     14 
     15 namespace v8 {
     16 namespace internal {
     17 
     18 // Forward declarations.
     19 class DeferredHandles;
     20 class HandleScopeImplementer;
     21 class Isolate;
     22 class Object;
     23 
     24 
     25 // ----------------------------------------------------------------------------
     26 // Base class for Handle instantiations.  Don't use directly.
     27 class HandleBase {
     28  public:
     29   V8_INLINE explicit HandleBase(Object** location) : location_(location) {}
     30   V8_INLINE explicit HandleBase(Object* object, Isolate* isolate);
     31 
     32   // Check if this handle refers to the exact same object as the other handle.
     33   V8_INLINE bool is_identical_to(const HandleBase that) const {
     34     // Dereferencing deferred handles to check object equality is safe.
     35     SLOW_DCHECK((this->location_ == nullptr ||
     36                  this->IsDereferenceAllowed(NO_DEFERRED_CHECK)) &&
     37                 (that.location_ == nullptr ||
     38                  that.IsDereferenceAllowed(NO_DEFERRED_CHECK)));
     39     if (this->location_ == that.location_) return true;
     40     if (this->location_ == NULL || that.location_ == NULL) return false;
     41     return *this->location_ == *that.location_;
     42   }
     43 
     44   V8_INLINE bool is_null() const { return location_ == nullptr; }
     45 
     46   // Returns the raw address where this handle is stored. This should only be
     47   // used for hashing handles; do not ever try to dereference it.
     48   V8_INLINE Address address() const { return bit_cast<Address>(location_); }
     49 
     50  protected:
     51   // Provides the C++ dereference operator.
     52   V8_INLINE Object* operator*() const {
     53     SLOW_DCHECK(IsDereferenceAllowed(INCLUDE_DEFERRED_CHECK));
     54     return *location_;
     55   }
     56 
     57   // Returns the address to where the raw pointer is stored.
     58   V8_INLINE Object** location() const {
     59     SLOW_DCHECK(location_ == nullptr ||
     60                 IsDereferenceAllowed(INCLUDE_DEFERRED_CHECK));
     61     return location_;
     62   }
     63 
     64   enum DereferenceCheckMode { INCLUDE_DEFERRED_CHECK, NO_DEFERRED_CHECK };
     65 #ifdef DEBUG
     66   bool V8_EXPORT_PRIVATE IsDereferenceAllowed(DereferenceCheckMode mode) const;
     67 #else
     68   V8_INLINE
     69   bool V8_EXPORT_PRIVATE IsDereferenceAllowed(DereferenceCheckMode mode) const {
     70     return true;
     71   }
     72 #endif  // DEBUG
     73 
     74   Object** location_;
     75 };
     76 
     77 
     78 // ----------------------------------------------------------------------------
     79 // A Handle provides a reference to an object that survives relocation by
     80 // the garbage collector.
     81 //
     82 // Handles are only valid within a HandleScope. When a handle is created
     83 // for an object a cell is allocated in the current HandleScope.
     84 //
     85 // Also note that Handles do not provide default equality comparison or hashing
     86 // operators on purpose. Such operators would be misleading, because intended
     87 // semantics is ambiguous between Handle location and object identity. Instead
     88 // use either {is_identical_to} or {location} explicitly.
     89 template <typename T>
     90 class Handle final : public HandleBase {
     91  public:
     92   V8_INLINE explicit Handle(T** location = nullptr)
     93       : HandleBase(reinterpret_cast<Object**>(location)) {
     94     Object* a = nullptr;
     95     T* b = nullptr;
     96     a = b;  // Fake assignment to enforce type checks.
     97     USE(a);
     98   }
     99   V8_INLINE explicit Handle(T* object) : Handle(object, object->GetIsolate()) {}
    100   V8_INLINE Handle(T* object, Isolate* isolate) : HandleBase(object, isolate) {}
    101 
    102   // Allocate a new handle for the object, do not canonicalize.
    103   V8_INLINE static Handle<T> New(T* object, Isolate* isolate);
    104 
    105   // Constructor for handling automatic up casting.
    106   // Ex. Handle<JSFunction> can be passed when Handle<Object> is expected.
    107   template <typename S>
    108   V8_INLINE Handle(Handle<S> handle)
    109       : HandleBase(handle) {
    110     T* a = nullptr;
    111     S* b = nullptr;
    112     a = b;  // Fake assignment to enforce type checks.
    113     USE(a);
    114   }
    115 
    116   V8_INLINE T* operator->() const { return operator*(); }
    117 
    118   // Provides the C++ dereference operator.
    119   V8_INLINE T* operator*() const {
    120     return reinterpret_cast<T*>(HandleBase::operator*());
    121   }
    122 
    123   // Returns the address to where the raw pointer is stored.
    124   V8_INLINE T** location() const {
    125     return reinterpret_cast<T**>(HandleBase::location());
    126   }
    127 
    128   template <typename S>
    129   static const Handle<T> cast(Handle<S> that) {
    130     T::cast(*reinterpret_cast<T**>(that.location_));
    131     return Handle<T>(reinterpret_cast<T**>(that.location_));
    132   }
    133 
    134   // TODO(yangguo): Values that contain empty handles should be declared as
    135   // MaybeHandle to force validation before being used as handles.
    136   static const Handle<T> null() { return Handle<T>(); }
    137 
    138   // Provide function object for location equality comparison.
    139   struct equal_to : public std::binary_function<Handle<T>, Handle<T>, bool> {
    140     V8_INLINE bool operator()(Handle<T> lhs, Handle<T> rhs) const {
    141       return lhs.address() == rhs.address();
    142     }
    143   };
    144 
    145   // Provide function object for location hashing.
    146   struct hash : public std::unary_function<Handle<T>, size_t> {
    147     V8_INLINE size_t operator()(Handle<T> const& handle) const {
    148       return base::hash<void*>()(handle.address());
    149     }
    150   };
    151 
    152  private:
    153   // Handles of different classes are allowed to access each other's location_.
    154   template <typename>
    155   friend class Handle;
    156   // MaybeHandle is allowed to access location_.
    157   template <typename>
    158   friend class MaybeHandle;
    159 };
    160 
    161 template <typename T>
    162 inline std::ostream& operator<<(std::ostream& os, Handle<T> handle);
    163 
    164 template <typename T>
    165 V8_INLINE Handle<T> handle(T* object, Isolate* isolate) {
    166   return Handle<T>(object, isolate);
    167 }
    168 
    169 template <typename T>
    170 V8_INLINE Handle<T> handle(T* object) {
    171   return Handle<T>(object);
    172 }
    173 
    174 
    175 // ----------------------------------------------------------------------------
    176 // A Handle can be converted into a MaybeHandle. Converting a MaybeHandle
    177 // into a Handle requires checking that it does not point to NULL.  This
    178 // ensures NULL checks before use.
    179 //
    180 // Also note that Handles do not provide default equality comparison or hashing
    181 // operators on purpose. Such operators would be misleading, because intended
    182 // semantics is ambiguous between Handle location and object identity.
    183 template <typename T>
    184 class MaybeHandle final {
    185  public:
    186   V8_INLINE MaybeHandle() {}
    187   V8_INLINE ~MaybeHandle() {}
    188 
    189   // Constructor for handling automatic up casting from Handle.
    190   // Ex. Handle<JSArray> can be passed when MaybeHandle<Object> is expected.
    191   template <typename S>
    192   V8_INLINE MaybeHandle(Handle<S> handle)
    193       : location_(reinterpret_cast<T**>(handle.location_)) {
    194     T* a = nullptr;
    195     S* b = nullptr;
    196     a = b;  // Fake assignment to enforce type checks.
    197     USE(a);
    198   }
    199 
    200   // Constructor for handling automatic up casting.
    201   // Ex. MaybeHandle<JSArray> can be passed when Handle<Object> is expected.
    202   template <typename S>
    203   V8_INLINE MaybeHandle(MaybeHandle<S> maybe_handle)
    204       : location_(reinterpret_cast<T**>(maybe_handle.location_)) {
    205     T* a = nullptr;
    206     S* b = nullptr;
    207     a = b;  // Fake assignment to enforce type checks.
    208     USE(a);
    209   }
    210 
    211   template <typename S>
    212   V8_INLINE MaybeHandle(S* object, Isolate* isolate)
    213       : MaybeHandle(handle(object, isolate)) {}
    214 
    215   V8_INLINE void Assert() const { DCHECK_NOT_NULL(location_); }
    216   V8_INLINE void Check() const { CHECK_NOT_NULL(location_); }
    217 
    218   V8_INLINE Handle<T> ToHandleChecked() const {
    219     Check();
    220     return Handle<T>(location_);
    221   }
    222 
    223   // Convert to a Handle with a type that can be upcasted to.
    224   template <typename S>
    225   V8_INLINE bool ToHandle(Handle<S>* out) const {
    226     if (location_ == nullptr) {
    227       *out = Handle<T>::null();
    228       return false;
    229     } else {
    230       *out = Handle<T>(location_);
    231       return true;
    232     }
    233   }
    234 
    235   // Returns the raw address where this handle is stored. This should only be
    236   // used for hashing handles; do not ever try to dereference it.
    237   V8_INLINE Address address() const { return bit_cast<Address>(location_); }
    238 
    239   bool is_null() const { return location_ == nullptr; }
    240 
    241  protected:
    242   T** location_ = nullptr;
    243 
    244   // MaybeHandles of different classes are allowed to access each
    245   // other's location_.
    246   template <typename>
    247   friend class MaybeHandle;
    248 };
    249 
    250 
    251 // ----------------------------------------------------------------------------
    252 // A stack-allocated class that governs a number of local handles.
    253 // After a handle scope has been created, all local handles will be
    254 // allocated within that handle scope until either the handle scope is
    255 // deleted or another handle scope is created.  If there is already a
    256 // handle scope and a new one is created, all allocations will take
    257 // place in the new handle scope until it is deleted.  After that,
    258 // new handles will again be allocated in the original handle scope.
    259 //
    260 // After the handle scope of a local handle has been deleted the
    261 // garbage collector will no longer track the object stored in the
    262 // handle and may deallocate it.  The behavior of accessing a handle
    263 // for which the handle scope has been deleted is undefined.
    264 class HandleScope {
    265  public:
    266   explicit inline HandleScope(Isolate* isolate);
    267 
    268   inline ~HandleScope();
    269 
    270   // Counts the number of allocated handles.
    271   V8_EXPORT_PRIVATE static int NumberOfHandles(Isolate* isolate);
    272 
    273   // Create a new handle or lookup a canonical handle.
    274   V8_INLINE static Object** GetHandle(Isolate* isolate, Object* value);
    275 
    276   // Creates a new handle with the given value.
    277   V8_INLINE static Object** CreateHandle(Isolate* isolate, Object* value);
    278 
    279   // Deallocates any extensions used by the current scope.
    280   V8_EXPORT_PRIVATE static void DeleteExtensions(Isolate* isolate);
    281 
    282   static Address current_next_address(Isolate* isolate);
    283   static Address current_limit_address(Isolate* isolate);
    284   static Address current_level_address(Isolate* isolate);
    285 
    286   // Closes the HandleScope (invalidating all handles
    287   // created in the scope of the HandleScope) and returns
    288   // a Handle backed by the parent scope holding the
    289   // value of the argument handle.
    290   template <typename T>
    291   Handle<T> CloseAndEscape(Handle<T> handle_value);
    292 
    293   Isolate* isolate() { return isolate_; }
    294 
    295   // Limit for number of handles with --check-handle-count. This is
    296   // large enough to compile natives and pass unit tests with some
    297   // slack for future changes to natives.
    298   static const int kCheckHandleThreshold = 30 * 1024;
    299 
    300  private:
    301   // Prevent heap allocation or illegal handle scopes.
    302   void* operator new(size_t size);
    303   void operator delete(void* size_t);
    304 
    305   Isolate* isolate_;
    306   Object** prev_next_;
    307   Object** prev_limit_;
    308 
    309   // Close the handle scope resetting limits to a previous state.
    310   static inline void CloseScope(Isolate* isolate,
    311                                 Object** prev_next,
    312                                 Object** prev_limit);
    313 
    314   // Extend the handle scope making room for more handles.
    315   V8_EXPORT_PRIVATE static Object** Extend(Isolate* isolate);
    316 
    317 #ifdef ENABLE_HANDLE_ZAPPING
    318   // Zaps the handles in the half-open interval [start, end).
    319   V8_EXPORT_PRIVATE static void ZapRange(Object** start, Object** end);
    320 #endif
    321 
    322   friend class v8::HandleScope;
    323   friend class DeferredHandles;
    324   friend class DeferredHandleScope;
    325   friend class HandleScopeImplementer;
    326   friend class Isolate;
    327 
    328   DISALLOW_COPY_AND_ASSIGN(HandleScope);
    329 };
    330 
    331 
    332 // Forward declarations for CanonicalHandleScope.
    333 template <typename V>
    334 class IdentityMap;
    335 class RootIndexMap;
    336 
    337 
    338 // A CanonicalHandleScope does not open a new HandleScope. It changes the
    339 // existing HandleScope so that Handles created within are canonicalized.
    340 // This does not apply to nested inner HandleScopes unless a nested
    341 // CanonicalHandleScope is introduced. Handles are only canonicalized within
    342 // the same CanonicalHandleScope, but not across nested ones.
    343 class V8_EXPORT_PRIVATE CanonicalHandleScope final {
    344  public:
    345   explicit CanonicalHandleScope(Isolate* isolate);
    346   ~CanonicalHandleScope();
    347 
    348  private:
    349   Object** Lookup(Object* object);
    350 
    351   Isolate* isolate_;
    352   Zone zone_;
    353   RootIndexMap* root_index_map_;
    354   IdentityMap<Object**>* identity_map_;
    355   // Ordinary nested handle scopes within the current one are not canonical.
    356   int canonical_level_;
    357   // We may have nested canonical scopes. Handles are canonical within each one.
    358   CanonicalHandleScope* prev_canonical_scope_;
    359 
    360   friend class HandleScope;
    361 };
    362 
    363 
    364 class DeferredHandleScope final {
    365  public:
    366   explicit DeferredHandleScope(Isolate* isolate);
    367   // The DeferredHandles object returned stores the Handles created
    368   // since the creation of this DeferredHandleScope.  The Handles are
    369   // alive as long as the DeferredHandles object is alive.
    370   DeferredHandles* Detach();
    371   ~DeferredHandleScope();
    372 
    373  private:
    374   Object** prev_limit_;
    375   Object** prev_next_;
    376   HandleScopeImplementer* impl_;
    377 
    378 #ifdef DEBUG
    379   bool handles_detached_;
    380   int prev_level_;
    381 #endif
    382 
    383   friend class HandleScopeImplementer;
    384 };
    385 
    386 
    387 // Seal off the current HandleScope so that new handles can only be created
    388 // if a new HandleScope is entered.
    389 class SealHandleScope final {
    390  public:
    391 #ifndef DEBUG
    392   explicit SealHandleScope(Isolate* isolate) {}
    393   ~SealHandleScope() {}
    394 #else
    395   explicit inline SealHandleScope(Isolate* isolate);
    396   inline ~SealHandleScope();
    397  private:
    398   Isolate* isolate_;
    399   Object** prev_limit_;
    400   int prev_sealed_level_;
    401 #endif
    402 };
    403 
    404 
    405 struct HandleScopeData final {
    406   Object** next;
    407   Object** limit;
    408   int level;
    409   int sealed_level;
    410   CanonicalHandleScope* canonical_scope;
    411 
    412   void Initialize() {
    413     next = limit = NULL;
    414     sealed_level = level = 0;
    415     canonical_scope = NULL;
    416   }
    417 };
    418 
    419 }  // namespace internal
    420 }  // namespace v8
    421 
    422 #endif  // V8_HANDLES_H_
    423