handles.h 12.5 KB
Newer Older
1
// Copyright 2011 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef V8_HANDLES_H_
#define V8_HANDLES_H_

31
#include "allocation.h"
32
#include "apiutils.h"
33
#include "objects.h"
34

35 36
namespace v8 {
namespace internal {
37 38 39 40

// ----------------------------------------------------------------------------
// A Handle provides a reference to an object that survives relocation by
// the garbage collector.
41
// Handles are only valid within a HandleScope.
42 43
// When a handle is created for an object a cell is allocated in the heap.

44
template<typename T>
45 46
class Handle {
 public:
47
  INLINE(explicit Handle(T** location)) { location_ = location; }
48
  INLINE(explicit Handle(T* obj));
49
  INLINE(Handle(T* obj, Isolate* isolate));
50 51 52 53 54 55 56 57 58 59 60 61

  INLINE(Handle()) : location_(NULL) {}

  // Constructor for handling automatic up casting.
  // Ex. Handle<JSFunction> can be passed when Handle<Object> is expected.
  template <class S> Handle(Handle<S> handle) {
#ifdef DEBUG
    T* a = NULL;
    S* b = NULL;
    a = b;  // Fake assignment to enforce type checks.
    USE(a);
#endif
62
    location_ = reinterpret_cast<T**>(handle.location_);
63 64
  }

65
  INLINE(T* operator->() const) { return operator*(); }
66 67

  // Check if this handle refers to the exact same object as the other handle.
68
  INLINE(bool is_identical_to(const Handle<T> other) const);
69 70 71 72 73

  // Provides the C++ dereference operator.
  INLINE(T* operator*() const);

  // Returns the address to where the raw pointer is stored.
74
  INLINE(T** location() const);
75 76

  template <class S> static Handle<T> cast(Handle<S> that) {
77 78
    T::cast(*reinterpret_cast<T**>(that.location_));
    return Handle<T>(reinterpret_cast<T**>(that.location_));
79 80 81
  }

  static Handle<T> null() { return Handle<T>(); }
82
  bool is_null() const { return location_ == NULL; }
83 84 85

  // Closes the given scope, but lets this handle escape. See
  // implementation in api.h.
86
  inline Handle<T> EscapeFrom(v8::HandleScope* scope);
87

88
#ifdef DEBUG
89 90 91
  enum DereferenceCheckMode { INCLUDE_DEFERRED_CHECK, NO_DEFERRED_CHECK };

  bool IsDereferenceAllowed(DereferenceCheckMode mode) const;
92 93
#endif  // DEBUG

94 95
 private:
  T** location_;
96 97 98

  // Handles of different classes are allowed to access each other's location_.
  template<class S> friend class Handle;
99 100 101
};


102 103
// Convenience wrapper.
template<class T>
104 105
inline Handle<T> handle(T* t, Isolate* isolate) {
  return Handle<T>(t, isolate);
106 107 108
}


109 110 111 112 113 114 115
// Convenience wrapper.
template<class T>
inline Handle<T> handle(T* t) {
  return Handle<T>(t, t->GetIsolate());
}


116
class DeferredHandles;
117 118 119
class HandleScopeImplementer;


120 121 122 123 124 125 126 127 128 129 130 131 132 133
// A stack-allocated class that governs a number of local handles.
// After a handle scope has been created, all local handles will be
// allocated within that handle scope until either the handle scope is
// deleted or another handle scope is created.  If there is already a
// handle scope and a new one is created, all allocations will take
// place in the new handle scope until it is deleted.  After that,
// new handles will again be allocated in the original handle scope.
//
// After the handle scope of a local handle has been deleted the
// garbage collector will no longer track the object stored in the
// handle and may deallocate it.  The behavior of accessing a handle
// for which the handle scope has been deleted is undefined.
class HandleScope {
 public:
134
  explicit inline HandleScope(Isolate* isolate);
135

136
  inline ~HandleScope();
137 138

  // Counts the number of allocated handles.
139
  static int NumberOfHandles(Isolate* isolate);
140 141

  // Creates a new handle with the given value.
142
  template <typename T>
143
  static inline T** CreateHandle(Isolate* isolate, T* value);
144

145
  // Deallocates any extensions used by the current scope.
146
  static void DeleteExtensions(Isolate* isolate);
147

148 149 150
  static Address current_next_address(Isolate* isolate);
  static Address current_limit_address(Isolate* isolate);
  static Address current_level_address(Isolate* isolate);
151

152 153 154 155 156
  // Closes the HandleScope (invalidating all handles
  // created in the scope of the HandleScope) and returns
  // a Handle backed by the parent scope holding the
  // value of the argument handle.
  template <typename T>
157 158 159
  Handle<T> CloseAndEscape(Handle<T> handle_value);

  Isolate* isolate() { return isolate_; }
160

161 162 163 164 165 166 167
 private:
  // Prevent heap allocation or illegal handle scopes.
  HandleScope(const HandleScope&);
  void operator=(const HandleScope&);
  void* operator new(size_t size);
  void operator delete(void* size_t);

168
  Isolate* isolate_;
169 170
  Object** prev_next_;
  Object** prev_limit_;
171

172 173 174 175 176
  // Close the handle scope resetting limits to a previous state.
  static inline void CloseScope(Isolate* isolate,
                                Object** prev_next,
                                Object** prev_limit);

177
  // Extend the handle scope making room for more handles.
178
  static internal::Object** Extend(Isolate* isolate);
179

180
#ifdef ENABLE_EXTRA_CHECKS
181
  // Zaps the handles in the half-open interval [start, end).
182
  static void ZapRange(Object** start, Object** end);
183
#endif
184 185

  friend class v8::HandleScope;
186
  friend class v8::internal::DeferredHandles;
187
  friend class v8::internal::HandleScopeImplementer;
188
  friend class v8::internal::Isolate;
189 190 191
};


192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
class DeferredHandles;


class DeferredHandleScope {
 public:
  explicit DeferredHandleScope(Isolate* isolate);
  // The DeferredHandles object returned stores the Handles created
  // since the creation of this DeferredHandleScope.  The Handles are
  // alive as long as the DeferredHandles object is alive.
  DeferredHandles* Detach();
  ~DeferredHandleScope();

 private:
  Object** prev_limit_;
  Object** prev_next_;
  HandleScopeImplementer* impl_;

#ifdef DEBUG
  bool handles_detached_;
  int prev_level_;
#endif

  friend class HandleScopeImplementer;
};


218 219
// ----------------------------------------------------------------------------
// Handle operations.
220 221 222
// They might invoke garbage collection. The result is an handle to
// an object of expected type, or the handle is an error if running out
// of space or encountering an internal error.
223

224
// Flattens a string.
225 226
void FlattenString(Handle<String> str);

227
// Flattens a string and returns the underlying external or sequential
228
// string.
229
Handle<String> FlattenGetString(Handle<String> str);
230

231 232
Handle<Object> SetProperty(Isolate* isolate,
                           Handle<Object> object,
233 234
                           Handle<Object> key,
                           Handle<Object> value,
235
                           PropertyAttributes attributes,
236
                           StrictModeFlag strict_mode);
237

238 239 240 241 242
Handle<Object> ForceSetProperty(Handle<JSObject> object,
                                Handle<Object> key,
                                Handle<Object> value,
                                PropertyAttributes attributes);

243
Handle<Object> DeleteProperty(Handle<JSObject> object, Handle<Object> key);
244

245 246 247 248 249
Handle<Object> ForceDeleteProperty(Handle<JSObject> object, Handle<Object> key);

Handle<Object> HasProperty(Handle<JSReceiver> obj, Handle<Object> key);

Handle<Object> GetProperty(Handle<JSReceiver> obj, const char* name);
250

251 252
Handle<Object> GetProperty(Isolate* isolate,
                           Handle<Object> obj,
253 254
                           Handle<Object> key);

255 256
Handle<Object> LookupSingleCharacterStringFromCode(Isolate* isolate,
                                                   uint32_t index);
257

258 259 260
Handle<FixedArray> AddKeysFromJSArray(Handle<FixedArray>,
                                      Handle<JSArray> array);

261 262 263 264
// Get the JS object corresponding to the given script; create it
// if none exists.
Handle<JSValue> GetScriptWrapper(Handle<Script> script);

265
// Script line number computations. Note that the line number is zero-based.
266
void InitScriptLineEnds(Handle<Script> script);
267 268 269 270 271
// For string calculates an array of line end positions. If the string
// does not end with a new line character, this character may optionally be
// imagined.
Handle<FixedArray> CalculateLineEnds(Handle<String> string,
                                     bool with_imaginary_last_new_line);
272
int GetScriptLineNumber(Handle<Script> script, int code_position);
273 274
// The safe version does not make heap allocations but may work much slower.
int GetScriptLineNumberSafe(Handle<Script> script, int code_position);
275
int GetScriptColumnNumber(Handle<Script> script, int code_position);
276
Handle<Object> GetScriptNameOrSourceURL(Handle<Script> script);
277

278 279
// Computes the enumerable keys from interceptors. Used for debug mirrors and
// by GetKeysInFixedArrayFor below.
280
v8::Handle<v8::Array> GetKeysForNamedInterceptor(Handle<JSReceiver> receiver,
281
                                                 Handle<JSObject> object);
282
v8::Handle<v8::Array> GetKeysForIndexedInterceptor(Handle<JSReceiver> receiver,
283
                                                   Handle<JSObject> object);
284 285 286

enum KeyCollectionType { LOCAL_ONLY, INCLUDE_PROTOS };

287 288
// Computes the enumerable keys for a JSObject. Used for implementing
// "for (n in object) { }".
289 290 291 292
Handle<FixedArray> GetKeysInFixedArrayFor(Handle<JSReceiver> object,
                                          KeyCollectionType type,
                                          bool* threw);
Handle<JSArray> GetKeysFor(Handle<JSReceiver> object, bool* threw);
293
Handle<FixedArray> ReduceFixedArrayTo(Handle<FixedArray> array, int length);
294 295
Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
                                       bool cache_result);
296 297 298 299 300 301

// Computes the union of keys and return the result.
// Used for implementing "for (n in object) { }"
Handle<FixedArray> UnionOfKeys(Handle<FixedArray> first,
                               Handle<FixedArray> second);

302 303 304 305
Handle<String> SubString(Handle<String> str,
                         int start,
                         int end,
                         PretenureFlag pretenure = NOT_TENURED);
306 307 308 309 310 311 312 313 314

// Sets the expected number of properties for the function's instances.
void SetExpectedNofProperties(Handle<JSFunction> func, int nof);

// Sets the expected number of properties based on estimate from compiler.
void SetExpectedNofPropertiesFromEstimate(Handle<SharedFunctionInfo> shared,
                                          int estimate);


315
Handle<JSGlobalProxy> ReinitializeJSGlobalProxy(
316
    Handle<JSFunction> constructor,
317
    Handle<JSGlobalProxy> global);
318

319 320 321 322 323 324
Handle<ObjectHashSet> ObjectHashSetAdd(Handle<ObjectHashSet> table,
                                       Handle<Object> key);

Handle<ObjectHashSet> ObjectHashSetRemove(Handle<ObjectHashSet> table,
                                          Handle<Object> key);

325
Handle<ObjectHashTable> PutIntoObjectHashTable(Handle<ObjectHashTable> table,
326
                                               Handle<Object> key,
327 328
                                               Handle<Object> value);

329 330 331 332

// Seal off the current HandleScope so that new handles can only be created
// if a new HandleScope is entered.
class SealHandleScope BASE_EMBEDDED {
333 334
 public:
#ifndef DEBUG
335 336
  explicit SealHandleScope(Isolate* isolate) {}
  ~SealHandleScope() {}
337
#else
338 339
  explicit inline SealHandleScope(Isolate* isolate);
  inline ~SealHandleScope();
340
 private:
341
  Isolate* isolate_;
342
  Object** limit_;
343
  int level_;
344 345 346 347 348 349
#endif
};

} }  // namespace v8::internal

#endif  // V8_HANDLES_H_