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