Home | History | Annotate | Download | only in src
      1 // Copyright 2011 the V8 project authors. All rights reserved.
      2 // Redistribution and use in source and binary forms, with or without
      3 // modification, are permitted provided that the following conditions are
      4 // met:
      5 //
      6 //     * Redistributions of source code must retain the above copyright
      7 //       notice, this list of conditions and the following disclaimer.
      8 //     * Redistributions in binary form must reproduce the above
      9 //       copyright notice, this list of conditions and the following
     10 //       disclaimer in the documentation and/or other materials provided
     11 //       with the distribution.
     12 //     * Neither the name of Google Inc. nor the names of its
     13 //       contributors may be used to endorse or promote products derived
     14 //       from this software without specific prior written permission.
     15 //
     16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27 
     28 #ifndef V8_HANDLES_H_
     29 #define V8_HANDLES_H_
     30 
     31 #include "allocation.h"
     32 #include "apiutils.h"
     33 #include "objects.h"
     34 
     35 namespace v8 {
     36 namespace internal {
     37 
     38 // ----------------------------------------------------------------------------
     39 // A Handle provides a reference to an object that survives relocation by
     40 // the garbage collector.
     41 // Handles are only valid within a HandleScope.
     42 // When a handle is created for an object a cell is allocated in the heap.
     43 
     44 template<typename T>
     45 class Handle {
     46  public:
     47   INLINE(explicit Handle(T** location)) { location_ = location; }
     48   INLINE(explicit Handle(T* obj));
     49   INLINE(Handle(T* obj, Isolate* isolate));
     50 
     51   INLINE(Handle()) : location_(NULL) {}
     52 
     53   // Constructor for handling automatic up casting.
     54   // Ex. Handle<JSFunction> can be passed when Handle<Object> is expected.
     55   template <class S> Handle(Handle<S> handle) {
     56 #ifdef DEBUG
     57     T* a = NULL;
     58     S* b = NULL;
     59     a = b;  // Fake assignment to enforce type checks.
     60     USE(a);
     61 #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   // Provides the C++ dereference operator.
     71   INLINE(T* operator*() const);
     72 
     73   // 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     T::cast(*reinterpret_cast<T**>(that.location_));
     78     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   // Closes the given scope, but lets this handle escape. See
     85   // implementation in api.h.
     86   inline Handle<T> EscapeFrom(v8::EscapableHandleScope* scope);
     87 
     88 #ifdef DEBUG
     89   enum DereferenceCheckMode { INCLUDE_DEFERRED_CHECK, NO_DEFERRED_CHECK };
     90 
     91   bool IsDereferenceAllowed(DereferenceCheckMode mode) const;
     92 #endif  // DEBUG
     93 
     94  private:
     95   T** location_;
     96 
     97   // Handles of different classes are allowed to access each other's location_.
     98   template<class S> friend class Handle;
     99 };
    100 
    101 
    102 // Convenience wrapper.
    103 template<class T>
    104 inline Handle<T> handle(T* t, Isolate* isolate) {
    105   return Handle<T>(t, isolate);
    106 }
    107 
    108 
    109 // Convenience wrapper.
    110 template<class T>
    111 inline Handle<T> handle(T* t) {
    112   return Handle<T>(t, t->GetIsolate());
    113 }
    114 
    115 
    116 class DeferredHandles;
    117 class HandleScopeImplementer;
    118 
    119 
    120 // A stack-allocated class that governs a number of local handles.
    121 // After a handle scope has been created, all local handles will be
    122 // allocated within that handle scope until either the handle scope is
    123 // deleted or another handle scope is created.  If there is already a
    124 // handle scope and a new one is created, all allocations will take
    125 // place in the new handle scope until it is deleted.  After that,
    126 // new handles will again be allocated in the original handle scope.
    127 //
    128 // After the handle scope of a local handle has been deleted the
    129 // garbage collector will no longer track the object stored in the
    130 // handle and may deallocate it.  The behavior of accessing a handle
    131 // for which the handle scope has been deleted is undefined.
    132 class HandleScope {
    133  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   static Address current_next_address(Isolate* isolate);
    149   static Address current_limit_address(Isolate* isolate);
    150   static Address current_level_address(Isolate* isolate);
    151 
    152   // Closes the HandleScope (invalidating all handles
    153   // created in the scope of the HandleScope) and returns
    154   // a Handle backed by the parent scope holding the
    155   // value of the argument handle.
    156   template <typename T>
    157   Handle<T> CloseAndEscape(Handle<T> handle_value);
    158 
    159   Isolate* isolate() { return isolate_; }
    160 
    161  private:
    162   // Prevent heap allocation or illegal handle scopes.
    163   HandleScope(const HandleScope&);
    164   void operator=(const HandleScope&);
    165   void* operator new(size_t size);
    166   void operator delete(void* size_t);
    167 
    168   Isolate* isolate_;
    169   Object** prev_next_;
    170   Object** prev_limit_;
    171 
    172   // Close the handle scope resetting limits to a previous state.
    173   static inline void CloseScope(Isolate* isolate,
    174                                 Object** prev_next,
    175                                 Object** prev_limit);
    176 
    177   // Extend the handle scope making room for more handles.
    178   static internal::Object** Extend(Isolate* isolate);
    179 
    180 #ifdef ENABLE_HANDLE_ZAPPING
    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 class DeferredHandles;
    193 
    194 
    195 class DeferredHandleScope {
    196  public:
    197   explicit DeferredHandleScope(Isolate* isolate);
    198   // The DeferredHandles object returned stores the Handles created
    199   // since the creation of this DeferredHandleScope.  The Handles are
    200   // alive as long as the DeferredHandles object is alive.
    201   DeferredHandles* Detach();
    202   ~DeferredHandleScope();
    203 
    204  private:
    205   Object** prev_limit_;
    206   Object** prev_next_;
    207   HandleScopeImplementer* impl_;
    208 
    209 #ifdef DEBUG
    210   bool handles_detached_;
    211   int prev_level_;
    212 #endif
    213 
    214   friend class HandleScopeImplementer;
    215 };
    216 
    217 
    218 // ----------------------------------------------------------------------------
    219 // Handle operations.
    220 // They might invoke garbage collection. The result is an handle to
    221 // an object of expected type, or the handle is an error if running out
    222 // of space or encountering an internal error.
    223 
    224 // Flattens a string.
    225 void FlattenString(Handle<String> str);
    226 
    227 // Flattens a string and returns the underlying external or sequential
    228 // string.
    229 Handle<String> FlattenGetString(Handle<String> str);
    230 
    231 Handle<Object> ForceSetProperty(Handle<JSObject> object,
    232                                 Handle<Object> key,
    233                                 Handle<Object> value,
    234                                 PropertyAttributes attributes);
    235 
    236 Handle<Object> DeleteProperty(Handle<JSObject> object, Handle<Object> key);
    237 
    238 Handle<Object> ForceDeleteProperty(Handle<JSObject> object, Handle<Object> key);
    239 
    240 Handle<Object> HasProperty(Handle<JSReceiver> obj, Handle<Object> key);
    241 
    242 Handle<Object> GetProperty(Handle<JSReceiver> obj, const char* name);
    243 
    244 Handle<Object> GetProperty(Isolate* isolate,
    245                            Handle<Object> obj,
    246                            Handle<Object> key);
    247 
    248 Handle<Object> LookupSingleCharacterStringFromCode(Isolate* isolate,
    249                                                    uint32_t index);
    250 
    251 Handle<FixedArray> AddKeysFromJSArray(Handle<FixedArray>,
    252                                       Handle<JSArray> array);
    253 
    254 // Get the JS object corresponding to the given script; create it
    255 // if none exists.
    256 Handle<JSValue> GetScriptWrapper(Handle<Script> script);
    257 
    258 // Script line number computations. Note that the line number is zero-based.
    259 void InitScriptLineEnds(Handle<Script> script);
    260 // For string calculates an array of line end positions. If the string
    261 // does not end with a new line character, this character may optionally be
    262 // imagined.
    263 Handle<FixedArray> CalculateLineEnds(Handle<String> string,
    264                                      bool with_imaginary_last_new_line);
    265 int GetScriptLineNumber(Handle<Script> script, int code_position);
    266 // The safe version does not make heap allocations but may work much slower.
    267 int GetScriptLineNumberSafe(Handle<Script> script, int code_position);
    268 int GetScriptColumnNumber(Handle<Script> script, int code_position);
    269 Handle<Object> GetScriptNameOrSourceURL(Handle<Script> script);
    270 
    271 // Computes the enumerable keys from interceptors. Used for debug mirrors and
    272 // by GetKeysInFixedArrayFor below.
    273 v8::Handle<v8::Array> GetKeysForNamedInterceptor(Handle<JSReceiver> receiver,
    274                                                  Handle<JSObject> object);
    275 v8::Handle<v8::Array> GetKeysForIndexedInterceptor(Handle<JSReceiver> receiver,
    276                                                    Handle<JSObject> object);
    277 
    278 enum KeyCollectionType { LOCAL_ONLY, INCLUDE_PROTOS };
    279 
    280 // Computes the enumerable keys for a JSObject. Used for implementing
    281 // "for (n in object) { }".
    282 Handle<FixedArray> GetKeysInFixedArrayFor(Handle<JSReceiver> object,
    283                                           KeyCollectionType type,
    284                                           bool* threw);
    285 Handle<JSArray> GetKeysFor(Handle<JSReceiver> object, bool* threw);
    286 Handle<FixedArray> ReduceFixedArrayTo(Handle<FixedArray> array, int length);
    287 Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
    288                                        bool cache_result);
    289 
    290 // Computes the union of keys and return the result.
    291 // Used for implementing "for (n in object) { }"
    292 Handle<FixedArray> UnionOfKeys(Handle<FixedArray> first,
    293                                Handle<FixedArray> second);
    294 
    295 Handle<JSGlobalProxy> ReinitializeJSGlobalProxy(
    296     Handle<JSFunction> constructor,
    297     Handle<JSGlobalProxy> global);
    298 
    299 void AddWeakObjectToCodeDependency(Heap* heap,
    300                                    Handle<Object> object,
    301                                    Handle<Code> code);
    302 
    303 // Seal off the current HandleScope so that new handles can only be created
    304 // if a new HandleScope is entered.
    305 class SealHandleScope BASE_EMBEDDED {
    306  public:
    307 #ifndef DEBUG
    308   explicit SealHandleScope(Isolate* isolate) {}
    309   ~SealHandleScope() {}
    310 #else
    311   explicit inline SealHandleScope(Isolate* isolate);
    312   inline ~SealHandleScope();
    313  private:
    314   Isolate* isolate_;
    315   Object** limit_;
    316   int level_;
    317 #endif
    318 };
    319 
    320 } }  // namespace v8::internal
    321 
    322 #endif  // V8_HANDLES_H_
    323