blob: 5d574657c5f0505346cd6fedb6f63bde1b8388c2 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 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 "apiutils.h"
32
33namespace v8 {
34namespace internal {
35
36// ----------------------------------------------------------------------------
37// A Handle provides a reference to an object that survives relocation by
38// the garbage collector.
39// Handles are only valid within a HandleScope.
40// When a handle is created for an object a cell is allocated in the heap.
41
42template<class T>
43class Handle {
44 public:
45 INLINE(Handle(T** location)) { location_ = location; }
46 INLINE(explicit Handle(T* obj));
47
48 INLINE(Handle()) : location_(NULL) {}
49
50 // Constructor for handling automatic up casting.
51 // Ex. Handle<JSFunction> can be passed when Handle<Object> is expected.
52 template <class S> Handle(Handle<S> handle) {
53#ifdef DEBUG
54 T* a = NULL;
55 S* b = NULL;
56 a = b; // Fake assignment to enforce type checks.
57 USE(a);
58#endif
59 location_ = reinterpret_cast<T**>(handle.location());
60 }
61
62 INLINE(T* operator ->() const) { return operator*(); }
63
64 // Check if this handle refers to the exact same object as the other handle.
65 bool is_identical_to(const Handle<T> other) const {
66 return operator*() == *other;
67 }
68
69 // Provides the C++ dereference operator.
70 INLINE(T* operator*() const);
71
72 // Returns the address to where the raw pointer is stored.
73 T** location() const {
74 ASSERT(location_ == NULL ||
75 reinterpret_cast<Address>(*location_) != kZapValue);
76 return location_;
77 }
78
79 template <class S> static Handle<T> cast(Handle<S> that) {
80 T::cast(*that);
81 return Handle<T>(reinterpret_cast<T**>(that.location()));
82 }
83
84 static Handle<T> null() { return Handle<T>(); }
85 bool is_null() { return location_ == NULL; }
86
87 // Closes the given scope, but lets this handle escape. See
88 // implementation in api.h.
89 inline Handle<T> EscapeFrom(v8::HandleScope* scope);
90
91 private:
92 T** location_;
93};
94
95
96// A stack-allocated class that governs a number of local handles.
97// After a handle scope has been created, all local handles will be
98// allocated within that handle scope until either the handle scope is
99// deleted or another handle scope is created. If there is already a
100// handle scope and a new one is created, all allocations will take
101// place in the new handle scope until it is deleted. After that,
102// new handles will again be allocated in the original handle scope.
103//
104// After the handle scope of a local handle has been deleted the
105// garbage collector will no longer track the object stored in the
106// handle and may deallocate it. The behavior of accessing a handle
107// for which the handle scope has been deleted is undefined.
108class HandleScope {
109 public:
110 HandleScope() : previous_(current_) {
111 current_.extensions = 0;
112 }
113
114 ~HandleScope() {
115 Leave(&previous_);
116 }
117
118 // Counts the number of allocated handles.
119 static int NumberOfHandles();
120
121 // Creates a new handle with the given value.
122 template <typename T>
123 static inline T** CreateHandle(T* value) {
124 internal::Object** cur = current_.next;
125 if (cur == current_.limit) cur = Extend();
126 // Update the current next field, set the value in the created
127 // handle, and return the result.
128 ASSERT(cur < current_.limit);
129 current_.next = cur + 1;
130
131 T** result = reinterpret_cast<T**>(cur);
132 *result = value;
133 return result;
134 }
135
136 private:
137 // Prevent heap allocation or illegal handle scopes.
138 HandleScope(const HandleScope&);
139 void operator=(const HandleScope&);
140 void* operator new(size_t size);
141 void operator delete(void* size_t);
142
143 static v8::ImplementationUtilities::HandleScopeData current_;
144 const v8::ImplementationUtilities::HandleScopeData previous_;
145
146 // Pushes a fresh handle scope to be used when allocating new handles.
147 static void Enter(
148 v8::ImplementationUtilities::HandleScopeData* previous) {
149 *previous = current_;
150 current_.extensions = 0;
151 }
152
153 // Re-establishes the previous scope state. Should be called only
154 // once, and only for the current scope.
155 static void Leave(
156 const v8::ImplementationUtilities::HandleScopeData* previous) {
157 if (current_.extensions > 0) {
158 DeleteExtensions();
159 }
160 current_ = *previous;
161#ifdef DEBUG
162 ZapRange(current_.next, current_.limit);
163#endif
164 }
165
166 // Extend the handle scope making room for more handles.
167 static internal::Object** Extend();
168
169 // Deallocates any extensions used by the current scope.
170 static void DeleteExtensions();
171
172 // Zaps the handles in the half-open interval [start, end).
173 static void ZapRange(internal::Object** start, internal::Object** end);
174
175 friend class v8::HandleScope;
176 friend class v8::ImplementationUtilities;
177};
178
179
180// ----------------------------------------------------------------------------
181// Handle operations.
182// They might invoke garbage collection. The result is an handle to
183// an object of expected type, or the handle is an error if running out
184// of space or encountering an internal error.
185
186void NormalizeProperties(Handle<JSObject> object,
187 PropertyNormalizationMode mode,
188 int expected_additional_properties);
189void NormalizeElements(Handle<JSObject> object);
190void TransformToFastProperties(Handle<JSObject> object,
191 int unused_property_fields);
192void FlattenString(Handle<String> str);
193
194Handle<Object> SetProperty(Handle<JSObject> object,
195 Handle<String> key,
196 Handle<Object> value,
197 PropertyAttributes attributes);
198
199Handle<Object> SetProperty(Handle<Object> object,
200 Handle<Object> key,
201 Handle<Object> value,
202 PropertyAttributes attributes);
203
204Handle<Object> ForceSetProperty(Handle<JSObject> object,
205 Handle<Object> key,
206 Handle<Object> value,
207 PropertyAttributes attributes);
208
209Handle<Object> ForceDeleteProperty(Handle<JSObject> object,
210 Handle<Object> key);
211
212Handle<Object> IgnoreAttributesAndSetLocalProperty(Handle<JSObject> object,
213 Handle<String> key,
214 Handle<Object> value,
215 PropertyAttributes attributes);
216
217Handle<Object> SetPropertyWithInterceptor(Handle<JSObject> object,
218 Handle<String> key,
219 Handle<Object> value,
220 PropertyAttributes attributes);
221
222Handle<Object> SetElement(Handle<JSObject> object,
223 uint32_t index,
224 Handle<Object> value);
225
226Handle<Object> GetProperty(Handle<JSObject> obj,
227 const char* name);
228
229Handle<Object> GetProperty(Handle<Object> obj,
230 Handle<Object> key);
231
232Handle<Object> GetPropertyWithInterceptor(Handle<JSObject> receiver,
233 Handle<JSObject> holder,
234 Handle<String> name,
235 PropertyAttributes* attributes);
236
237Handle<Object> GetPrototype(Handle<Object> obj);
238
239// Return the object's hidden properties object. If the object has no hidden
240// properties and create_if_needed is true, then a new hidden property object
241// will be allocated. Otherwise the Heap::undefined_value is returned.
242Handle<Object> GetHiddenProperties(Handle<JSObject> obj, bool create_if_needed);
243
244Handle<Object> DeleteElement(Handle<JSObject> obj, uint32_t index);
245Handle<Object> DeleteProperty(Handle<JSObject> obj, Handle<String> prop);
246
247Handle<Object> LookupSingleCharacterStringFromCode(uint32_t index);
248
249Handle<JSObject> Copy(Handle<JSObject> obj);
250
251Handle<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.
256Handle<JSValue> GetScriptWrapper(Handle<Script> script);
257
258// Script line number computations.
259void InitScriptLineEnds(Handle<Script> script);
260int GetScriptLineNumber(Handle<Script> script, int code_position);
261
262// Computes the enumerable keys from interceptors. Used for debug mirrors and
263// by GetKeysInFixedArrayFor below.
264v8::Handle<v8::Array> GetKeysForNamedInterceptor(Handle<JSObject> receiver,
265 Handle<JSObject> object);
266v8::Handle<v8::Array> GetKeysForIndexedInterceptor(Handle<JSObject> receiver,
267 Handle<JSObject> object);
268
269enum KeyCollectionType { LOCAL_ONLY, INCLUDE_PROTOS };
270
271// Computes the enumerable keys for a JSObject. Used for implementing
272// "for (n in object) { }".
273Handle<FixedArray> GetKeysInFixedArrayFor(Handle<JSObject> object,
274 KeyCollectionType type);
275Handle<JSArray> GetKeysFor(Handle<JSObject> object);
276Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object);
277
278// Computes the union of keys and return the result.
279// Used for implementing "for (n in object) { }"
280Handle<FixedArray> UnionOfKeys(Handle<FixedArray> first,
281 Handle<FixedArray> second);
282
283Handle<String> SubString(Handle<String> str, int start, int end);
284
285
286// Sets the expected number of properties for the function's instances.
287void SetExpectedNofProperties(Handle<JSFunction> func, int nof);
288
289// Sets the prototype property for a function instance.
290void SetPrototypeProperty(Handle<JSFunction> func, Handle<JSObject> value);
291
292// Sets the expected number of properties based on estimate from compiler.
293void SetExpectedNofPropertiesFromEstimate(Handle<SharedFunctionInfo> shared,
294 int estimate);
295void SetExpectedNofPropertiesFromEstimate(Handle<JSFunction> func,
296 int estimate);
297
298
299Handle<JSGlobalProxy> ReinitializeJSGlobalProxy(
300 Handle<JSFunction> constructor,
301 Handle<JSGlobalProxy> global);
302
303Handle<Object> SetPrototype(Handle<JSFunction> function,
304 Handle<Object> prototype);
305
306
307// Do lazy compilation of the given function. Returns true on success
308// and false if the compilation resulted in a stack overflow.
309enum ClearExceptionFlag { KEEP_EXCEPTION, CLEAR_EXCEPTION };
310
311bool CompileLazyShared(Handle<SharedFunctionInfo> shared,
312 ClearExceptionFlag flag,
313 int loop_nesting);
314
315bool CompileLazy(Handle<JSFunction> function, ClearExceptionFlag flag);
316bool CompileLazyInLoop(Handle<JSFunction> function, ClearExceptionFlag flag);
317
318// These deal with lazily loaded properties.
319void SetupLazy(Handle<JSObject> obj,
320 int index,
321 Handle<Context> compile_context,
322 Handle<Context> function_context);
323void LoadLazy(Handle<JSObject> obj, bool* pending_exception);
324
325class NoHandleAllocation BASE_EMBEDDED {
326 public:
327#ifndef DEBUG
328 NoHandleAllocation() {}
329 ~NoHandleAllocation() {}
330#else
331 inline NoHandleAllocation();
332 inline ~NoHandleAllocation();
333 private:
334 int extensions_;
335#endif
336};
337
338
339// ----------------------------------------------------------------------------
340
341
342// Stack allocated wrapper call for optimizing adding multiple
343// properties to an object.
344class OptimizedObjectForAddingMultipleProperties BASE_EMBEDDED {
345 public:
346 OptimizedObjectForAddingMultipleProperties(Handle<JSObject> object,
347 int expected_property_count,
348 bool condition = true);
349 ~OptimizedObjectForAddingMultipleProperties();
350 private:
351 bool has_been_transformed_; // Tells whether the object has been transformed.
352 int unused_property_fields_; // Captures the unused number of field.
353 Handle<JSObject> object_; // The object being optimized.
354};
355
356
357} } // namespace v8::internal
358
359#endif // V8_HANDLES_H_