blob: b4598c67dba7934b251b712126a46bbfc0aca2e5 [file] [log] [blame]
Ben Murdoch257744e2011-11-30 15:57:28 +00001// Copyright 2011 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// 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/** \mainpage V8 API Reference Guide
29 *
30 * V8 is Google's open source JavaScript engine.
31 *
32 * This set of documents provides reference material generated from the
33 * V8 header file, include/v8.h.
34 *
35 * For other documentation see http://code.google.com/apis/v8/
36 */
37
38#ifndef V8_H_
39#define V8_H_
40
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080041#include "v8stdint.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000042
43#ifdef _WIN32
Steve Blocka7e24c12009-10-30 11:49:00 +000044
45// Setup for Windows DLL export/import. When building the V8 DLL the
46// BUILDING_V8_SHARED needs to be defined. When building a program which uses
47// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
48// static library or building a program which uses the V8 static library neither
49// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
Steve Blocka7e24c12009-10-30 11:49:00 +000050#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
51#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
52 build configuration to ensure that at most one of these is set
53#endif
54
55#ifdef BUILDING_V8_SHARED
56#define V8EXPORT __declspec(dllexport)
Steve Blocka7e24c12009-10-30 11:49:00 +000057#elif USING_V8_SHARED
58#define V8EXPORT __declspec(dllimport)
Steve Blocka7e24c12009-10-30 11:49:00 +000059#else
60#define V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +000061#endif // BUILDING_V8_SHARED
62
63#else // _WIN32
64
Steve Blocka7e24c12009-10-30 11:49:00 +000065// Setup for Linux shared library export. There is no need to distinguish
66// between building or using the V8 shared library, but we should not
67// export symbols when we are building a static library.
68#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
69#define V8EXPORT __attribute__ ((visibility("default")))
Steve Blocka7e24c12009-10-30 11:49:00 +000070#else // defined(__GNUC__) && (__GNUC__ >= 4)
71#define V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +000072#endif // defined(__GNUC__) && (__GNUC__ >= 4)
73
74#endif // _WIN32
75
76/**
77 * The v8 JavaScript engine.
78 */
79namespace v8 {
80
81class Context;
82class String;
83class Value;
84class Utils;
85class Number;
86class Object;
87class Array;
88class Int32;
89class Uint32;
90class External;
91class Primitive;
92class Boolean;
93class Integer;
94class Function;
95class Date;
96class ImplementationUtilities;
97class Signature;
98template <class T> class Handle;
99template <class T> class Local;
100template <class T> class Persistent;
101class FunctionTemplate;
102class ObjectTemplate;
103class Data;
Leon Clarkef7060e22010-06-03 12:02:55 +0100104class AccessorInfo;
Kristian Monsen25f61362010-05-21 11:50:48 +0100105class StackTrace;
106class StackFrame;
Steve Blocka7e24c12009-10-30 11:49:00 +0000107
108namespace internal {
109
Steve Blocka7e24c12009-10-30 11:49:00 +0000110class Arguments;
Steve Blockd0582a62009-12-15 09:54:21 +0000111class Object;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100112class Heap;
Steve Block44f0eee2011-05-26 01:26:41 +0100113class HeapObject;
114class Isolate;
Steve Blocka7e24c12009-10-30 11:49:00 +0000115}
116
117
Ben Murdoch257744e2011-11-30 15:57:28 +0000118// --- Weak Handles ---
Steve Blocka7e24c12009-10-30 11:49:00 +0000119
120
121/**
122 * A weak reference callback function.
123 *
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100124 * This callback should either explicitly invoke Dispose on |object| if
125 * V8 wrapper is not needed anymore, or 'revive' it by invocation of MakeWeak.
126 *
Steve Blocka7e24c12009-10-30 11:49:00 +0000127 * \param object the weak global object to be reclaimed by the garbage collector
128 * \param parameter the value passed in when making the weak global object
129 */
130typedef void (*WeakReferenceCallback)(Persistent<Value> object,
131 void* parameter);
132
133
Ben Murdoch257744e2011-11-30 15:57:28 +0000134// --- Handles ---
Steve Blocka7e24c12009-10-30 11:49:00 +0000135
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100136#define TYPE_CHECK(T, S) \
137 while (false) { \
138 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
Steve Blocka7e24c12009-10-30 11:49:00 +0000139 }
140
141/**
142 * An object reference managed by the v8 garbage collector.
143 *
144 * All objects returned from v8 have to be tracked by the garbage
145 * collector so that it knows that the objects are still alive. Also,
146 * because the garbage collector may move objects, it is unsafe to
147 * point directly to an object. Instead, all objects are stored in
148 * handles which are known by the garbage collector and updated
149 * whenever an object moves. Handles should always be passed by value
150 * (except in cases like out-parameters) and they should never be
151 * allocated on the heap.
152 *
153 * There are two types of handles: local and persistent handles.
154 * Local handles are light-weight and transient and typically used in
155 * local operations. They are managed by HandleScopes. Persistent
156 * handles can be used when storing objects across several independent
157 * operations and have to be explicitly deallocated when they're no
158 * longer used.
159 *
160 * It is safe to extract the object stored in the handle by
161 * dereferencing the handle (for instance, to extract the Object* from
Ben Murdoch257744e2011-11-30 15:57:28 +0000162 * a Handle<Object>); the value will still be governed by a handle
Steve Blocka7e24c12009-10-30 11:49:00 +0000163 * behind the scenes and the same rules apply to these values as to
164 * their handles.
165 */
Steve Block8defd9f2010-07-08 12:39:36 +0100166template <class T> class Handle {
Steve Blocka7e24c12009-10-30 11:49:00 +0000167 public:
168
169 /**
170 * Creates an empty handle.
171 */
172 inline Handle();
173
174 /**
175 * Creates a new handle for the specified value.
176 */
Steve Block8defd9f2010-07-08 12:39:36 +0100177 inline explicit Handle(T* val) : val_(val) { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000178
179 /**
180 * Creates a handle for the contents of the specified handle. This
181 * constructor allows you to pass handles as arguments by value and
182 * to assign between handles. However, if you try to assign between
183 * incompatible handles, for instance from a Handle<String> to a
Ben Murdoch257744e2011-11-30 15:57:28 +0000184 * Handle<Number> it will cause a compile-time error. Assigning
Steve Blocka7e24c12009-10-30 11:49:00 +0000185 * between compatible handles, for instance assigning a
186 * Handle<String> to a variable declared as Handle<Value>, is legal
187 * because String is a subclass of Value.
188 */
189 template <class S> inline Handle(Handle<S> that)
190 : val_(reinterpret_cast<T*>(*that)) {
191 /**
192 * This check fails when trying to convert between incompatible
193 * handles. For example, converting from a Handle<String> to a
194 * Handle<Number>.
195 */
196 TYPE_CHECK(T, S);
197 }
198
199 /**
200 * Returns true if the handle is empty.
201 */
Steve Block8defd9f2010-07-08 12:39:36 +0100202 inline bool IsEmpty() const { return val_ == 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000203
Steve Block8defd9f2010-07-08 12:39:36 +0100204 inline T* operator->() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000205
Steve Block8defd9f2010-07-08 12:39:36 +0100206 inline T* operator*() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000207
208 /**
209 * Sets the handle to be empty. IsEmpty() will then return true.
210 */
Steve Block8defd9f2010-07-08 12:39:36 +0100211 inline void Clear() { this->val_ = 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000212
213 /**
214 * Checks whether two handles are the same.
215 * Returns true if both are empty, or if the objects
216 * to which they refer are identical.
217 * The handles' references are not checked.
218 */
Steve Block8defd9f2010-07-08 12:39:36 +0100219 template <class S> inline bool operator==(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000220 internal::Object** a = reinterpret_cast<internal::Object**>(**this);
221 internal::Object** b = reinterpret_cast<internal::Object**>(*that);
222 if (a == 0) return b == 0;
223 if (b == 0) return false;
224 return *a == *b;
225 }
226
227 /**
228 * Checks whether two handles are different.
229 * Returns true if only one of the handles is empty, or if
230 * the objects to which they refer are different.
231 * The handles' references are not checked.
232 */
Steve Block8defd9f2010-07-08 12:39:36 +0100233 template <class S> inline bool operator!=(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000234 return !operator==(that);
235 }
236
237 template <class S> static inline Handle<T> Cast(Handle<S> that) {
238#ifdef V8_ENABLE_CHECKS
239 // If we're going to perform the type check then we have to check
240 // that the handle isn't empty before doing the checked cast.
241 if (that.IsEmpty()) return Handle<T>();
242#endif
243 return Handle<T>(T::Cast(*that));
244 }
245
Steve Block6ded16b2010-05-10 14:33:55 +0100246 template <class S> inline Handle<S> As() {
247 return Handle<S>::Cast(*this);
248 }
249
Steve Blocka7e24c12009-10-30 11:49:00 +0000250 private:
251 T* val_;
252};
253
254
255/**
256 * A light-weight stack-allocated object handle. All operations
257 * that return objects from within v8 return them in local handles. They
258 * are created within HandleScopes, and all local handles allocated within a
259 * handle scope are destroyed when the handle scope is destroyed. Hence it
260 * is not necessary to explicitly deallocate local handles.
261 */
Steve Block8defd9f2010-07-08 12:39:36 +0100262template <class T> class Local : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000263 public:
264 inline Local();
265 template <class S> inline Local(Local<S> that)
266 : Handle<T>(reinterpret_cast<T*>(*that)) {
267 /**
268 * This check fails when trying to convert between incompatible
269 * handles. For example, converting from a Handle<String> to a
270 * Handle<Number>.
271 */
272 TYPE_CHECK(T, S);
273 }
274 template <class S> inline Local(S* that) : Handle<T>(that) { }
275 template <class S> static inline Local<T> Cast(Local<S> that) {
276#ifdef V8_ENABLE_CHECKS
277 // If we're going to perform the type check then we have to check
278 // that the handle isn't empty before doing the checked cast.
279 if (that.IsEmpty()) return Local<T>();
280#endif
281 return Local<T>(T::Cast(*that));
282 }
283
Steve Block6ded16b2010-05-10 14:33:55 +0100284 template <class S> inline Local<S> As() {
285 return Local<S>::Cast(*this);
286 }
287
Steve Blocka7e24c12009-10-30 11:49:00 +0000288 /** Create a local handle for the content of another handle.
289 * The referee is kept alive by the local handle even when
290 * the original handle is destroyed/disposed.
291 */
292 inline static Local<T> New(Handle<T> that);
293};
294
295
296/**
297 * An object reference that is independent of any handle scope. Where
298 * a Local handle only lives as long as the HandleScope in which it was
299 * allocated, a Persistent handle remains valid until it is explicitly
300 * disposed.
301 *
302 * A persistent handle contains a reference to a storage cell within
303 * the v8 engine which holds an object value and which is updated by
304 * the garbage collector whenever the object is moved. A new storage
305 * cell can be created using Persistent::New and existing handles can
306 * be disposed using Persistent::Dispose. Since persistent handles
307 * are passed by value you may have many persistent handle objects
308 * that point to the same storage cell. For instance, if you pass a
309 * persistent handle as an argument to a function you will not get two
310 * different storage cells but rather two references to the same
311 * storage cell.
312 */
Steve Block8defd9f2010-07-08 12:39:36 +0100313template <class T> class Persistent : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000314 public:
315
316 /**
317 * Creates an empty persistent handle that doesn't point to any
318 * storage cell.
319 */
320 inline Persistent();
321
322 /**
323 * Creates a persistent handle for the same storage cell as the
324 * specified handle. This constructor allows you to pass persistent
325 * handles as arguments by value and to assign between persistent
326 * handles. However, attempting to assign between incompatible
327 * persistent handles, for instance from a Persistent<String> to a
Ben Murdoch257744e2011-11-30 15:57:28 +0000328 * Persistent<Number> will cause a compile-time error. Assigning
Steve Blocka7e24c12009-10-30 11:49:00 +0000329 * between compatible persistent handles, for instance assigning a
330 * Persistent<String> to a variable declared as Persistent<Value>,
331 * is allowed as String is a subclass of Value.
332 */
333 template <class S> inline Persistent(Persistent<S> that)
334 : Handle<T>(reinterpret_cast<T*>(*that)) {
335 /**
336 * This check fails when trying to convert between incompatible
337 * handles. For example, converting from a Handle<String> to a
338 * Handle<Number>.
339 */
340 TYPE_CHECK(T, S);
341 }
342
343 template <class S> inline Persistent(S* that) : Handle<T>(that) { }
344
345 /**
346 * "Casts" a plain handle which is known to be a persistent handle
347 * to a persistent handle.
348 */
349 template <class S> explicit inline Persistent(Handle<S> that)
350 : Handle<T>(*that) { }
351
352 template <class S> static inline Persistent<T> Cast(Persistent<S> that) {
353#ifdef V8_ENABLE_CHECKS
354 // If we're going to perform the type check then we have to check
355 // that the handle isn't empty before doing the checked cast.
356 if (that.IsEmpty()) return Persistent<T>();
357#endif
358 return Persistent<T>(T::Cast(*that));
359 }
360
Steve Block6ded16b2010-05-10 14:33:55 +0100361 template <class S> inline Persistent<S> As() {
362 return Persistent<S>::Cast(*this);
363 }
364
Steve Blocka7e24c12009-10-30 11:49:00 +0000365 /**
366 * Creates a new persistent handle for an existing local or
367 * persistent handle.
368 */
369 inline static Persistent<T> New(Handle<T> that);
370
371 /**
372 * Releases the storage cell referenced by this persistent handle.
373 * Does not remove the reference to the cell from any handles.
Ben Murdoch257744e2011-11-30 15:57:28 +0000374 * This handle's reference, and any other references to the storage
Steve Blocka7e24c12009-10-30 11:49:00 +0000375 * cell remain and IsEmpty will still return false.
376 */
377 inline void Dispose();
378
379 /**
380 * Make the reference to this object weak. When only weak handles
381 * refer to the object, the garbage collector will perform a
382 * callback to the given V8::WeakReferenceCallback function, passing
383 * it the object reference and the given parameters.
384 */
385 inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
386
387 /** Clears the weak reference to this object.*/
388 inline void ClearWeak();
389
390 /**
Ben Murdoch257744e2011-11-30 15:57:28 +0000391 * Marks the reference to this object independent. Garbage collector
392 * is free to ignore any object groups containing this object.
393 * Weak callback for an independent handle should not
394 * assume that it will be preceded by a global GC prologue callback
395 * or followed by a global GC epilogue callback.
396 */
397 inline void MarkIndependent();
398
399 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000400 *Checks if the handle holds the only reference to an object.
401 */
402 inline bool IsNearDeath() const;
403
404 /**
405 * Returns true if the handle's reference is weak.
406 */
407 inline bool IsWeak() const;
408
Steve Block44f0eee2011-05-26 01:26:41 +0100409 /**
410 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo
411 * interface description in v8-profiler.h for details.
412 */
413 inline void SetWrapperClassId(uint16_t class_id);
414
Steve Blocka7e24c12009-10-30 11:49:00 +0000415 private:
416 friend class ImplementationUtilities;
417 friend class ObjectTemplate;
418};
419
420
421 /**
422 * A stack-allocated class that governs a number of local handles.
423 * After a handle scope has been created, all local handles will be
424 * allocated within that handle scope until either the handle scope is
425 * deleted or another handle scope is created. If there is already a
426 * handle scope and a new one is created, all allocations will take
427 * place in the new handle scope until it is deleted. After that,
428 * new handles will again be allocated in the original handle scope.
429 *
430 * After the handle scope of a local handle has been deleted the
431 * garbage collector will no longer track the object stored in the
432 * handle and may deallocate it. The behavior of accessing a handle
433 * for which the handle scope has been deleted is undefined.
434 */
435class V8EXPORT HandleScope {
436 public:
437 HandleScope();
438
439 ~HandleScope();
440
441 /**
442 * Closes the handle scope and returns the value as a handle in the
443 * previous scope, which is the new current scope after the call.
444 */
445 template <class T> Local<T> Close(Handle<T> value);
446
447 /**
448 * Counts the number of allocated handles.
449 */
450 static int NumberOfHandles();
451
452 /**
453 * Creates a new handle with the given value.
454 */
455 static internal::Object** CreateHandle(internal::Object* value);
Steve Block44f0eee2011-05-26 01:26:41 +0100456 // Faster version, uses HeapObject to obtain the current Isolate.
457 static internal::Object** CreateHandle(internal::HeapObject* value);
Steve Blocka7e24c12009-10-30 11:49:00 +0000458
459 private:
460 // Make it impossible to create heap-allocated or illegal handle
461 // scopes by disallowing certain operations.
462 HandleScope(const HandleScope&);
463 void operator=(const HandleScope&);
464 void* operator new(size_t size);
465 void operator delete(void*, size_t);
466
Steve Blockd0582a62009-12-15 09:54:21 +0000467 // This Data class is accessible internally as HandleScopeData through a
468 // typedef in the ImplementationUtilities class.
Steve Blocka7e24c12009-10-30 11:49:00 +0000469 class V8EXPORT Data {
470 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000471 internal::Object** next;
472 internal::Object** limit;
John Reck59135872010-11-02 12:39:01 -0700473 int level;
Steve Blocka7e24c12009-10-30 11:49:00 +0000474 inline void Initialize() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000475 next = limit = NULL;
John Reck59135872010-11-02 12:39:01 -0700476 level = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000477 }
478 };
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800479
John Reck59135872010-11-02 12:39:01 -0700480 void Leave();
Steve Blocka7e24c12009-10-30 11:49:00 +0000481
Steve Block44f0eee2011-05-26 01:26:41 +0100482 internal::Isolate* isolate_;
John Reck59135872010-11-02 12:39:01 -0700483 internal::Object** prev_next_;
484 internal::Object** prev_limit_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000485
486 // Allow for the active closing of HandleScopes which allows to pass a handle
487 // from the HandleScope being closed to the next top most HandleScope.
488 bool is_closed_;
489 internal::Object** RawClose(internal::Object** value);
490
491 friend class ImplementationUtilities;
492};
493
494
Ben Murdoch257744e2011-11-30 15:57:28 +0000495// --- Special objects ---
Steve Blocka7e24c12009-10-30 11:49:00 +0000496
497
498/**
499 * The superclass of values and API object templates.
500 */
501class V8EXPORT Data {
502 private:
503 Data();
504};
505
506
507/**
508 * Pre-compilation data that can be associated with a script. This
509 * data can be calculated for a script in advance of actually
510 * compiling it, and can be stored between compilations. When script
511 * data is given to the compile method compilation will be faster.
512 */
513class V8EXPORT ScriptData { // NOLINT
514 public:
515 virtual ~ScriptData() { }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100516
Leon Clarkef7060e22010-06-03 12:02:55 +0100517 /**
518 * Pre-compiles the specified script (context-independent).
519 *
520 * \param input Pointer to UTF-8 script source code.
521 * \param length Length of UTF-8 script source code.
522 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000523 static ScriptData* PreCompile(const char* input, int length);
Steve Blocka7e24c12009-10-30 11:49:00 +0000524
Leon Clarkef7060e22010-06-03 12:02:55 +0100525 /**
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100526 * Pre-compiles the specified script (context-independent).
527 *
528 * NOTE: Pre-compilation using this method cannot happen on another thread
529 * without using Lockers.
530 *
531 * \param source Script source code.
532 */
533 static ScriptData* PreCompile(Handle<String> source);
534
535 /**
Leon Clarkef7060e22010-06-03 12:02:55 +0100536 * Load previous pre-compilation data.
537 *
538 * \param data Pointer to data returned by a call to Data() of a previous
539 * ScriptData. Ownership is not transferred.
540 * \param length Length of data.
541 */
542 static ScriptData* New(const char* data, int length);
543
544 /**
545 * Returns the length of Data().
546 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000547 virtual int Length() = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +0100548
549 /**
550 * Returns a serialized representation of this ScriptData that can later be
551 * passed to New(). NOTE: Serialized data is platform-dependent.
552 */
553 virtual const char* Data() = 0;
554
555 /**
556 * Returns true if the source code could not be parsed.
557 */
Leon Clarkee46be812010-01-19 14:06:41 +0000558 virtual bool HasError() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000559};
560
561
562/**
563 * The origin, within a file, of a script.
564 */
Steve Block8defd9f2010-07-08 12:39:36 +0100565class ScriptOrigin {
Steve Blocka7e24c12009-10-30 11:49:00 +0000566 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100567 inline ScriptOrigin(
568 Handle<Value> resource_name,
569 Handle<Integer> resource_line_offset = Handle<Integer>(),
570 Handle<Integer> resource_column_offset = Handle<Integer>())
Steve Blocka7e24c12009-10-30 11:49:00 +0000571 : resource_name_(resource_name),
572 resource_line_offset_(resource_line_offset),
573 resource_column_offset_(resource_column_offset) { }
574 inline Handle<Value> ResourceName() const;
575 inline Handle<Integer> ResourceLineOffset() const;
576 inline Handle<Integer> ResourceColumnOffset() const;
577 private:
578 Handle<Value> resource_name_;
579 Handle<Integer> resource_line_offset_;
580 Handle<Integer> resource_column_offset_;
581};
582
583
584/**
585 * A compiled JavaScript script.
586 */
587class V8EXPORT Script {
588 public:
589
Steve Blocka7e24c12009-10-30 11:49:00 +0000590 /**
Andrei Popescu402d9372010-02-26 13:31:12 +0000591 * Compiles the specified script (context-independent).
Steve Blocka7e24c12009-10-30 11:49:00 +0000592 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000593 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100594 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000595 * when New() returns
596 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
597 * using pre_data speeds compilation if it's done multiple times.
598 * Owned by caller, no references are kept when New() returns.
599 * \param script_data Arbitrary data associated with script. Using
Steve Block6ded16b2010-05-10 14:33:55 +0100600 * this has same effect as calling SetData(), but allows data to be
Andrei Popescu402d9372010-02-26 13:31:12 +0000601 * available to compile event handlers.
602 * \return Compiled script object (context independent; when run it
603 * will use the currently entered context).
Steve Blocka7e24c12009-10-30 11:49:00 +0000604 */
Andrei Popescu402d9372010-02-26 13:31:12 +0000605 static Local<Script> New(Handle<String> source,
606 ScriptOrigin* origin = NULL,
607 ScriptData* pre_data = NULL,
608 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000609
610 /**
611 * Compiles the specified script using the specified file name
612 * object (typically a string) as the script's origin.
613 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000614 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100615 * \param file_name file name object (typically a string) to be used
Andrei Popescu402d9372010-02-26 13:31:12 +0000616 * as the script's origin.
617 * \return Compiled script object (context independent; when run it
618 * will use the currently entered context).
619 */
620 static Local<Script> New(Handle<String> source,
621 Handle<Value> file_name);
622
623 /**
624 * Compiles the specified script (bound to current context).
625 *
626 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100627 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000628 * when Compile() returns
629 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
630 * using pre_data speeds compilation if it's done multiple times.
631 * Owned by caller, no references are kept when Compile() returns.
632 * \param script_data Arbitrary data associated with script. Using
633 * this has same effect as calling SetData(), but makes data available
634 * earlier (i.e. to compile event handlers).
635 * \return Compiled script object, bound to the context that was active
636 * when this function was called. When run it will always use this
637 * context.
Steve Blocka7e24c12009-10-30 11:49:00 +0000638 */
639 static Local<Script> Compile(Handle<String> source,
Andrei Popescu402d9372010-02-26 13:31:12 +0000640 ScriptOrigin* origin = NULL,
641 ScriptData* pre_data = NULL,
642 Handle<String> script_data = Handle<String>());
643
644 /**
645 * Compiles the specified script using the specified file name
646 * object (typically a string) as the script's origin.
647 *
648 * \param source Script source code.
649 * \param file_name File name to use as script's origin
650 * \param script_data Arbitrary data associated with script. Using
651 * this has same effect as calling SetData(), but makes data available
652 * earlier (i.e. to compile event handlers).
653 * \return Compiled script object, bound to the context that was active
654 * when this function was called. When run it will always use this
655 * context.
656 */
657 static Local<Script> Compile(Handle<String> source,
658 Handle<Value> file_name,
659 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000660
661 /**
662 * Runs the script returning the resulting value. If the script is
663 * context independent (created using ::New) it will be run in the
664 * currently entered context. If it is context specific (created
665 * using ::Compile) it will be run in the context in which it was
666 * compiled.
667 */
668 Local<Value> Run();
669
670 /**
671 * Returns the script id value.
672 */
673 Local<Value> Id();
674
675 /**
676 * Associate an additional data object with the script. This is mainly used
677 * with the debugger as this data object is only available through the
678 * debugger API.
679 */
Steve Blockd0582a62009-12-15 09:54:21 +0000680 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000681};
682
683
684/**
685 * An error message.
686 */
687class V8EXPORT Message {
688 public:
689 Local<String> Get() const;
690 Local<String> GetSourceLine() const;
691
692 /**
693 * Returns the resource name for the script from where the function causing
694 * the error originates.
695 */
696 Handle<Value> GetScriptResourceName() const;
697
698 /**
699 * Returns the resource data for the script from where the function causing
700 * the error originates.
701 */
702 Handle<Value> GetScriptData() const;
703
704 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100705 * Exception stack trace. By default stack traces are not captured for
706 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
707 * to change this option.
708 */
709 Handle<StackTrace> GetStackTrace() const;
710
711 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000712 * Returns the number, 1-based, of the line where the error occurred.
713 */
714 int GetLineNumber() const;
715
716 /**
717 * Returns the index within the script of the first character where
718 * the error occurred.
719 */
720 int GetStartPosition() const;
721
722 /**
723 * Returns the index within the script of the last character where
724 * the error occurred.
725 */
726 int GetEndPosition() const;
727
728 /**
729 * Returns the index within the line of the first character where
730 * the error occurred.
731 */
732 int GetStartColumn() const;
733
734 /**
735 * Returns the index within the line of the last character where
736 * the error occurred.
737 */
738 int GetEndColumn() const;
739
740 // TODO(1245381): Print to a string instead of on a FILE.
741 static void PrintCurrentStackTrace(FILE* out);
Kristian Monsen25f61362010-05-21 11:50:48 +0100742
743 static const int kNoLineNumberInfo = 0;
744 static const int kNoColumnInfo = 0;
745};
746
747
748/**
749 * Representation of a JavaScript stack trace. The information collected is a
750 * snapshot of the execution stack and the information remains valid after
751 * execution continues.
752 */
753class V8EXPORT StackTrace {
754 public:
755 /**
756 * Flags that determine what information is placed captured for each
757 * StackFrame when grabbing the current stack trace.
758 */
759 enum StackTraceOptions {
760 kLineNumber = 1,
761 kColumnOffset = 1 << 1 | kLineNumber,
762 kScriptName = 1 << 2,
763 kFunctionName = 1 << 3,
764 kIsEval = 1 << 4,
765 kIsConstructor = 1 << 5,
Ben Murdochf87a2032010-10-22 12:50:53 +0100766 kScriptNameOrSourceURL = 1 << 6,
Kristian Monsen25f61362010-05-21 11:50:48 +0100767 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
Ben Murdochf87a2032010-10-22 12:50:53 +0100768 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
Kristian Monsen25f61362010-05-21 11:50:48 +0100769 };
770
771 /**
772 * Returns a StackFrame at a particular index.
773 */
774 Local<StackFrame> GetFrame(uint32_t index) const;
775
776 /**
777 * Returns the number of StackFrames.
778 */
779 int GetFrameCount() const;
780
781 /**
782 * Returns StackTrace as a v8::Array that contains StackFrame objects.
783 */
784 Local<Array> AsArray();
785
786 /**
Ben Murdoch257744e2011-11-30 15:57:28 +0000787 * Grab a snapshot of the current JavaScript execution stack.
Kristian Monsen25f61362010-05-21 11:50:48 +0100788 *
789 * \param frame_limit The maximum number of stack frames we want to capture.
790 * \param options Enumerates the set of things we will capture for each
791 * StackFrame.
792 */
793 static Local<StackTrace> CurrentStackTrace(
794 int frame_limit,
795 StackTraceOptions options = kOverview);
796};
797
798
799/**
800 * A single JavaScript stack frame.
801 */
802class V8EXPORT StackFrame {
803 public:
804 /**
805 * Returns the number, 1-based, of the line for the associate function call.
806 * This method will return Message::kNoLineNumberInfo if it is unable to
807 * retrieve the line number, or if kLineNumber was not passed as an option
808 * when capturing the StackTrace.
809 */
810 int GetLineNumber() const;
811
812 /**
813 * Returns the 1-based column offset on the line for the associated function
814 * call.
815 * This method will return Message::kNoColumnInfo if it is unable to retrieve
816 * the column number, or if kColumnOffset was not passed as an option when
817 * capturing the StackTrace.
818 */
819 int GetColumn() const;
820
821 /**
822 * Returns the name of the resource that contains the script for the
823 * function for this StackFrame.
824 */
825 Local<String> GetScriptName() const;
826
827 /**
Ben Murdochf87a2032010-10-22 12:50:53 +0100828 * Returns the name of the resource that contains the script for the
829 * function for this StackFrame or sourceURL value if the script name
830 * is undefined and its source ends with //@ sourceURL=... string.
831 */
832 Local<String> GetScriptNameOrSourceURL() const;
833
834 /**
Kristian Monsen25f61362010-05-21 11:50:48 +0100835 * Returns the name of the function associated with this stack frame.
836 */
837 Local<String> GetFunctionName() const;
838
839 /**
840 * Returns whether or not the associated function is compiled via a call to
841 * eval().
842 */
843 bool IsEval() const;
844
845 /**
Ben Murdoch257744e2011-11-30 15:57:28 +0000846 * Returns whether or not the associated function is called as a
Kristian Monsen25f61362010-05-21 11:50:48 +0100847 * constructor via "new".
848 */
849 bool IsConstructor() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000850};
851
852
Ben Murdoch257744e2011-11-30 15:57:28 +0000853// --- Value ---
Steve Blocka7e24c12009-10-30 11:49:00 +0000854
855
856/**
857 * The superclass of all JavaScript values and objects.
858 */
Steve Block8defd9f2010-07-08 12:39:36 +0100859class Value : public Data {
Steve Blocka7e24c12009-10-30 11:49:00 +0000860 public:
861
862 /**
863 * Returns true if this value is the undefined value. See ECMA-262
864 * 4.3.10.
865 */
Steve Block8defd9f2010-07-08 12:39:36 +0100866 V8EXPORT bool IsUndefined() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000867
868 /**
869 * Returns true if this value is the null value. See ECMA-262
870 * 4.3.11.
871 */
Steve Block8defd9f2010-07-08 12:39:36 +0100872 V8EXPORT bool IsNull() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000873
874 /**
875 * Returns true if this value is true.
876 */
Steve Block8defd9f2010-07-08 12:39:36 +0100877 V8EXPORT bool IsTrue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000878
879 /**
880 * Returns true if this value is false.
881 */
Steve Block8defd9f2010-07-08 12:39:36 +0100882 V8EXPORT bool IsFalse() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000883
884 /**
885 * Returns true if this value is an instance of the String type.
886 * See ECMA-262 8.4.
887 */
888 inline bool IsString() const;
889
890 /**
891 * Returns true if this value is a function.
892 */
Steve Block8defd9f2010-07-08 12:39:36 +0100893 V8EXPORT bool IsFunction() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000894
895 /**
896 * Returns true if this value is an array.
897 */
Steve Block8defd9f2010-07-08 12:39:36 +0100898 V8EXPORT bool IsArray() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000899
900 /**
901 * Returns true if this value is an object.
902 */
Steve Block8defd9f2010-07-08 12:39:36 +0100903 V8EXPORT bool IsObject() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000904
905 /**
906 * Returns true if this value is boolean.
907 */
Steve Block8defd9f2010-07-08 12:39:36 +0100908 V8EXPORT bool IsBoolean() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000909
910 /**
911 * Returns true if this value is a number.
912 */
Steve Block8defd9f2010-07-08 12:39:36 +0100913 V8EXPORT bool IsNumber() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000914
915 /**
916 * Returns true if this value is external.
917 */
Steve Block8defd9f2010-07-08 12:39:36 +0100918 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000919
920 /**
921 * Returns true if this value is a 32-bit signed integer.
922 */
Steve Block8defd9f2010-07-08 12:39:36 +0100923 V8EXPORT bool IsInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000924
925 /**
Steve Block6ded16b2010-05-10 14:33:55 +0100926 * Returns true if this value is a 32-bit unsigned integer.
927 */
Steve Block8defd9f2010-07-08 12:39:36 +0100928 V8EXPORT bool IsUint32() const;
Steve Block6ded16b2010-05-10 14:33:55 +0100929
930 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000931 * Returns true if this value is a Date.
932 */
Steve Block8defd9f2010-07-08 12:39:36 +0100933 V8EXPORT bool IsDate() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000934
Iain Merrick75681382010-08-19 15:07:18 +0100935 /**
936 * Returns true if this value is a RegExp.
937 */
938 V8EXPORT bool IsRegExp() const;
939
Steve Block8defd9f2010-07-08 12:39:36 +0100940 V8EXPORT Local<Boolean> ToBoolean() const;
941 V8EXPORT Local<Number> ToNumber() const;
942 V8EXPORT Local<String> ToString() const;
943 V8EXPORT Local<String> ToDetailString() const;
944 V8EXPORT Local<Object> ToObject() const;
945 V8EXPORT Local<Integer> ToInteger() const;
946 V8EXPORT Local<Uint32> ToUint32() const;
947 V8EXPORT Local<Int32> ToInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000948
949 /**
950 * Attempts to convert a string to an array index.
951 * Returns an empty handle if the conversion fails.
952 */
Steve Block8defd9f2010-07-08 12:39:36 +0100953 V8EXPORT Local<Uint32> ToArrayIndex() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000954
Steve Block8defd9f2010-07-08 12:39:36 +0100955 V8EXPORT bool BooleanValue() const;
956 V8EXPORT double NumberValue() const;
957 V8EXPORT int64_t IntegerValue() const;
958 V8EXPORT uint32_t Uint32Value() const;
959 V8EXPORT int32_t Int32Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000960
961 /** JS == */
Steve Block8defd9f2010-07-08 12:39:36 +0100962 V8EXPORT bool Equals(Handle<Value> that) const;
963 V8EXPORT bool StrictEquals(Handle<Value> that) const;
Steve Block3ce2e202009-11-05 08:53:23 +0000964
Steve Blocka7e24c12009-10-30 11:49:00 +0000965 private:
966 inline bool QuickIsString() const;
Steve Block8defd9f2010-07-08 12:39:36 +0100967 V8EXPORT bool FullIsString() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000968};
969
970
971/**
972 * The superclass of primitive values. See ECMA-262 4.3.2.
973 */
Steve Block8defd9f2010-07-08 12:39:36 +0100974class Primitive : public Value { };
Steve Blocka7e24c12009-10-30 11:49:00 +0000975
976
977/**
978 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
979 * or false value.
980 */
Steve Block8defd9f2010-07-08 12:39:36 +0100981class Boolean : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000982 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100983 V8EXPORT bool Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000984 static inline Handle<Boolean> New(bool value);
985};
986
987
988/**
989 * A JavaScript string value (ECMA-262, 4.3.17).
990 */
Steve Block8defd9f2010-07-08 12:39:36 +0100991class String : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000992 public:
993
994 /**
995 * Returns the number of characters in this string.
996 */
Steve Block8defd9f2010-07-08 12:39:36 +0100997 V8EXPORT int Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000998
999 /**
1000 * Returns the number of bytes in the UTF-8 encoded
1001 * representation of this string.
1002 */
Steve Block8defd9f2010-07-08 12:39:36 +01001003 V8EXPORT int Utf8Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001004
1005 /**
1006 * Write the contents of the string to an external buffer.
1007 * If no arguments are given, expects the buffer to be large
1008 * enough to hold the entire string and NULL terminator. Copies
1009 * the contents of the string and the NULL terminator into the
1010 * buffer.
1011 *
Ben Murdochb0fe1622011-05-05 13:52:32 +01001012 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1013 * before the end of the buffer.
1014 *
Steve Blocka7e24c12009-10-30 11:49:00 +00001015 * Copies up to length characters into the output buffer.
1016 * Only null-terminates if there is enough space in the buffer.
1017 *
1018 * \param buffer The buffer into which the string will be copied.
1019 * \param start The starting position within the string at which
1020 * copying begins.
Ben Murdochb0fe1622011-05-05 13:52:32 +01001021 * \param length The number of characters to copy from the string. For
1022 * WriteUtf8 the number of bytes in the buffer.
Steve Block6ded16b2010-05-10 14:33:55 +01001023 * \param nchars_ref The number of characters written, can be NULL.
1024 * \param hints Various hints that might affect performance of this or
1025 * subsequent operations.
Ben Murdochb0fe1622011-05-05 13:52:32 +01001026 * \return The number of characters copied to the buffer excluding the null
1027 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1028 * including the null terminator.
Steve Blocka7e24c12009-10-30 11:49:00 +00001029 */
Steve Block6ded16b2010-05-10 14:33:55 +01001030 enum WriteHints {
1031 NO_HINTS = 0,
1032 HINT_MANY_WRITES_EXPECTED = 1
1033 };
1034
Steve Block8defd9f2010-07-08 12:39:36 +01001035 V8EXPORT int Write(uint16_t* buffer,
1036 int start = 0,
1037 int length = -1,
1038 WriteHints hints = NO_HINTS) const; // UTF-16
1039 V8EXPORT int WriteAscii(char* buffer,
1040 int start = 0,
1041 int length = -1,
1042 WriteHints hints = NO_HINTS) const; // ASCII
1043 V8EXPORT int WriteUtf8(char* buffer,
1044 int length = -1,
1045 int* nchars_ref = NULL,
1046 WriteHints hints = NO_HINTS) const; // UTF-8
Steve Blocka7e24c12009-10-30 11:49:00 +00001047
1048 /**
1049 * A zero length string.
1050 */
Steve Block8defd9f2010-07-08 12:39:36 +01001051 V8EXPORT static v8::Local<v8::String> Empty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001052
1053 /**
1054 * Returns true if the string is external
1055 */
Steve Block8defd9f2010-07-08 12:39:36 +01001056 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001057
1058 /**
1059 * Returns true if the string is both external and ascii
1060 */
Steve Block8defd9f2010-07-08 12:39:36 +01001061 V8EXPORT bool IsExternalAscii() const;
Leon Clarkee46be812010-01-19 14:06:41 +00001062
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001063 class V8EXPORT ExternalStringResourceBase { // NOLINT
Leon Clarkee46be812010-01-19 14:06:41 +00001064 public:
1065 virtual ~ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001066
Leon Clarkee46be812010-01-19 14:06:41 +00001067 protected:
1068 ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001069
1070 /**
1071 * Internally V8 will call this Dispose method when the external string
1072 * resource is no longer needed. The default implementation will use the
1073 * delete operator. This method can be overridden in subclasses to
1074 * control how allocated external string resources are disposed.
1075 */
1076 virtual void Dispose() { delete this; }
1077
Leon Clarkee46be812010-01-19 14:06:41 +00001078 private:
1079 // Disallow copying and assigning.
1080 ExternalStringResourceBase(const ExternalStringResourceBase&);
1081 void operator=(const ExternalStringResourceBase&);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001082
1083 friend class v8::internal::Heap;
Leon Clarkee46be812010-01-19 14:06:41 +00001084 };
1085
Steve Blocka7e24c12009-10-30 11:49:00 +00001086 /**
1087 * An ExternalStringResource is a wrapper around a two-byte string
1088 * buffer that resides outside V8's heap. Implement an
1089 * ExternalStringResource to manage the life cycle of the underlying
1090 * buffer. Note that the string data must be immutable.
1091 */
Leon Clarkee46be812010-01-19 14:06:41 +00001092 class V8EXPORT ExternalStringResource
1093 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001094 public:
1095 /**
1096 * Override the destructor to manage the life cycle of the underlying
1097 * buffer.
1098 */
1099 virtual ~ExternalStringResource() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001100
1101 /**
1102 * The string data from the underlying buffer.
1103 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001104 virtual const uint16_t* data() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001105
1106 /**
1107 * The length of the string. That is, the number of two-byte characters.
1108 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001109 virtual size_t length() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001110
Steve Blocka7e24c12009-10-30 11:49:00 +00001111 protected:
1112 ExternalStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001113 };
1114
1115 /**
1116 * An ExternalAsciiStringResource is a wrapper around an ascii
1117 * string buffer that resides outside V8's heap. Implement an
1118 * ExternalAsciiStringResource to manage the life cycle of the
1119 * underlying buffer. Note that the string data must be immutable
1120 * and that the data must be strict 7-bit ASCII, not Latin1 or
1121 * UTF-8, which would require special treatment internally in the
1122 * engine and, in the case of UTF-8, do not allow efficient indexing.
1123 * Use String::New or convert to 16 bit data for non-ASCII.
1124 */
1125
Leon Clarkee46be812010-01-19 14:06:41 +00001126 class V8EXPORT ExternalAsciiStringResource
1127 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001128 public:
1129 /**
1130 * Override the destructor to manage the life cycle of the underlying
1131 * buffer.
1132 */
1133 virtual ~ExternalAsciiStringResource() {}
1134 /** The string data from the underlying buffer.*/
1135 virtual const char* data() const = 0;
1136 /** The number of ascii characters in the string.*/
1137 virtual size_t length() const = 0;
1138 protected:
1139 ExternalAsciiStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001140 };
1141
1142 /**
1143 * Get the ExternalStringResource for an external string. Returns
1144 * NULL if IsExternal() doesn't return true.
1145 */
1146 inline ExternalStringResource* GetExternalStringResource() const;
1147
1148 /**
1149 * Get the ExternalAsciiStringResource for an external ascii string.
1150 * Returns NULL if IsExternalAscii() doesn't return true.
1151 */
Steve Block8defd9f2010-07-08 12:39:36 +01001152 V8EXPORT ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001153
1154 static inline String* Cast(v8::Value* obj);
1155
1156 /**
1157 * Allocates a new string from either utf-8 encoded or ascii data.
1158 * The second parameter 'length' gives the buffer length.
1159 * If the data is utf-8 encoded, the caller must
1160 * be careful to supply the length parameter.
1161 * If it is not given, the function calls
1162 * 'strlen' to determine the buffer length, it might be
1163 * wrong if 'data' contains a null character.
1164 */
Steve Block8defd9f2010-07-08 12:39:36 +01001165 V8EXPORT static Local<String> New(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001166
1167 /** Allocates a new string from utf16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001168 V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001169
1170 /** Creates a symbol. Returns one if it exists already.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001171 V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001172
1173 /**
Steve Block3ce2e202009-11-05 08:53:23 +00001174 * Creates a new string by concatenating the left and the right strings
1175 * passed in as parameters.
1176 */
Steve Block8defd9f2010-07-08 12:39:36 +01001177 V8EXPORT static Local<String> Concat(Handle<String> left,
1178 Handle<String>right);
Steve Block3ce2e202009-11-05 08:53:23 +00001179
1180 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001181 * Creates a new external string using the data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001182 * resource. When the external string is no longer live on V8's heap the
1183 * resource will be disposed by calling its Dispose method. The caller of
1184 * this function should not otherwise delete or modify the resource. Neither
1185 * should the underlying buffer be deallocated or modified except through the
1186 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001187 */
Steve Block8defd9f2010-07-08 12:39:36 +01001188 V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001189
1190 /**
1191 * Associate an external string resource with this string by transforming it
1192 * in place so that existing references to this string in the JavaScript heap
1193 * will use the external string resource. The external string resource's
Ben Murdoch257744e2011-11-30 15:57:28 +00001194 * character contents need to be equivalent to this string.
Steve Blocka7e24c12009-10-30 11:49:00 +00001195 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001196 * The string is not modified if the operation fails. See NewExternal for
1197 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001198 */
Steve Block8defd9f2010-07-08 12:39:36 +01001199 V8EXPORT bool MakeExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001200
1201 /**
1202 * Creates a new external string using the ascii data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001203 * resource. When the external string is no longer live on V8's heap the
1204 * resource will be disposed by calling its Dispose method. The caller of
1205 * this function should not otherwise delete or modify the resource. Neither
1206 * should the underlying buffer be deallocated or modified except through the
1207 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001208 */
Steve Block8defd9f2010-07-08 12:39:36 +01001209 V8EXPORT static Local<String> NewExternal(
1210 ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001211
1212 /**
1213 * Associate an external string resource with this string by transforming it
1214 * in place so that existing references to this string in the JavaScript heap
1215 * will use the external string resource. The external string resource's
Ben Murdoch257744e2011-11-30 15:57:28 +00001216 * character contents need to be equivalent to this string.
Steve Blocka7e24c12009-10-30 11:49:00 +00001217 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001218 * The string is not modified if the operation fails. See NewExternal for
1219 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001220 */
Steve Block8defd9f2010-07-08 12:39:36 +01001221 V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001222
1223 /**
1224 * Returns true if this string can be made external.
1225 */
Steve Block8defd9f2010-07-08 12:39:36 +01001226 V8EXPORT bool CanMakeExternal();
Steve Blocka7e24c12009-10-30 11:49:00 +00001227
1228 /** Creates an undetectable string from the supplied ascii or utf-8 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001229 V8EXPORT static Local<String> NewUndetectable(const char* data,
1230 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001231
1232 /** Creates an undetectable string from the supplied utf-16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001233 V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1234 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001235
1236 /**
1237 * Converts an object to a utf8-encoded character array. Useful if
1238 * you want to print the object. If conversion to a string fails
1239 * (eg. due to an exception in the toString() method of the object)
1240 * then the length() method returns 0 and the * operator returns
1241 * NULL.
1242 */
1243 class V8EXPORT Utf8Value {
1244 public:
1245 explicit Utf8Value(Handle<v8::Value> obj);
1246 ~Utf8Value();
1247 char* operator*() { return str_; }
1248 const char* operator*() const { return str_; }
1249 int length() const { return length_; }
1250 private:
1251 char* str_;
1252 int length_;
1253
1254 // Disallow copying and assigning.
1255 Utf8Value(const Utf8Value&);
1256 void operator=(const Utf8Value&);
1257 };
1258
1259 /**
1260 * Converts an object to an ascii string.
1261 * Useful if you want to print the object.
1262 * If conversion to a string fails (eg. due to an exception in the toString()
1263 * method of the object) then the length() method returns 0 and the * operator
1264 * returns NULL.
1265 */
1266 class V8EXPORT AsciiValue {
1267 public:
1268 explicit AsciiValue(Handle<v8::Value> obj);
1269 ~AsciiValue();
1270 char* operator*() { return str_; }
1271 const char* operator*() const { return str_; }
1272 int length() const { return length_; }
1273 private:
1274 char* str_;
1275 int length_;
1276
1277 // Disallow copying and assigning.
1278 AsciiValue(const AsciiValue&);
1279 void operator=(const AsciiValue&);
1280 };
1281
1282 /**
1283 * Converts an object to a two-byte string.
1284 * If conversion to a string fails (eg. due to an exception in the toString()
1285 * method of the object) then the length() method returns 0 and the * operator
1286 * returns NULL.
1287 */
1288 class V8EXPORT Value {
1289 public:
1290 explicit Value(Handle<v8::Value> obj);
1291 ~Value();
1292 uint16_t* operator*() { return str_; }
1293 const uint16_t* operator*() const { return str_; }
1294 int length() const { return length_; }
1295 private:
1296 uint16_t* str_;
1297 int length_;
1298
1299 // Disallow copying and assigning.
1300 Value(const Value&);
1301 void operator=(const Value&);
1302 };
Steve Block3ce2e202009-11-05 08:53:23 +00001303
Steve Blocka7e24c12009-10-30 11:49:00 +00001304 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001305 V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1306 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001307};
1308
1309
1310/**
1311 * A JavaScript number value (ECMA-262, 4.3.20)
1312 */
Steve Block8defd9f2010-07-08 12:39:36 +01001313class Number : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +00001314 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001315 V8EXPORT double Value() const;
1316 V8EXPORT static Local<Number> New(double value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001317 static inline Number* Cast(v8::Value* obj);
1318 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001319 V8EXPORT Number();
Steve Blocka7e24c12009-10-30 11:49:00 +00001320 static void CheckCast(v8::Value* obj);
1321};
1322
1323
1324/**
1325 * A JavaScript value representing a signed integer.
1326 */
Steve Block8defd9f2010-07-08 12:39:36 +01001327class Integer : public Number {
Steve Blocka7e24c12009-10-30 11:49:00 +00001328 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001329 V8EXPORT static Local<Integer> New(int32_t value);
1330 V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1331 V8EXPORT int64_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001332 static inline Integer* Cast(v8::Value* obj);
1333 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001334 V8EXPORT Integer();
1335 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001336};
1337
1338
1339/**
1340 * A JavaScript value representing a 32-bit signed integer.
1341 */
Steve Block8defd9f2010-07-08 12:39:36 +01001342class Int32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001343 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001344 V8EXPORT int32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001345 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001346 V8EXPORT Int32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001347};
1348
1349
1350/**
1351 * A JavaScript value representing a 32-bit unsigned integer.
1352 */
Steve Block8defd9f2010-07-08 12:39:36 +01001353class Uint32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001354 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001355 V8EXPORT uint32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001356 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001357 V8EXPORT Uint32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001358};
1359
1360
Steve Blocka7e24c12009-10-30 11:49:00 +00001361enum PropertyAttribute {
1362 None = 0,
1363 ReadOnly = 1 << 0,
1364 DontEnum = 1 << 1,
1365 DontDelete = 1 << 2
1366};
1367
Steve Block3ce2e202009-11-05 08:53:23 +00001368enum ExternalArrayType {
1369 kExternalByteArray = 1,
1370 kExternalUnsignedByteArray,
1371 kExternalShortArray,
1372 kExternalUnsignedShortArray,
1373 kExternalIntArray,
1374 kExternalUnsignedIntArray,
Steve Block44f0eee2011-05-26 01:26:41 +01001375 kExternalFloatArray,
Ben Murdoch257744e2011-11-30 15:57:28 +00001376 kExternalDoubleArray,
Steve Block44f0eee2011-05-26 01:26:41 +01001377 kExternalPixelArray
Steve Block3ce2e202009-11-05 08:53:23 +00001378};
1379
Steve Blocka7e24c12009-10-30 11:49:00 +00001380/**
Leon Clarkef7060e22010-06-03 12:02:55 +01001381 * Accessor[Getter|Setter] are used as callback functions when
1382 * setting|getting a particular property. See Object and ObjectTemplate's
1383 * method SetAccessor.
1384 */
1385typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1386 const AccessorInfo& info);
1387
1388
1389typedef void (*AccessorSetter)(Local<String> property,
1390 Local<Value> value,
1391 const AccessorInfo& info);
1392
1393
1394/**
1395 * Access control specifications.
1396 *
1397 * Some accessors should be accessible across contexts. These
1398 * accessors have an explicit access control parameter which specifies
1399 * the kind of cross-context access that should be allowed.
1400 *
1401 * Additionally, for security, accessors can prohibit overwriting by
1402 * accessors defined in JavaScript. For objects that have such
1403 * accessors either locally or in their prototype chain it is not
1404 * possible to overwrite the accessor by using __defineGetter__ or
1405 * __defineSetter__ from JavaScript code.
1406 */
1407enum AccessControl {
1408 DEFAULT = 0,
1409 ALL_CAN_READ = 1,
1410 ALL_CAN_WRITE = 1 << 1,
1411 PROHIBITS_OVERWRITING = 1 << 2
1412};
1413
1414
1415/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001416 * A JavaScript object (ECMA-262, 4.3.3)
1417 */
Steve Block8defd9f2010-07-08 12:39:36 +01001418class Object : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001419 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001420 V8EXPORT bool Set(Handle<Value> key,
1421 Handle<Value> value,
1422 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001423
Steve Block8defd9f2010-07-08 12:39:36 +01001424 V8EXPORT bool Set(uint32_t index,
1425 Handle<Value> value);
Steve Block6ded16b2010-05-10 14:33:55 +01001426
Steve Blocka7e24c12009-10-30 11:49:00 +00001427 // Sets a local property on this object bypassing interceptors and
1428 // overriding accessors or read-only properties.
1429 //
1430 // Note that if the object has an interceptor the property will be set
1431 // locally, but since the interceptor takes precedence the local property
1432 // will only be returned if the interceptor doesn't return a value.
1433 //
1434 // Note also that this only works for named properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001435 V8EXPORT bool ForceSet(Handle<Value> key,
1436 Handle<Value> value,
1437 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001438
Steve Block8defd9f2010-07-08 12:39:36 +01001439 V8EXPORT Local<Value> Get(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001440
Steve Block8defd9f2010-07-08 12:39:36 +01001441 V8EXPORT Local<Value> Get(uint32_t index);
Steve Block6ded16b2010-05-10 14:33:55 +01001442
Steve Blocka7e24c12009-10-30 11:49:00 +00001443 // TODO(1245389): Replace the type-specific versions of these
1444 // functions with generic ones that accept a Handle<Value> key.
Steve Block8defd9f2010-07-08 12:39:36 +01001445 V8EXPORT bool Has(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001446
Steve Block8defd9f2010-07-08 12:39:36 +01001447 V8EXPORT bool Delete(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001448
1449 // Delete a property on this object bypassing interceptors and
1450 // ignoring dont-delete attributes.
Steve Block8defd9f2010-07-08 12:39:36 +01001451 V8EXPORT bool ForceDelete(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001452
Steve Block8defd9f2010-07-08 12:39:36 +01001453 V8EXPORT bool Has(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001454
Steve Block8defd9f2010-07-08 12:39:36 +01001455 V8EXPORT bool Delete(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001456
Steve Block8defd9f2010-07-08 12:39:36 +01001457 V8EXPORT bool SetAccessor(Handle<String> name,
1458 AccessorGetter getter,
1459 AccessorSetter setter = 0,
1460 Handle<Value> data = Handle<Value>(),
1461 AccessControl settings = DEFAULT,
1462 PropertyAttribute attribute = None);
Leon Clarkef7060e22010-06-03 12:02:55 +01001463
Steve Blocka7e24c12009-10-30 11:49:00 +00001464 /**
1465 * Returns an array containing the names of the enumerable properties
1466 * of this object, including properties from prototype objects. The
1467 * array returned by this method contains the same values as would
1468 * be enumerated by a for-in statement over this object.
1469 */
Steve Block8defd9f2010-07-08 12:39:36 +01001470 V8EXPORT Local<Array> GetPropertyNames();
Steve Blocka7e24c12009-10-30 11:49:00 +00001471
1472 /**
1473 * Get the prototype object. This does not skip objects marked to
1474 * be skipped by __proto__ and it does not consult the security
1475 * handler.
1476 */
Steve Block8defd9f2010-07-08 12:39:36 +01001477 V8EXPORT Local<Value> GetPrototype();
Steve Blocka7e24c12009-10-30 11:49:00 +00001478
1479 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00001480 * Set the prototype object. This does not skip objects marked to
1481 * be skipped by __proto__ and it does not consult the security
1482 * handler.
1483 */
Steve Block8defd9f2010-07-08 12:39:36 +01001484 V8EXPORT bool SetPrototype(Handle<Value> prototype);
Andrei Popescu402d9372010-02-26 13:31:12 +00001485
1486 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001487 * Finds an instance of the given function template in the prototype
1488 * chain.
1489 */
Steve Block8defd9f2010-07-08 12:39:36 +01001490 V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1491 Handle<FunctionTemplate> tmpl);
Steve Blocka7e24c12009-10-30 11:49:00 +00001492
1493 /**
1494 * Call builtin Object.prototype.toString on this object.
1495 * This is different from Value::ToString() that may call
1496 * user-defined toString function. This one does not.
1497 */
Steve Block8defd9f2010-07-08 12:39:36 +01001498 V8EXPORT Local<String> ObjectProtoToString();
Steve Blocka7e24c12009-10-30 11:49:00 +00001499
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08001500 /**
1501 * Returns the name of the function invoked as a constructor for this object.
1502 */
1503 V8EXPORT Local<String> GetConstructorName();
1504
Steve Blocka7e24c12009-10-30 11:49:00 +00001505 /** Gets the number of internal fields for this Object. */
Steve Block8defd9f2010-07-08 12:39:36 +01001506 V8EXPORT int InternalFieldCount();
Steve Blocka7e24c12009-10-30 11:49:00 +00001507 /** Gets the value in an internal field. */
1508 inline Local<Value> GetInternalField(int index);
1509 /** Sets the value in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001510 V8EXPORT void SetInternalField(int index, Handle<Value> value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001511
1512 /** Gets a native pointer from an internal field. */
1513 inline void* GetPointerFromInternalField(int index);
Steve Block3ce2e202009-11-05 08:53:23 +00001514
Steve Blocka7e24c12009-10-30 11:49:00 +00001515 /** Sets a native pointer in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001516 V8EXPORT void SetPointerInInternalField(int index, void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001517
1518 // Testers for local properties.
Ben Murdoch257744e2011-11-30 15:57:28 +00001519 V8EXPORT bool HasOwnProperty(Handle<String> key);
Steve Block8defd9f2010-07-08 12:39:36 +01001520 V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1521 V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1522 V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001523
1524 /**
1525 * If result.IsEmpty() no real property was located in the prototype chain.
1526 * This means interceptors in the prototype chain are not called.
1527 */
Steve Block8defd9f2010-07-08 12:39:36 +01001528 V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1529 Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001530
1531 /**
1532 * If result.IsEmpty() no real property was located on the object or
1533 * in the prototype chain.
1534 * This means interceptors in the prototype chain are not called.
1535 */
Steve Block8defd9f2010-07-08 12:39:36 +01001536 V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001537
1538 /** Tests for a named lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001539 V8EXPORT bool HasNamedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001540
1541 /** Tests for an index lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001542 V8EXPORT bool HasIndexedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001543
1544 /**
1545 * Turns on access check on the object if the object is an instance of
1546 * a template that has access check callbacks. If an object has no
1547 * access check info, the object cannot be accessed by anyone.
1548 */
Steve Block8defd9f2010-07-08 12:39:36 +01001549 V8EXPORT void TurnOnAccessCheck();
Steve Blocka7e24c12009-10-30 11:49:00 +00001550
1551 /**
Ben Murdoch257744e2011-11-30 15:57:28 +00001552 * Returns the identity hash for this object. The current implementation
1553 * uses a hidden property on the object to store the identity hash.
Steve Blocka7e24c12009-10-30 11:49:00 +00001554 *
1555 * The return value will never be 0. Also, it is not guaranteed to be
1556 * unique.
1557 */
Steve Block8defd9f2010-07-08 12:39:36 +01001558 V8EXPORT int GetIdentityHash();
Steve Blocka7e24c12009-10-30 11:49:00 +00001559
1560 /**
1561 * Access hidden properties on JavaScript objects. These properties are
1562 * hidden from the executing JavaScript and only accessible through the V8
1563 * C++ API. Hidden properties introduced by V8 internally (for example the
1564 * identity hash) are prefixed with "v8::".
1565 */
Steve Block8defd9f2010-07-08 12:39:36 +01001566 V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1567 V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1568 V8EXPORT bool DeleteHiddenValue(Handle<String> key);
Steve Block3ce2e202009-11-05 08:53:23 +00001569
Steve Blocka7e24c12009-10-30 11:49:00 +00001570 /**
1571 * Returns true if this is an instance of an api function (one
1572 * created from a function created from a function template) and has
1573 * been modified since it was created. Note that this method is
1574 * conservative and may return true for objects that haven't actually
1575 * been modified.
1576 */
Steve Block8defd9f2010-07-08 12:39:36 +01001577 V8EXPORT bool IsDirty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001578
1579 /**
1580 * Clone this object with a fast but shallow copy. Values will point
1581 * to the same values as the original object.
1582 */
Steve Block8defd9f2010-07-08 12:39:36 +01001583 V8EXPORT Local<Object> Clone();
Steve Blocka7e24c12009-10-30 11:49:00 +00001584
1585 /**
Ben Murdoch8b112d22011-06-08 16:22:53 +01001586 * Returns the context in which the object was created.
1587 */
1588 V8EXPORT Local<Context> CreationContext();
1589
1590 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001591 * Set the backing store of the indexed properties to be managed by the
1592 * embedding layer. Access to the indexed properties will follow the rules
1593 * spelled out in CanvasPixelArray.
1594 * Note: The embedding program still owns the data and needs to ensure that
1595 * the backing store is preserved while V8 has a reference.
1596 */
Steve Block8defd9f2010-07-08 12:39:36 +01001597 V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
Steve Block9fac8402011-05-12 15:51:54 +01001598 V8EXPORT bool HasIndexedPropertiesInPixelData();
1599 V8EXPORT uint8_t* GetIndexedPropertiesPixelData();
1600 V8EXPORT int GetIndexedPropertiesPixelDataLength();
Steve Blocka7e24c12009-10-30 11:49:00 +00001601
Steve Block3ce2e202009-11-05 08:53:23 +00001602 /**
1603 * Set the backing store of the indexed properties to be managed by the
1604 * embedding layer. Access to the indexed properties will follow the rules
1605 * spelled out for the CanvasArray subtypes in the WebGL specification.
1606 * Note: The embedding program still owns the data and needs to ensure that
1607 * the backing store is preserved while V8 has a reference.
1608 */
Steve Block8defd9f2010-07-08 12:39:36 +01001609 V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1610 void* data,
1611 ExternalArrayType array_type,
1612 int number_of_elements);
Steve Block9fac8402011-05-12 15:51:54 +01001613 V8EXPORT bool HasIndexedPropertiesInExternalArrayData();
1614 V8EXPORT void* GetIndexedPropertiesExternalArrayData();
1615 V8EXPORT ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1616 V8EXPORT int GetIndexedPropertiesExternalArrayDataLength();
Steve Block3ce2e202009-11-05 08:53:23 +00001617
Ben Murdoch257744e2011-11-30 15:57:28 +00001618 /**
1619 * Checks whether a callback is set by the
1620 * ObjectTemplate::SetCallAsFunctionHandler method.
1621 * When an Object is callable this method returns true.
1622 */
1623 V8EXPORT bool IsCallable();
1624
1625 /**
1626 * Call an Object as a function if a callback is set by the
1627 * ObjectTemplate::SetCallAsFunctionHandler method.
1628 */
1629 V8EXPORT Local<Value> CallAsFunction(Handle<Object> recv,
1630 int argc,
1631 Handle<Value> argv[]);
1632
1633 /**
1634 * Call an Object as a constructor if a callback is set by the
1635 * ObjectTemplate::SetCallAsFunctionHandler method.
1636 * Note: This method behaves like the Function::NewInstance method.
1637 */
1638 V8EXPORT Local<Value> CallAsConstructor(int argc,
1639 Handle<Value> argv[]);
1640
Steve Block8defd9f2010-07-08 12:39:36 +01001641 V8EXPORT static Local<Object> New();
Steve Blocka7e24c12009-10-30 11:49:00 +00001642 static inline Object* Cast(Value* obj);
1643 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001644 V8EXPORT Object();
1645 V8EXPORT static void CheckCast(Value* obj);
1646 V8EXPORT Local<Value> CheckedGetInternalField(int index);
1647 V8EXPORT void* SlowGetPointerFromInternalField(int index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001648
1649 /**
1650 * If quick access to the internal field is possible this method
Steve Block3ce2e202009-11-05 08:53:23 +00001651 * returns the value. Otherwise an empty handle is returned.
Steve Blocka7e24c12009-10-30 11:49:00 +00001652 */
1653 inline Local<Value> UncheckedGetInternalField(int index);
1654};
1655
1656
1657/**
1658 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1659 */
Steve Block8defd9f2010-07-08 12:39:36 +01001660class Array : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001661 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001662 V8EXPORT uint32_t Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001663
1664 /**
1665 * Clones an element at index |index|. Returns an empty
1666 * handle if cloning fails (for any reason).
1667 */
Steve Block8defd9f2010-07-08 12:39:36 +01001668 V8EXPORT Local<Object> CloneElementAt(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001669
Steve Block44f0eee2011-05-26 01:26:41 +01001670 /**
1671 * Creates a JavaScript array with the given length. If the length
1672 * is negative the returned array will have length 0.
1673 */
Steve Block8defd9f2010-07-08 12:39:36 +01001674 V8EXPORT static Local<Array> New(int length = 0);
Steve Block44f0eee2011-05-26 01:26:41 +01001675
Steve Blocka7e24c12009-10-30 11:49:00 +00001676 static inline Array* Cast(Value* obj);
1677 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001678 V8EXPORT Array();
Steve Blocka7e24c12009-10-30 11:49:00 +00001679 static void CheckCast(Value* obj);
1680};
1681
1682
1683/**
1684 * A JavaScript function object (ECMA-262, 15.3).
1685 */
Steve Block8defd9f2010-07-08 12:39:36 +01001686class Function : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001687 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001688 V8EXPORT Local<Object> NewInstance() const;
1689 V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1690 V8EXPORT Local<Value> Call(Handle<Object> recv,
1691 int argc,
1692 Handle<Value> argv[]);
1693 V8EXPORT void SetName(Handle<String> name);
1694 V8EXPORT Handle<Value> GetName() const;
Andrei Popescu402d9372010-02-26 13:31:12 +00001695
1696 /**
1697 * Returns zero based line number of function body and
1698 * kLineOffsetNotFound if no information available.
1699 */
Steve Block8defd9f2010-07-08 12:39:36 +01001700 V8EXPORT int GetScriptLineNumber() const;
1701 V8EXPORT ScriptOrigin GetScriptOrigin() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001702 static inline Function* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001703 V8EXPORT static const int kLineOffsetNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00001704 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001705 V8EXPORT Function();
1706 V8EXPORT static void CheckCast(Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001707};
1708
1709
1710/**
Ben Murdoch257744e2011-11-30 15:57:28 +00001711 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1712 */
1713class Date : public Object {
1714 public:
1715 V8EXPORT static Local<Value> New(double time);
1716
1717 /**
1718 * A specialization of Value::NumberValue that is more efficient
1719 * because we know the structure of this object.
1720 */
1721 V8EXPORT double NumberValue() const;
1722
1723 static inline Date* Cast(v8::Value* obj);
1724
1725 /**
1726 * Notification that the embedder has changed the time zone,
1727 * daylight savings time, or other date / time configuration
1728 * parameters. V8 keeps a cache of various values used for
1729 * date / time computation. This notification will reset
1730 * those cached values for the current context so that date /
1731 * time configuration changes would be reflected in the Date
1732 * object.
1733 *
1734 * This API should not be called more than needed as it will
1735 * negatively impact the performance of date operations.
1736 */
1737 V8EXPORT static void DateTimeConfigurationChangeNotification();
1738
1739 private:
1740 V8EXPORT static void CheckCast(v8::Value* obj);
1741};
1742
1743
1744/**
1745 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1746 */
1747class RegExp : public Object {
1748 public:
1749 /**
1750 * Regular expression flag bits. They can be or'ed to enable a set
1751 * of flags.
1752 */
1753 enum Flags {
1754 kNone = 0,
1755 kGlobal = 1,
1756 kIgnoreCase = 2,
1757 kMultiline = 4
1758 };
1759
1760 /**
1761 * Creates a regular expression from the given pattern string and
1762 * the flags bit field. May throw a JavaScript exception as
1763 * described in ECMA-262, 15.10.4.1.
1764 *
1765 * For example,
1766 * RegExp::New(v8::String::New("foo"),
1767 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
1768 * is equivalent to evaluating "/foo/gm".
1769 */
1770 V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1771 Flags flags);
1772
1773 /**
1774 * Returns the value of the source property: a string representing
1775 * the regular expression.
1776 */
1777 V8EXPORT Local<String> GetSource() const;
1778
1779 /**
1780 * Returns the flags bit field.
1781 */
1782 V8EXPORT Flags GetFlags() const;
1783
1784 static inline RegExp* Cast(v8::Value* obj);
1785
1786 private:
1787 V8EXPORT static void CheckCast(v8::Value* obj);
1788};
1789
1790
1791/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001792 * A JavaScript value that wraps a C++ void*. This type of value is
1793 * mainly used to associate C++ data structures with JavaScript
1794 * objects.
1795 *
1796 * The Wrap function V8 will return the most optimal Value object wrapping the
1797 * C++ void*. The type of the value is not guaranteed to be an External object
1798 * and no assumptions about its type should be made. To access the wrapped
1799 * value Unwrap should be used, all other operations on that object will lead
1800 * to unpredictable results.
1801 */
Steve Block8defd9f2010-07-08 12:39:36 +01001802class External : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001803 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001804 V8EXPORT static Local<Value> Wrap(void* data);
Steve Blocka7e24c12009-10-30 11:49:00 +00001805 static inline void* Unwrap(Handle<Value> obj);
1806
Steve Block8defd9f2010-07-08 12:39:36 +01001807 V8EXPORT static Local<External> New(void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001808 static inline External* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001809 V8EXPORT void* Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001810 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001811 V8EXPORT External();
1812 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001813 static inline void* QuickUnwrap(Handle<v8::Value> obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001814 V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001815};
1816
1817
Ben Murdoch257744e2011-11-30 15:57:28 +00001818// --- Templates ---
Steve Blocka7e24c12009-10-30 11:49:00 +00001819
1820
1821/**
1822 * The superclass of object and function templates.
1823 */
1824class V8EXPORT Template : public Data {
1825 public:
1826 /** Adds a property to each instance created by this template.*/
1827 void Set(Handle<String> name, Handle<Data> value,
1828 PropertyAttribute attributes = None);
1829 inline void Set(const char* name, Handle<Data> value);
1830 private:
1831 Template();
1832
1833 friend class ObjectTemplate;
1834 friend class FunctionTemplate;
1835};
1836
1837
1838/**
1839 * The argument information given to function call callbacks. This
1840 * class provides access to information about the context of the call,
1841 * including the receiver, the number and values of arguments, and
1842 * the holder of the function.
1843 */
Steve Block8defd9f2010-07-08 12:39:36 +01001844class Arguments {
Steve Blocka7e24c12009-10-30 11:49:00 +00001845 public:
1846 inline int Length() const;
1847 inline Local<Value> operator[](int i) const;
1848 inline Local<Function> Callee() const;
1849 inline Local<Object> This() const;
1850 inline Local<Object> Holder() const;
1851 inline bool IsConstructCall() const;
1852 inline Local<Value> Data() const;
1853 private:
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001854 static const int kDataIndex = 0;
1855 static const int kCalleeIndex = -1;
1856 static const int kHolderIndex = -2;
1857
Steve Blocka7e24c12009-10-30 11:49:00 +00001858 friend class ImplementationUtilities;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001859 inline Arguments(internal::Object** implicit_args,
1860 internal::Object** values,
1861 int length,
1862 bool is_construct_call);
1863 internal::Object** implicit_args_;
1864 internal::Object** values_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001865 int length_;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001866 bool is_construct_call_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001867};
1868
1869
1870/**
1871 * The information passed to an accessor callback about the context
1872 * of the property access.
1873 */
1874class V8EXPORT AccessorInfo {
1875 public:
1876 inline AccessorInfo(internal::Object** args)
1877 : args_(args) { }
1878 inline Local<Value> Data() const;
1879 inline Local<Object> This() const;
1880 inline Local<Object> Holder() const;
1881 private:
1882 internal::Object** args_;
1883};
1884
1885
1886typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
1887
Steve Blocka7e24c12009-10-30 11:49:00 +00001888/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001889 * NamedProperty[Getter|Setter] are used as interceptors on object.
1890 * See ObjectTemplate::SetNamedPropertyHandler.
1891 */
1892typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
1893 const AccessorInfo& info);
1894
1895
1896/**
1897 * Returns the value if the setter intercepts the request.
1898 * Otherwise, returns an empty handle.
1899 */
1900typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
1901 Local<Value> value,
1902 const AccessorInfo& info);
1903
Steve Blocka7e24c12009-10-30 11:49:00 +00001904/**
1905 * Returns a non-empty handle if the interceptor intercepts the request.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001906 * The result is an integer encoding property attributes (like v8::None,
1907 * v8::DontEnum, etc.)
Steve Blocka7e24c12009-10-30 11:49:00 +00001908 */
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001909typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
1910 const AccessorInfo& info);
Steve Blocka7e24c12009-10-30 11:49:00 +00001911
1912
1913/**
1914 * Returns a non-empty handle if the deleter intercepts the request.
1915 * The return value is true if the property could be deleted and false
1916 * otherwise.
1917 */
1918typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
1919 const AccessorInfo& info);
1920
1921/**
1922 * Returns an array containing the names of the properties the named
1923 * property getter intercepts.
1924 */
1925typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
1926
1927
1928/**
1929 * Returns the value of the property if the getter intercepts the
1930 * request. Otherwise, returns an empty handle.
1931 */
1932typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
1933 const AccessorInfo& info);
1934
1935
1936/**
1937 * Returns the value if the setter intercepts the request.
1938 * Otherwise, returns an empty handle.
1939 */
1940typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
1941 Local<Value> value,
1942 const AccessorInfo& info);
1943
1944
1945/**
1946 * Returns a non-empty handle if the interceptor intercepts the request.
Iain Merrick75681382010-08-19 15:07:18 +01001947 * The result is an integer encoding property attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00001948 */
Iain Merrick75681382010-08-19 15:07:18 +01001949typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
Steve Blocka7e24c12009-10-30 11:49:00 +00001950 const AccessorInfo& info);
1951
1952/**
1953 * Returns a non-empty handle if the deleter intercepts the request.
1954 * The return value is true if the property could be deleted and false
1955 * otherwise.
1956 */
1957typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
1958 const AccessorInfo& info);
1959
1960/**
1961 * Returns an array containing the indices of the properties the
1962 * indexed property getter intercepts.
1963 */
1964typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
1965
1966
1967/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001968 * Access type specification.
1969 */
1970enum AccessType {
1971 ACCESS_GET,
1972 ACCESS_SET,
1973 ACCESS_HAS,
1974 ACCESS_DELETE,
1975 ACCESS_KEYS
1976};
1977
1978
1979/**
1980 * Returns true if cross-context access should be allowed to the named
1981 * property with the given key on the host object.
1982 */
1983typedef bool (*NamedSecurityCallback)(Local<Object> host,
1984 Local<Value> key,
1985 AccessType type,
1986 Local<Value> data);
1987
1988
1989/**
1990 * Returns true if cross-context access should be allowed to the indexed
1991 * property with the given index on the host object.
1992 */
1993typedef bool (*IndexedSecurityCallback)(Local<Object> host,
1994 uint32_t index,
1995 AccessType type,
1996 Local<Value> data);
1997
1998
1999/**
2000 * A FunctionTemplate is used to create functions at runtime. There
2001 * can only be one function created from a FunctionTemplate in a
2002 * context. The lifetime of the created function is equal to the
2003 * lifetime of the context. So in case the embedder needs to create
2004 * temporary functions that can be collected using Scripts is
2005 * preferred.
2006 *
2007 * A FunctionTemplate can have properties, these properties are added to the
2008 * function object when it is created.
2009 *
2010 * A FunctionTemplate has a corresponding instance template which is
2011 * used to create object instances when the function is used as a
2012 * constructor. Properties added to the instance template are added to
2013 * each object instance.
2014 *
2015 * A FunctionTemplate can have a prototype template. The prototype template
2016 * is used to create the prototype object of the function.
2017 *
2018 * The following example shows how to use a FunctionTemplate:
2019 *
2020 * \code
2021 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
2022 * t->Set("func_property", v8::Number::New(1));
2023 *
2024 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
2025 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
2026 * proto_t->Set("proto_const", v8::Number::New(2));
2027 *
2028 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
2029 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
2030 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
2031 * instance_t->Set("instance_property", Number::New(3));
2032 *
2033 * v8::Local<v8::Function> function = t->GetFunction();
2034 * v8::Local<v8::Object> instance = function->NewInstance();
2035 * \endcode
2036 *
2037 * Let's use "function" as the JS variable name of the function object
2038 * and "instance" for the instance object created above. The function
2039 * and the instance will have the following properties:
2040 *
2041 * \code
2042 * func_property in function == true;
2043 * function.func_property == 1;
2044 *
2045 * function.prototype.proto_method() invokes 'InvokeCallback'
2046 * function.prototype.proto_const == 2;
2047 *
2048 * instance instanceof function == true;
2049 * instance.instance_accessor calls 'InstanceAccessorCallback'
2050 * instance.instance_property == 3;
2051 * \endcode
2052 *
2053 * A FunctionTemplate can inherit from another one by calling the
2054 * FunctionTemplate::Inherit method. The following graph illustrates
2055 * the semantics of inheritance:
2056 *
2057 * \code
2058 * FunctionTemplate Parent -> Parent() . prototype -> { }
2059 * ^ ^
2060 * | Inherit(Parent) | .__proto__
2061 * | |
2062 * FunctionTemplate Child -> Child() . prototype -> { }
2063 * \endcode
2064 *
2065 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
2066 * object of the Child() function has __proto__ pointing to the
2067 * Parent() function's prototype object. An instance of the Child
2068 * function has all properties on Parent's instance templates.
2069 *
2070 * Let Parent be the FunctionTemplate initialized in the previous
2071 * section and create a Child FunctionTemplate by:
2072 *
2073 * \code
2074 * Local<FunctionTemplate> parent = t;
2075 * Local<FunctionTemplate> child = FunctionTemplate::New();
2076 * child->Inherit(parent);
2077 *
2078 * Local<Function> child_function = child->GetFunction();
2079 * Local<Object> child_instance = child_function->NewInstance();
2080 * \endcode
2081 *
2082 * The Child function and Child instance will have the following
2083 * properties:
2084 *
2085 * \code
2086 * child_func.prototype.__proto__ == function.prototype;
2087 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
2088 * child_instance.instance_property == 3;
2089 * \endcode
2090 */
2091class V8EXPORT FunctionTemplate : public Template {
2092 public:
2093 /** Creates a function template.*/
2094 static Local<FunctionTemplate> New(
2095 InvocationCallback callback = 0,
2096 Handle<Value> data = Handle<Value>(),
2097 Handle<Signature> signature = Handle<Signature>());
2098 /** Returns the unique function instance in the current execution context.*/
2099 Local<Function> GetFunction();
2100
2101 /**
2102 * Set the call-handler callback for a FunctionTemplate. This
2103 * callback is called whenever the function created from this
2104 * FunctionTemplate is called.
2105 */
2106 void SetCallHandler(InvocationCallback callback,
2107 Handle<Value> data = Handle<Value>());
2108
2109 /** Get the InstanceTemplate. */
2110 Local<ObjectTemplate> InstanceTemplate();
2111
2112 /** Causes the function template to inherit from a parent function template.*/
2113 void Inherit(Handle<FunctionTemplate> parent);
2114
2115 /**
2116 * A PrototypeTemplate is the template used to create the prototype object
2117 * of the function created by this template.
2118 */
2119 Local<ObjectTemplate> PrototypeTemplate();
2120
2121
2122 /**
2123 * Set the class name of the FunctionTemplate. This is used for
2124 * printing objects created with the function created from the
2125 * FunctionTemplate as its constructor.
2126 */
2127 void SetClassName(Handle<String> name);
2128
2129 /**
2130 * Determines whether the __proto__ accessor ignores instances of
2131 * the function template. If instances of the function template are
2132 * ignored, __proto__ skips all instances and instead returns the
2133 * next object in the prototype chain.
2134 *
2135 * Call with a value of true to make the __proto__ accessor ignore
2136 * instances of the function template. Call with a value of false
2137 * to make the __proto__ accessor not ignore instances of the
2138 * function template. By default, instances of a function template
2139 * are not ignored.
2140 */
2141 void SetHiddenPrototype(bool value);
2142
2143 /**
2144 * Returns true if the given object is an instance of this function
2145 * template.
2146 */
2147 bool HasInstance(Handle<Value> object);
2148
2149 private:
2150 FunctionTemplate();
2151 void AddInstancePropertyAccessor(Handle<String> name,
2152 AccessorGetter getter,
2153 AccessorSetter setter,
2154 Handle<Value> data,
2155 AccessControl settings,
2156 PropertyAttribute attributes);
2157 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2158 NamedPropertySetter setter,
2159 NamedPropertyQuery query,
2160 NamedPropertyDeleter remover,
2161 NamedPropertyEnumerator enumerator,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002162 Handle<Value> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00002163 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2164 IndexedPropertySetter setter,
2165 IndexedPropertyQuery query,
2166 IndexedPropertyDeleter remover,
2167 IndexedPropertyEnumerator enumerator,
2168 Handle<Value> data);
2169 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2170 Handle<Value> data);
2171
2172 friend class Context;
2173 friend class ObjectTemplate;
2174};
2175
2176
2177/**
2178 * An ObjectTemplate is used to create objects at runtime.
2179 *
2180 * Properties added to an ObjectTemplate are added to each object
2181 * created from the ObjectTemplate.
2182 */
2183class V8EXPORT ObjectTemplate : public Template {
2184 public:
2185 /** Creates an ObjectTemplate. */
2186 static Local<ObjectTemplate> New();
2187
2188 /** Creates a new instance of this template.*/
2189 Local<Object> NewInstance();
2190
2191 /**
2192 * Sets an accessor on the object template.
2193 *
2194 * Whenever the property with the given name is accessed on objects
2195 * created from this ObjectTemplate the getter and setter callbacks
2196 * are called instead of getting and setting the property directly
2197 * on the JavaScript object.
2198 *
2199 * \param name The name of the property for which an accessor is added.
2200 * \param getter The callback to invoke when getting the property.
2201 * \param setter The callback to invoke when setting the property.
2202 * \param data A piece of data that will be passed to the getter and setter
2203 * callbacks whenever they are invoked.
2204 * \param settings Access control settings for the accessor. This is a bit
2205 * field consisting of one of more of
2206 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2207 * The default is to not allow cross-context access.
2208 * ALL_CAN_READ means that all cross-context reads are allowed.
2209 * ALL_CAN_WRITE means that all cross-context writes are allowed.
2210 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2211 * cross-context access.
2212 * \param attribute The attributes of the property for which an accessor
2213 * is added.
2214 */
2215 void SetAccessor(Handle<String> name,
2216 AccessorGetter getter,
2217 AccessorSetter setter = 0,
2218 Handle<Value> data = Handle<Value>(),
2219 AccessControl settings = DEFAULT,
2220 PropertyAttribute attribute = None);
2221
2222 /**
2223 * Sets a named property handler on the object template.
2224 *
2225 * Whenever a named property is accessed on objects created from
2226 * this object template, the provided callback is invoked instead of
2227 * accessing the property directly on the JavaScript object.
2228 *
2229 * \param getter The callback to invoke when getting a property.
2230 * \param setter The callback to invoke when setting a property.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002231 * \param query The callback to invoke to check if a property is present,
2232 * and if present, get its attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00002233 * \param deleter The callback to invoke when deleting a property.
2234 * \param enumerator The callback to invoke to enumerate all the named
2235 * properties of an object.
2236 * \param data A piece of data that will be passed to the callbacks
2237 * whenever they are invoked.
2238 */
2239 void SetNamedPropertyHandler(NamedPropertyGetter getter,
2240 NamedPropertySetter setter = 0,
2241 NamedPropertyQuery query = 0,
2242 NamedPropertyDeleter deleter = 0,
2243 NamedPropertyEnumerator enumerator = 0,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002244 Handle<Value> data = Handle<Value>());
Steve Blocka7e24c12009-10-30 11:49:00 +00002245
2246 /**
2247 * Sets an indexed property handler on the object template.
2248 *
2249 * Whenever an indexed property is accessed on objects created from
2250 * this object template, the provided callback is invoked instead of
2251 * accessing the property directly on the JavaScript object.
2252 *
2253 * \param getter The callback to invoke when getting a property.
2254 * \param setter The callback to invoke when setting a property.
Ben Murdoch257744e2011-11-30 15:57:28 +00002255 * \param query The callback to invoke to check if an object has a property.
Steve Blocka7e24c12009-10-30 11:49:00 +00002256 * \param deleter The callback to invoke when deleting a property.
2257 * \param enumerator The callback to invoke to enumerate all the indexed
2258 * properties of an object.
2259 * \param data A piece of data that will be passed to the callbacks
2260 * whenever they are invoked.
2261 */
2262 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2263 IndexedPropertySetter setter = 0,
2264 IndexedPropertyQuery query = 0,
2265 IndexedPropertyDeleter deleter = 0,
2266 IndexedPropertyEnumerator enumerator = 0,
2267 Handle<Value> data = Handle<Value>());
Iain Merrick75681382010-08-19 15:07:18 +01002268
Steve Blocka7e24c12009-10-30 11:49:00 +00002269 /**
2270 * Sets the callback to be used when calling instances created from
2271 * this template as a function. If no callback is set, instances
2272 * behave like normal JavaScript objects that cannot be called as a
2273 * function.
2274 */
2275 void SetCallAsFunctionHandler(InvocationCallback callback,
2276 Handle<Value> data = Handle<Value>());
2277
2278 /**
2279 * Mark object instances of the template as undetectable.
2280 *
2281 * In many ways, undetectable objects behave as though they are not
2282 * there. They behave like 'undefined' in conditionals and when
2283 * printed. However, properties can be accessed and called as on
2284 * normal objects.
2285 */
2286 void MarkAsUndetectable();
2287
2288 /**
2289 * Sets access check callbacks on the object template.
2290 *
2291 * When accessing properties on instances of this object template,
2292 * the access check callback will be called to determine whether or
2293 * not to allow cross-context access to the properties.
2294 * The last parameter specifies whether access checks are turned
2295 * on by default on instances. If access checks are off by default,
2296 * they can be turned on on individual instances by calling
2297 * Object::TurnOnAccessCheck().
2298 */
2299 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2300 IndexedSecurityCallback indexed_handler,
2301 Handle<Value> data = Handle<Value>(),
2302 bool turned_on_by_default = true);
2303
2304 /**
2305 * Gets the number of internal fields for objects generated from
2306 * this template.
2307 */
2308 int InternalFieldCount();
2309
2310 /**
2311 * Sets the number of internal fields for objects generated from
2312 * this template.
2313 */
2314 void SetInternalFieldCount(int value);
2315
2316 private:
2317 ObjectTemplate();
2318 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2319 friend class FunctionTemplate;
2320};
2321
2322
2323/**
2324 * A Signature specifies which receivers and arguments a function can
2325 * legally be called with.
2326 */
2327class V8EXPORT Signature : public Data {
2328 public:
2329 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2330 Handle<FunctionTemplate>(),
2331 int argc = 0,
2332 Handle<FunctionTemplate> argv[] = 0);
2333 private:
2334 Signature();
2335};
2336
2337
2338/**
2339 * A utility for determining the type of objects based on the template
2340 * they were constructed from.
2341 */
2342class V8EXPORT TypeSwitch : public Data {
2343 public:
2344 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2345 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2346 int match(Handle<Value> value);
2347 private:
2348 TypeSwitch();
2349};
2350
2351
Ben Murdoch257744e2011-11-30 15:57:28 +00002352// --- Extensions ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002353
2354
2355/**
2356 * Ignore
2357 */
2358class V8EXPORT Extension { // NOLINT
2359 public:
2360 Extension(const char* name,
2361 const char* source = 0,
2362 int dep_count = 0,
2363 const char** deps = 0);
2364 virtual ~Extension() { }
2365 virtual v8::Handle<v8::FunctionTemplate>
2366 GetNativeFunction(v8::Handle<v8::String> name) {
2367 return v8::Handle<v8::FunctionTemplate>();
2368 }
2369
2370 const char* name() { return name_; }
2371 const char* source() { return source_; }
2372 int dependency_count() { return dep_count_; }
2373 const char** dependencies() { return deps_; }
2374 void set_auto_enable(bool value) { auto_enable_ = value; }
2375 bool auto_enable() { return auto_enable_; }
2376
2377 private:
2378 const char* name_;
2379 const char* source_;
2380 int dep_count_;
2381 const char** deps_;
2382 bool auto_enable_;
2383
2384 // Disallow copying and assigning.
2385 Extension(const Extension&);
2386 void operator=(const Extension&);
2387};
2388
2389
2390void V8EXPORT RegisterExtension(Extension* extension);
2391
2392
2393/**
2394 * Ignore
2395 */
2396class V8EXPORT DeclareExtension {
2397 public:
2398 inline DeclareExtension(Extension* extension) {
2399 RegisterExtension(extension);
2400 }
2401};
2402
2403
Ben Murdoch257744e2011-11-30 15:57:28 +00002404// --- Statics ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002405
2406
2407Handle<Primitive> V8EXPORT Undefined();
2408Handle<Primitive> V8EXPORT Null();
2409Handle<Boolean> V8EXPORT True();
2410Handle<Boolean> V8EXPORT False();
2411
2412
2413/**
2414 * A set of constraints that specifies the limits of the runtime's memory use.
2415 * You must set the heap size before initializing the VM - the size cannot be
2416 * adjusted after the VM is initialized.
2417 *
2418 * If you are using threads then you should hold the V8::Locker lock while
2419 * setting the stack limit and you must set a non-default stack limit separately
2420 * for each thread.
2421 */
2422class V8EXPORT ResourceConstraints {
2423 public:
2424 ResourceConstraints();
2425 int max_young_space_size() const { return max_young_space_size_; }
2426 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2427 int max_old_space_size() const { return max_old_space_size_; }
2428 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
Russell Brenner90bac252010-11-18 13:33:46 -08002429 int max_executable_size() { return max_executable_size_; }
2430 void set_max_executable_size(int value) { max_executable_size_ = value; }
Steve Blocka7e24c12009-10-30 11:49:00 +00002431 uint32_t* stack_limit() const { return stack_limit_; }
2432 // Sets an address beyond which the VM's stack may not grow.
2433 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2434 private:
2435 int max_young_space_size_;
2436 int max_old_space_size_;
Russell Brenner90bac252010-11-18 13:33:46 -08002437 int max_executable_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002438 uint32_t* stack_limit_;
2439};
2440
2441
Kristian Monsen25f61362010-05-21 11:50:48 +01002442bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
Steve Blocka7e24c12009-10-30 11:49:00 +00002443
2444
Ben Murdoch257744e2011-11-30 15:57:28 +00002445// --- Exceptions ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002446
2447
2448typedef void (*FatalErrorCallback)(const char* location, const char* message);
2449
2450
2451typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2452
2453
2454/**
2455 * Schedules an exception to be thrown when returning to JavaScript. When an
2456 * exception has been scheduled it is illegal to invoke any JavaScript
2457 * operation; the caller must return immediately and only after the exception
2458 * has been handled does it become legal to invoke JavaScript operations.
2459 */
2460Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2461
2462/**
2463 * Create new error objects by calling the corresponding error object
2464 * constructor with the message.
2465 */
2466class V8EXPORT Exception {
2467 public:
2468 static Local<Value> RangeError(Handle<String> message);
2469 static Local<Value> ReferenceError(Handle<String> message);
2470 static Local<Value> SyntaxError(Handle<String> message);
2471 static Local<Value> TypeError(Handle<String> message);
2472 static Local<Value> Error(Handle<String> message);
2473};
2474
2475
Ben Murdoch257744e2011-11-30 15:57:28 +00002476// --- Counters Callbacks ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002477
2478typedef int* (*CounterLookupCallback)(const char* name);
2479
2480typedef void* (*CreateHistogramCallback)(const char* name,
2481 int min,
2482 int max,
2483 size_t buckets);
2484
2485typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2486
Ben Murdoch257744e2011-11-30 15:57:28 +00002487// --- Memory Allocation Callback ---
Iain Merrick9ac36c92010-09-13 15:29:50 +01002488 enum ObjectSpace {
2489 kObjectSpaceNewSpace = 1 << 0,
2490 kObjectSpaceOldPointerSpace = 1 << 1,
2491 kObjectSpaceOldDataSpace = 1 << 2,
2492 kObjectSpaceCodeSpace = 1 << 3,
2493 kObjectSpaceMapSpace = 1 << 4,
2494 kObjectSpaceLoSpace = 1 << 5,
2495
2496 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2497 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2498 kObjectSpaceLoSpace
2499 };
2500
2501 enum AllocationAction {
2502 kAllocationActionAllocate = 1 << 0,
2503 kAllocationActionFree = 1 << 1,
2504 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2505 };
2506
2507typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2508 AllocationAction action,
2509 int size);
2510
Ben Murdoch257744e2011-11-30 15:57:28 +00002511// --- Failed Access Check Callback ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002512typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2513 AccessType type,
2514 Local<Value> data);
2515
Ben Murdoch257744e2011-11-30 15:57:28 +00002516// --- AllowCodeGenerationFromStrings callbacks ---
2517
2518/**
2519 * Callback to check if code generation from strings is allowed. See
2520 * Context::AllowCodeGenerationFromStrings.
2521 */
2522typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
2523
2524// --- Garbage Collection Callbacks ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002525
2526/**
Steve Block6ded16b2010-05-10 14:33:55 +01002527 * Applications can register callback functions which will be called
2528 * before and after a garbage collection. Allocations are not
2529 * allowed in the callback functions, you therefore cannot manipulate
Steve Blocka7e24c12009-10-30 11:49:00 +00002530 * objects (set or delete properties for example) since it is possible
2531 * such operations will result in the allocation of objects.
2532 */
Steve Block6ded16b2010-05-10 14:33:55 +01002533enum GCType {
2534 kGCTypeScavenge = 1 << 0,
2535 kGCTypeMarkSweepCompact = 1 << 1,
2536 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2537};
2538
2539enum GCCallbackFlags {
2540 kNoGCCallbackFlags = 0,
2541 kGCCallbackFlagCompacted = 1 << 0
2542};
2543
2544typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2545typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2546
Steve Blocka7e24c12009-10-30 11:49:00 +00002547typedef void (*GCCallback)();
2548
2549
Steve Blocka7e24c12009-10-30 11:49:00 +00002550/**
2551 * Profiler modules.
2552 *
2553 * In V8, profiler consists of several modules: CPU profiler, and different
2554 * kinds of heap profiling. Each can be turned on / off independently.
2555 * When PROFILER_MODULE_HEAP_SNAPSHOT flag is passed to ResumeProfilerEx,
2556 * modules are enabled only temporarily for making a snapshot of the heap.
2557 */
2558enum ProfilerModules {
2559 PROFILER_MODULE_NONE = 0,
2560 PROFILER_MODULE_CPU = 1,
2561 PROFILER_MODULE_HEAP_STATS = 1 << 1,
2562 PROFILER_MODULE_JS_CONSTRUCTORS = 1 << 2,
2563 PROFILER_MODULE_HEAP_SNAPSHOT = 1 << 16
2564};
2565
2566
2567/**
Steve Block3ce2e202009-11-05 08:53:23 +00002568 * Collection of V8 heap information.
2569 *
2570 * Instances of this class can be passed to v8::V8::HeapStatistics to
2571 * get heap statistics from V8.
2572 */
2573class V8EXPORT HeapStatistics {
2574 public:
2575 HeapStatistics();
2576 size_t total_heap_size() { return total_heap_size_; }
Russell Brenner90bac252010-11-18 13:33:46 -08002577 size_t total_heap_size_executable() { return total_heap_size_executable_; }
Steve Block3ce2e202009-11-05 08:53:23 +00002578 size_t used_heap_size() { return used_heap_size_; }
Ben Murdochb8e0da22011-05-16 14:20:40 +01002579 size_t heap_size_limit() { return heap_size_limit_; }
Steve Block3ce2e202009-11-05 08:53:23 +00002580
2581 private:
2582 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
Russell Brenner90bac252010-11-18 13:33:46 -08002583 void set_total_heap_size_executable(size_t size) {
2584 total_heap_size_executable_ = size;
2585 }
Steve Block3ce2e202009-11-05 08:53:23 +00002586 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
Ben Murdochb8e0da22011-05-16 14:20:40 +01002587 void set_heap_size_limit(size_t size) { heap_size_limit_ = size; }
Steve Block3ce2e202009-11-05 08:53:23 +00002588
2589 size_t total_heap_size_;
Russell Brenner90bac252010-11-18 13:33:46 -08002590 size_t total_heap_size_executable_;
Steve Block3ce2e202009-11-05 08:53:23 +00002591 size_t used_heap_size_;
Ben Murdochb8e0da22011-05-16 14:20:40 +01002592 size_t heap_size_limit_;
Steve Block3ce2e202009-11-05 08:53:23 +00002593
2594 friend class V8;
2595};
2596
2597
Steve Block44f0eee2011-05-26 01:26:41 +01002598class RetainedObjectInfo;
2599
2600/**
2601 * Isolate represents an isolated instance of the V8 engine. V8
2602 * isolates have completely separate states. Objects from one isolate
2603 * must not be used in other isolates. When V8 is initialized a
2604 * default isolate is implicitly created and entered. The embedder
2605 * can create additional isolates and use them in parallel in multiple
2606 * threads. An isolate can be entered by at most one thread at any
2607 * given time. The Locker/Unlocker API can be used to synchronize.
2608 */
2609class V8EXPORT Isolate {
2610 public:
2611 /**
2612 * Stack-allocated class which sets the isolate for all operations
2613 * executed within a local scope.
2614 */
2615 class V8EXPORT Scope {
2616 public:
2617 explicit Scope(Isolate* isolate) : isolate_(isolate) {
2618 isolate->Enter();
2619 }
2620
2621 ~Scope() { isolate_->Exit(); }
2622
2623 private:
2624 Isolate* const isolate_;
2625
2626 // Prevent copying of Scope objects.
2627 Scope(const Scope&);
2628 Scope& operator=(const Scope&);
2629 };
2630
2631 /**
2632 * Creates a new isolate. Does not change the currently entered
2633 * isolate.
2634 *
2635 * When an isolate is no longer used its resources should be freed
2636 * by calling Dispose(). Using the delete operator is not allowed.
2637 */
2638 static Isolate* New();
2639
2640 /**
2641 * Returns the entered isolate for the current thread or NULL in
2642 * case there is no current isolate.
2643 */
2644 static Isolate* GetCurrent();
2645
2646 /**
2647 * Methods below this point require holding a lock (using Locker) in
2648 * a multi-threaded environment.
2649 */
2650
2651 /**
2652 * Sets this isolate as the entered one for the current thread.
2653 * Saves the previously entered one (if any), so that it can be
2654 * restored when exiting. Re-entering an isolate is allowed.
2655 */
2656 void Enter();
2657
2658 /**
2659 * Exits this isolate by restoring the previously entered one in the
2660 * current thread. The isolate may still stay the same, if it was
2661 * entered more than once.
2662 *
2663 * Requires: this == Isolate::GetCurrent().
2664 */
2665 void Exit();
2666
2667 /**
2668 * Disposes the isolate. The isolate must not be entered by any
2669 * thread to be disposable.
2670 */
2671 void Dispose();
2672
Ben Murdoch257744e2011-11-30 15:57:28 +00002673 /**
2674 * Associate embedder-specific data with the isolate
2675 */
2676 void SetData(void* data);
2677
2678 /**
2679 * Retrive embedder-specific data from the isolate.
2680 * Returns NULL if SetData has never been called.
2681 */
2682 void* GetData();
2683
Steve Block44f0eee2011-05-26 01:26:41 +01002684 private:
2685
2686 Isolate();
2687 Isolate(const Isolate&);
2688 ~Isolate();
2689 Isolate& operator=(const Isolate&);
2690 void* operator new(size_t size);
2691 void operator delete(void*, size_t);
2692};
2693
2694
Ben Murdoch257744e2011-11-30 15:57:28 +00002695class StartupData {
2696 public:
2697 enum CompressionAlgorithm {
2698 kUncompressed,
2699 kBZip2
2700 };
2701
2702 const char* data;
2703 int compressed_size;
2704 int raw_size;
2705};
2706
Steve Block3ce2e202009-11-05 08:53:23 +00002707/**
Steve Blocka7e24c12009-10-30 11:49:00 +00002708 * Container class for static utility functions.
2709 */
2710class V8EXPORT V8 {
2711 public:
2712 /** Set the callback to invoke in case of fatal errors. */
2713 static void SetFatalErrorHandler(FatalErrorCallback that);
2714
2715 /**
Ben Murdoch257744e2011-11-30 15:57:28 +00002716 * Set the callback to invoke to check if code generation from
2717 * strings should be allowed.
2718 */
2719 static void SetAllowCodeGenerationFromStringsCallback(
2720 AllowCodeGenerationFromStringsCallback that);
2721
2722 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002723 * Ignore out-of-memory exceptions.
2724 *
2725 * V8 running out of memory is treated as a fatal error by default.
2726 * This means that the fatal error handler is called and that V8 is
2727 * terminated.
2728 *
Ben Murdoch257744e2011-11-30 15:57:28 +00002729 * IgnoreOutOfMemoryException can be used to not treat an
Steve Blocka7e24c12009-10-30 11:49:00 +00002730 * out-of-memory situation as a fatal error. This way, the contexts
2731 * that did not cause the out of memory problem might be able to
2732 * continue execution.
2733 */
2734 static void IgnoreOutOfMemoryException();
2735
2736 /**
2737 * Check if V8 is dead and therefore unusable. This is the case after
2738 * fatal errors such as out-of-memory situations.
2739 */
2740 static bool IsDead();
2741
2742 /**
Ben Murdoch257744e2011-11-30 15:57:28 +00002743 * The following 4 functions are to be used when V8 is built with
2744 * the 'compress_startup_data' flag enabled. In this case, the
2745 * embedder must decompress startup data prior to initializing V8.
2746 *
2747 * This is how interaction with V8 should look like:
2748 * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
2749 * v8::StartupData* compressed_data =
2750 * new v8::StartupData[compressed_data_count];
2751 * v8::V8::GetCompressedStartupData(compressed_data);
2752 * ... decompress data (compressed_data can be updated in-place) ...
2753 * v8::V8::SetDecompressedStartupData(compressed_data);
2754 * ... now V8 can be initialized
2755 * ... make sure the decompressed data stays valid until V8 shutdown
2756 */
2757 static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
2758 static int GetCompressedStartupDataCount();
2759 static void GetCompressedStartupData(StartupData* compressed_data);
2760 static void SetDecompressedStartupData(StartupData* decompressed_data);
2761
2762 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002763 * Adds a message listener.
2764 *
Ben Murdoch257744e2011-11-30 15:57:28 +00002765 * The same message listener can be added more than once and in that
Steve Blocka7e24c12009-10-30 11:49:00 +00002766 * case it will be called more than once for each message.
2767 */
2768 static bool AddMessageListener(MessageCallback that,
2769 Handle<Value> data = Handle<Value>());
2770
2771 /**
2772 * Remove all message listeners from the specified callback function.
2773 */
2774 static void RemoveMessageListeners(MessageCallback that);
2775
2776 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002777 * Tells V8 to capture current stack trace when uncaught exception occurs
2778 * and report it to the message listeners. The option is off by default.
2779 */
2780 static void SetCaptureStackTraceForUncaughtExceptions(
2781 bool capture,
2782 int frame_limit = 10,
2783 StackTrace::StackTraceOptions options = StackTrace::kOverview);
2784
2785 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002786 * Sets V8 flags from a string.
2787 */
2788 static void SetFlagsFromString(const char* str, int length);
2789
2790 /**
2791 * Sets V8 flags from the command line.
2792 */
2793 static void SetFlagsFromCommandLine(int* argc,
2794 char** argv,
2795 bool remove_flags);
2796
2797 /** Get the version string. */
2798 static const char* GetVersion();
2799
2800 /**
2801 * Enables the host application to provide a mechanism for recording
2802 * statistics counters.
2803 */
2804 static void SetCounterFunction(CounterLookupCallback);
2805
2806 /**
2807 * Enables the host application to provide a mechanism for recording
2808 * histograms. The CreateHistogram function returns a
2809 * histogram which will later be passed to the AddHistogramSample
2810 * function.
2811 */
2812 static void SetCreateHistogramFunction(CreateHistogramCallback);
2813 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
2814
2815 /**
2816 * Enables the computation of a sliding window of states. The sliding
2817 * window information is recorded in statistics counters.
2818 */
2819 static void EnableSlidingStateWindow();
2820
2821 /** Callback function for reporting failed access checks.*/
2822 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
2823
2824 /**
2825 * Enables the host application to receive a notification before a
Steve Block6ded16b2010-05-10 14:33:55 +01002826 * garbage collection. Allocations are not allowed in the
2827 * callback function, you therefore cannot manipulate objects (set
2828 * or delete properties for example) since it is possible such
2829 * operations will result in the allocation of objects. It is possible
2830 * to specify the GCType filter for your callback. But it is not possible to
2831 * register the same callback function two times with different
2832 * GCType filters.
2833 */
2834 static void AddGCPrologueCallback(
2835 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
2836
2837 /**
2838 * This function removes callback which was installed by
2839 * AddGCPrologueCallback function.
2840 */
2841 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
2842
2843 /**
2844 * The function is deprecated. Please use AddGCPrologueCallback instead.
2845 * Enables the host application to receive a notification before a
2846 * garbage collection. Allocations are not allowed in the
Steve Blocka7e24c12009-10-30 11:49:00 +00002847 * callback function, you therefore cannot manipulate objects (set
2848 * or delete properties for example) since it is possible such
2849 * operations will result in the allocation of objects.
2850 */
2851 static void SetGlobalGCPrologueCallback(GCCallback);
2852
2853 /**
2854 * Enables the host application to receive a notification after a
Steve Block6ded16b2010-05-10 14:33:55 +01002855 * garbage collection. Allocations are not allowed in the
2856 * callback function, you therefore cannot manipulate objects (set
2857 * or delete properties for example) since it is possible such
2858 * operations will result in the allocation of objects. It is possible
2859 * to specify the GCType filter for your callback. But it is not possible to
2860 * register the same callback function two times with different
2861 * GCType filters.
2862 */
2863 static void AddGCEpilogueCallback(
2864 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
2865
2866 /**
2867 * This function removes callback which was installed by
2868 * AddGCEpilogueCallback function.
2869 */
2870 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
2871
2872 /**
2873 * The function is deprecated. Please use AddGCEpilogueCallback instead.
2874 * Enables the host application to receive a notification after a
Steve Blocka7e24c12009-10-30 11:49:00 +00002875 * major garbage collection. Allocations are not allowed in the
2876 * callback function, you therefore cannot manipulate objects (set
2877 * or delete properties for example) since it is possible such
2878 * operations will result in the allocation of objects.
2879 */
2880 static void SetGlobalGCEpilogueCallback(GCCallback);
2881
2882 /**
Iain Merrick9ac36c92010-09-13 15:29:50 +01002883 * Enables the host application to provide a mechanism to be notified
2884 * and perform custom logging when V8 Allocates Executable Memory.
2885 */
2886 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
2887 ObjectSpace space,
2888 AllocationAction action);
2889
2890 /**
2891 * This function removes callback which was installed by
2892 * AddMemoryAllocationCallback function.
2893 */
2894 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
2895
2896 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002897 * Allows the host application to group objects together. If one
2898 * object in the group is alive, all objects in the group are alive.
2899 * After each garbage collection, object groups are removed. It is
2900 * intended to be used in the before-garbage-collection callback
2901 * function, for instance to simulate DOM tree connections among JS
2902 * wrapper objects.
Steve Block44f0eee2011-05-26 01:26:41 +01002903 * See v8-profiler.h for RetainedObjectInfo interface description.
Steve Blocka7e24c12009-10-30 11:49:00 +00002904 */
Steve Block44f0eee2011-05-26 01:26:41 +01002905 static void AddObjectGroup(Persistent<Value>* objects,
2906 size_t length,
2907 RetainedObjectInfo* info = NULL);
2908
2909 /**
2910 * Allows the host application to declare implicit references between
2911 * the objects: if |parent| is alive, all |children| are alive too.
2912 * After each garbage collection, all implicit references
2913 * are removed. It is intended to be used in the before-garbage-collection
2914 * callback function.
2915 */
2916 static void AddImplicitReferences(Persistent<Object> parent,
2917 Persistent<Value>* children,
2918 size_t length);
Steve Blocka7e24c12009-10-30 11:49:00 +00002919
2920 /**
2921 * Initializes from snapshot if possible. Otherwise, attempts to
2922 * initialize from scratch. This function is called implicitly if
2923 * you use the API without calling it first.
2924 */
2925 static bool Initialize();
2926
2927 /**
2928 * Adjusts the amount of registered external memory. Used to give
2929 * V8 an indication of the amount of externally allocated memory
2930 * that is kept alive by JavaScript objects. V8 uses this to decide
2931 * when to perform global garbage collections. Registering
2932 * externally allocated memory will trigger global garbage
2933 * collections more often than otherwise in an attempt to garbage
2934 * collect the JavaScript objects keeping the externally allocated
2935 * memory alive.
2936 *
2937 * \param change_in_bytes the change in externally allocated memory
2938 * that is kept alive by JavaScript objects.
2939 * \returns the adjusted value.
2940 */
2941 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
2942
2943 /**
2944 * Suspends recording of tick samples in the profiler.
2945 * When the V8 profiling mode is enabled (usually via command line
2946 * switches) this function suspends recording of tick samples.
2947 * Profiling ticks are discarded until ResumeProfiler() is called.
2948 *
2949 * See also the --prof and --prof_auto command line switches to
2950 * enable V8 profiling.
2951 */
2952 static void PauseProfiler();
2953
2954 /**
2955 * Resumes recording of tick samples in the profiler.
2956 * See also PauseProfiler().
2957 */
2958 static void ResumeProfiler();
2959
2960 /**
2961 * Return whether profiler is currently paused.
2962 */
2963 static bool IsProfilerPaused();
2964
2965 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002966 * Resumes specified profiler modules. Can be called several times to
2967 * mark the opening of a profiler events block with the given tag.
2968 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002969 * "ResumeProfiler" is equivalent to "ResumeProfilerEx(PROFILER_MODULE_CPU)".
2970 * See ProfilerModules enum.
2971 *
2972 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002973 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002974 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002975 static void ResumeProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002976
2977 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002978 * Pauses specified profiler modules. Each call to "PauseProfilerEx" closes
2979 * a block of profiler events opened by a call to "ResumeProfilerEx" with the
2980 * same tag value. There is no need for blocks to be properly nested.
2981 * The profiler is paused when the last opened block is closed.
2982 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002983 * "PauseProfiler" is equivalent to "PauseProfilerEx(PROFILER_MODULE_CPU)".
2984 * See ProfilerModules enum.
2985 *
2986 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002987 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002988 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002989 static void PauseProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002990
2991 /**
2992 * Returns active (resumed) profiler modules.
2993 * See ProfilerModules enum.
2994 *
2995 * \returns active profiler modules.
2996 */
2997 static int GetActiveProfilerModules();
2998
2999 /**
3000 * If logging is performed into a memory buffer (via --logfile=*), allows to
3001 * retrieve previously written messages. This can be used for retrieving
3002 * profiler log data in the application. This function is thread-safe.
3003 *
3004 * Caller provides a destination buffer that must exist during GetLogLines
3005 * call. Only whole log lines are copied into the buffer.
3006 *
3007 * \param from_pos specified a point in a buffer to read from, 0 is the
3008 * beginning of a buffer. It is assumed that caller updates its current
3009 * position using returned size value from the previous call.
3010 * \param dest_buf destination buffer for log data.
3011 * \param max_size size of the destination buffer.
3012 * \returns actual size of log data copied into buffer.
3013 */
3014 static int GetLogLines(int from_pos, char* dest_buf, int max_size);
3015
3016 /**
Steve Block6ded16b2010-05-10 14:33:55 +01003017 * The minimum allowed size for a log lines buffer. If the size of
3018 * the buffer given will not be enough to hold a line of the maximum
3019 * length, an attempt to find a log line end in GetLogLines will
3020 * fail, and an empty result will be returned.
3021 */
3022 static const int kMinimumSizeForLogLinesBuffer = 2048;
3023
3024 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003025 * Retrieve the V8 thread id of the calling thread.
3026 *
3027 * The thread id for a thread should only be retrieved after the V8
3028 * lock has been acquired with a Locker object with that thread.
3029 */
3030 static int GetCurrentThreadId();
3031
3032 /**
3033 * Forcefully terminate execution of a JavaScript thread. This can
3034 * be used to terminate long-running scripts.
3035 *
3036 * TerminateExecution should only be called when then V8 lock has
3037 * been acquired with a Locker object. Therefore, in order to be
3038 * able to terminate long-running threads, preemption must be
3039 * enabled to allow the user of TerminateExecution to acquire the
3040 * lock.
3041 *
3042 * The termination is achieved by throwing an exception that is
3043 * uncatchable by JavaScript exception handlers. Termination
3044 * exceptions act as if they were caught by a C++ TryCatch exception
Ben Murdoch257744e2011-11-30 15:57:28 +00003045 * handler. If forceful termination is used, any C++ TryCatch
Steve Blocka7e24c12009-10-30 11:49:00 +00003046 * exception handler that catches an exception should check if that
3047 * exception is a termination exception and immediately return if
3048 * that is the case. Returning immediately in that case will
3049 * continue the propagation of the termination exception if needed.
3050 *
3051 * The thread id passed to TerminateExecution must have been
3052 * obtained by calling GetCurrentThreadId on the thread in question.
3053 *
3054 * \param thread_id The thread id of the thread to terminate.
3055 */
3056 static void TerminateExecution(int thread_id);
3057
3058 /**
Steve Block44f0eee2011-05-26 01:26:41 +01003059 * Forcefully terminate the current thread of JavaScript execution
3060 * in the given isolate. If no isolate is provided, the default
3061 * isolate is used.
Steve Blocka7e24c12009-10-30 11:49:00 +00003062 *
3063 * This method can be used by any thread even if that thread has not
3064 * acquired the V8 lock with a Locker object.
Steve Block44f0eee2011-05-26 01:26:41 +01003065 *
3066 * \param isolate The isolate in which to terminate the current JS execution.
Steve Blocka7e24c12009-10-30 11:49:00 +00003067 */
Steve Block44f0eee2011-05-26 01:26:41 +01003068 static void TerminateExecution(Isolate* isolate = NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00003069
3070 /**
Steve Block6ded16b2010-05-10 14:33:55 +01003071 * Is V8 terminating JavaScript execution.
3072 *
3073 * Returns true if JavaScript execution is currently terminating
3074 * because of a call to TerminateExecution. In that case there are
3075 * still JavaScript frames on the stack and the termination
3076 * exception is still active.
3077 */
3078 static bool IsExecutionTerminating();
3079
3080 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003081 * Releases any resources used by v8 and stops any utility threads
3082 * that may be running. Note that disposing v8 is permanent, it
3083 * cannot be reinitialized.
3084 *
3085 * It should generally not be necessary to dispose v8 before exiting
3086 * a process, this should happen automatically. It is only necessary
3087 * to use if the process needs the resources taken up by v8.
3088 */
3089 static bool Dispose();
3090
Steve Block3ce2e202009-11-05 08:53:23 +00003091 /**
3092 * Get statistics about the heap memory usage.
3093 */
3094 static void GetHeapStatistics(HeapStatistics* heap_statistics);
Steve Blocka7e24c12009-10-30 11:49:00 +00003095
3096 /**
3097 * Optional notification that the embedder is idle.
3098 * V8 uses the notification to reduce memory footprint.
3099 * This call can be used repeatedly if the embedder remains idle.
Steve Blocka7e24c12009-10-30 11:49:00 +00003100 * Returns true if the embedder should stop calling IdleNotification
3101 * until real work has been done. This indicates that V8 has done
3102 * as much cleanup as it will be able to do.
3103 */
Steve Block3ce2e202009-11-05 08:53:23 +00003104 static bool IdleNotification();
Steve Blocka7e24c12009-10-30 11:49:00 +00003105
3106 /**
3107 * Optional notification that the system is running low on memory.
3108 * V8 uses these notifications to attempt to free memory.
3109 */
3110 static void LowMemoryNotification();
3111
Steve Block6ded16b2010-05-10 14:33:55 +01003112 /**
3113 * Optional notification that a context has been disposed. V8 uses
3114 * these notifications to guide the GC heuristic. Returns the number
3115 * of context disposals - including this one - since the last time
3116 * V8 had a chance to clean up.
3117 */
3118 static int ContextDisposedNotification();
3119
Steve Blocka7e24c12009-10-30 11:49:00 +00003120 private:
3121 V8();
3122
3123 static internal::Object** GlobalizeReference(internal::Object** handle);
3124 static void DisposeGlobal(internal::Object** global_handle);
3125 static void MakeWeak(internal::Object** global_handle,
3126 void* data,
3127 WeakReferenceCallback);
3128 static void ClearWeak(internal::Object** global_handle);
Ben Murdoch257744e2011-11-30 15:57:28 +00003129 static void MarkIndependent(internal::Object** global_handle);
Steve Blocka7e24c12009-10-30 11:49:00 +00003130 static bool IsGlobalNearDeath(internal::Object** global_handle);
3131 static bool IsGlobalWeak(internal::Object** global_handle);
Steve Block44f0eee2011-05-26 01:26:41 +01003132 static void SetWrapperClassId(internal::Object** global_handle,
3133 uint16_t class_id);
Steve Blocka7e24c12009-10-30 11:49:00 +00003134
3135 template <class T> friend class Handle;
3136 template <class T> friend class Local;
3137 template <class T> friend class Persistent;
3138 friend class Context;
3139};
3140
3141
3142/**
3143 * An external exception handler.
3144 */
3145class V8EXPORT TryCatch {
3146 public:
3147
3148 /**
3149 * Creates a new try/catch block and registers it with v8.
3150 */
3151 TryCatch();
3152
3153 /**
3154 * Unregisters and deletes this try/catch block.
3155 */
3156 ~TryCatch();
3157
3158 /**
3159 * Returns true if an exception has been caught by this try/catch block.
3160 */
3161 bool HasCaught() const;
3162
3163 /**
3164 * For certain types of exceptions, it makes no sense to continue
3165 * execution.
3166 *
3167 * Currently, the only type of exception that can be caught by a
3168 * TryCatch handler and for which it does not make sense to continue
3169 * is termination exception. Such exceptions are thrown when the
3170 * TerminateExecution methods are called to terminate a long-running
3171 * script.
3172 *
3173 * If CanContinue returns false, the correct action is to perform
3174 * any C++ cleanup needed and then return.
3175 */
3176 bool CanContinue() const;
3177
3178 /**
Steve Blockd0582a62009-12-15 09:54:21 +00003179 * Throws the exception caught by this TryCatch in a way that avoids
3180 * it being caught again by this same TryCatch. As with ThrowException
3181 * it is illegal to execute any JavaScript operations after calling
3182 * ReThrow; the caller must return immediately to where the exception
3183 * is caught.
3184 */
3185 Handle<Value> ReThrow();
3186
3187 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003188 * Returns the exception caught by this try/catch block. If no exception has
3189 * been caught an empty handle is returned.
3190 *
3191 * The returned handle is valid until this TryCatch block has been destroyed.
3192 */
3193 Local<Value> Exception() const;
3194
3195 /**
3196 * Returns the .stack property of the thrown object. If no .stack
3197 * property is present an empty handle is returned.
3198 */
3199 Local<Value> StackTrace() const;
3200
3201 /**
3202 * Returns the message associated with this exception. If there is
3203 * no message associated an empty handle is returned.
3204 *
3205 * The returned handle is valid until this TryCatch block has been
3206 * destroyed.
3207 */
3208 Local<v8::Message> Message() const;
3209
3210 /**
3211 * Clears any exceptions that may have been caught by this try/catch block.
3212 * After this method has been called, HasCaught() will return false.
3213 *
3214 * It is not necessary to clear a try/catch block before using it again; if
3215 * another exception is thrown the previously caught exception will just be
3216 * overwritten. However, it is often a good idea since it makes it easier
3217 * to determine which operation threw a given exception.
3218 */
3219 void Reset();
3220
3221 /**
3222 * Set verbosity of the external exception handler.
3223 *
3224 * By default, exceptions that are caught by an external exception
3225 * handler are not reported. Call SetVerbose with true on an
3226 * external exception handler to have exceptions caught by the
3227 * handler reported as if they were not caught.
3228 */
3229 void SetVerbose(bool value);
3230
3231 /**
3232 * Set whether or not this TryCatch should capture a Message object
3233 * which holds source information about where the exception
3234 * occurred. True by default.
3235 */
3236 void SetCaptureMessage(bool value);
3237
Steve Blockd0582a62009-12-15 09:54:21 +00003238 private:
3239 void* next_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003240 void* exception_;
3241 void* message_;
Steve Blockd0582a62009-12-15 09:54:21 +00003242 bool is_verbose_ : 1;
3243 bool can_continue_ : 1;
3244 bool capture_message_ : 1;
3245 bool rethrow_ : 1;
3246
Steve Block44f0eee2011-05-26 01:26:41 +01003247 friend class v8::internal::Isolate;
Steve Blocka7e24c12009-10-30 11:49:00 +00003248};
3249
3250
Ben Murdoch257744e2011-11-30 15:57:28 +00003251// --- Context ---
Steve Blocka7e24c12009-10-30 11:49:00 +00003252
3253
3254/**
3255 * Ignore
3256 */
3257class V8EXPORT ExtensionConfiguration {
3258 public:
3259 ExtensionConfiguration(int name_count, const char* names[])
3260 : name_count_(name_count), names_(names) { }
3261 private:
3262 friend class ImplementationUtilities;
3263 int name_count_;
3264 const char** names_;
3265};
3266
3267
3268/**
3269 * A sandboxed execution context with its own set of built-in objects
3270 * and functions.
3271 */
3272class V8EXPORT Context {
3273 public:
Steve Block1e0659c2011-05-24 12:43:12 +01003274 /**
3275 * Returns the global proxy object or global object itself for
3276 * detached contexts.
3277 *
3278 * Global proxy object is a thin wrapper whose prototype points to
3279 * actual context's global object with the properties like Object, etc.
3280 * This is done that way for security reasons (for more details see
3281 * https://wiki.mozilla.org/Gecko:SplitWindow).
3282 *
3283 * Please note that changes to global proxy object prototype most probably
3284 * would break VM---v8 expects only global object as a prototype of
3285 * global proxy object.
3286 *
3287 * If DetachGlobal() has been invoked, Global() would return actual global
3288 * object until global is reattached with ReattachGlobal().
3289 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003290 Local<Object> Global();
3291
3292 /**
3293 * Detaches the global object from its context before
3294 * the global object can be reused to create a new context.
3295 */
3296 void DetachGlobal();
3297
Andrei Popescu74b3c142010-03-29 12:03:09 +01003298 /**
3299 * Reattaches a global object to a context. This can be used to
3300 * restore the connection between a global object and a context
3301 * after DetachGlobal has been called.
3302 *
3303 * \param global_object The global object to reattach to the
3304 * context. For this to work, the global object must be the global
3305 * object that was associated with this context before a call to
3306 * DetachGlobal.
3307 */
3308 void ReattachGlobal(Handle<Object> global_object);
3309
Leon Clarkef7060e22010-06-03 12:02:55 +01003310 /** Creates a new context.
3311 *
3312 * Returns a persistent handle to the newly allocated context. This
3313 * persistent handle has to be disposed when the context is no
3314 * longer used so the context can be garbage collected.
Steve Block9fac8402011-05-12 15:51:54 +01003315 *
3316 * \param extensions An optional extension configuration containing
3317 * the extensions to be installed in the newly created context.
3318 *
3319 * \param global_template An optional object template from which the
3320 * global object for the newly created context will be created.
3321 *
3322 * \param global_object An optional global object to be reused for
3323 * the newly created context. This global object must have been
3324 * created by a previous call to Context::New with the same global
3325 * template. The state of the global object will be completely reset
3326 * and only object identify will remain.
Leon Clarkef7060e22010-06-03 12:02:55 +01003327 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003328 static Persistent<Context> New(
Andrei Popescu31002712010-02-23 13:46:05 +00003329 ExtensionConfiguration* extensions = NULL,
Steve Blocka7e24c12009-10-30 11:49:00 +00003330 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3331 Handle<Value> global_object = Handle<Value>());
3332
3333 /** Returns the last entered context. */
3334 static Local<Context> GetEntered();
3335
3336 /** Returns the context that is on the top of the stack. */
3337 static Local<Context> GetCurrent();
3338
3339 /**
3340 * Returns the context of the calling JavaScript code. That is the
3341 * context of the top-most JavaScript frame. If there are no
3342 * JavaScript frames an empty handle is returned.
3343 */
3344 static Local<Context> GetCalling();
3345
3346 /**
3347 * Sets the security token for the context. To access an object in
3348 * another context, the security tokens must match.
3349 */
3350 void SetSecurityToken(Handle<Value> token);
3351
3352 /** Restores the security token to the default value. */
3353 void UseDefaultSecurityToken();
3354
3355 /** Returns the security token of this context.*/
3356 Handle<Value> GetSecurityToken();
3357
3358 /**
3359 * Enter this context. After entering a context, all code compiled
3360 * and run is compiled and run in this context. If another context
3361 * is already entered, this old context is saved so it can be
3362 * restored when the new context is exited.
3363 */
3364 void Enter();
3365
3366 /**
3367 * Exit this context. Exiting the current context restores the
3368 * context that was in place when entering the current context.
3369 */
3370 void Exit();
3371
3372 /** Returns true if the context has experienced an out of memory situation. */
3373 bool HasOutOfMemoryException();
3374
3375 /** Returns true if V8 has a current context. */
3376 static bool InContext();
3377
3378 /**
3379 * Associate an additional data object with the context. This is mainly used
3380 * with the debugger to provide additional information on the context through
3381 * the debugger API.
3382 */
Steve Blockd0582a62009-12-15 09:54:21 +00003383 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00003384 Local<Value> GetData();
3385
3386 /**
Ben Murdoch257744e2011-11-30 15:57:28 +00003387 * Control whether code generation from strings is allowed. Calling
3388 * this method with false will disable 'eval' and the 'Function'
3389 * constructor for code running in this context. If 'eval' or the
3390 * 'Function' constructor are used an exception will be thrown.
3391 *
3392 * If code generation from strings is not allowed the
3393 * V8::AllowCodeGenerationFromStrings callback will be invoked if
3394 * set before blocking the call to 'eval' or the 'Function'
3395 * constructor. If that callback returns true, the call will be
3396 * allowed, otherwise an exception will be thrown. If no callback is
3397 * set an exception will be thrown.
3398 */
3399 void AllowCodeGenerationFromStrings(bool allow);
3400
3401 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003402 * Stack-allocated class which sets the execution context for all
3403 * operations executed within a local scope.
3404 */
Steve Block8defd9f2010-07-08 12:39:36 +01003405 class Scope {
Steve Blocka7e24c12009-10-30 11:49:00 +00003406 public:
Ben Murdoch8b112d22011-06-08 16:22:53 +01003407 explicit inline Scope(Handle<Context> context) : context_(context) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003408 context_->Enter();
3409 }
3410 inline ~Scope() { context_->Exit(); }
3411 private:
3412 Handle<Context> context_;
3413 };
3414
3415 private:
3416 friend class Value;
3417 friend class Script;
3418 friend class Object;
3419 friend class Function;
3420};
3421
3422
3423/**
3424 * Multiple threads in V8 are allowed, but only one thread at a time
Steve Block44f0eee2011-05-26 01:26:41 +01003425 * is allowed to use any given V8 isolate. See Isolate class
3426 * comments. The definition of 'using V8 isolate' includes
3427 * accessing handles or holding onto object pointers obtained
3428 * from V8 handles while in the particular V8 isolate. It is up
3429 * to the user of V8 to ensure (perhaps with locking) that this
3430 * constraint is not violated.
Steve Blocka7e24c12009-10-30 11:49:00 +00003431 *
Ben Murdoch257744e2011-11-30 15:57:28 +00003432 * v8::Locker is a scoped lock object. While it's
3433 * active (i.e. between its construction and destruction) the current thread is
3434 * allowed to use the locked isolate. V8 guarantees that an isolate can be locked
3435 * by at most one thread at any time. In other words, the scope of a v8::Locker is
3436 * a critical section.
Steve Block44f0eee2011-05-26 01:26:41 +01003437 *
Ben Murdoch257744e2011-11-30 15:57:28 +00003438 * Sample usage:
3439* \code
Steve Blocka7e24c12009-10-30 11:49:00 +00003440 * ...
3441 * {
Ben Murdoch257744e2011-11-30 15:57:28 +00003442 * v8::Locker locker(isolate);
3443 * v8::Isolate::Scope isolate_scope(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00003444 * ...
Ben Murdoch257744e2011-11-30 15:57:28 +00003445 * // Code using V8 and isolate goes here.
Steve Blocka7e24c12009-10-30 11:49:00 +00003446 * ...
3447 * } // Destructor called here
3448 * \endcode
3449 *
Ben Murdoch257744e2011-11-30 15:57:28 +00003450 * If you wish to stop using V8 in a thread A you can do this either
Steve Blocka7e24c12009-10-30 11:49:00 +00003451 * by destroying the v8::Locker object as above or by constructing a
3452 * v8::Unlocker object:
3453 *
3454 * \code
3455 * {
Ben Murdoch257744e2011-11-30 15:57:28 +00003456 * isolate->Exit();
3457 * v8::Unlocker unlocker(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00003458 * ...
3459 * // Code not using V8 goes here while V8 can run in another thread.
3460 * ...
3461 * } // Destructor called here.
Ben Murdoch257744e2011-11-30 15:57:28 +00003462 * isolate->Enter();
Steve Blocka7e24c12009-10-30 11:49:00 +00003463 * \endcode
3464 *
3465 * The Unlocker object is intended for use in a long-running callback
3466 * from V8, where you want to release the V8 lock for other threads to
3467 * use.
3468 *
3469 * The v8::Locker is a recursive lock. That is, you can lock more than
3470 * once in a given thread. This can be useful if you have code that can
3471 * be called either from code that holds the lock or from code that does
3472 * not. The Unlocker is not recursive so you can not have several
3473 * Unlockers on the stack at once, and you can not use an Unlocker in a
3474 * thread that is not inside a Locker's scope.
3475 *
3476 * An unlocker will unlock several lockers if it has to and reinstate
3477 * the correct depth of locking on its destruction. eg.:
3478 *
3479 * \code
3480 * // V8 not locked.
3481 * {
Ben Murdoch257744e2011-11-30 15:57:28 +00003482 * v8::Locker locker(isolate);
3483 * Isolate::Scope isolate_scope(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00003484 * // V8 locked.
3485 * {
Ben Murdoch257744e2011-11-30 15:57:28 +00003486 * v8::Locker another_locker(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00003487 * // V8 still locked (2 levels).
3488 * {
Ben Murdoch257744e2011-11-30 15:57:28 +00003489 * isolate->Exit();
3490 * v8::Unlocker unlocker(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00003491 * // V8 not locked.
3492 * }
Ben Murdoch257744e2011-11-30 15:57:28 +00003493 * isolate->Enter();
Steve Blocka7e24c12009-10-30 11:49:00 +00003494 * // V8 locked again (2 levels).
3495 * }
3496 * // V8 still locked (1 level).
3497 * }
3498 * // V8 Now no longer locked.
3499 * \endcode
Ben Murdoch257744e2011-11-30 15:57:28 +00003500 *
3501 *
Steve Blocka7e24c12009-10-30 11:49:00 +00003502 */
3503class V8EXPORT Unlocker {
3504 public:
Ben Murdoch257744e2011-11-30 15:57:28 +00003505 /**
3506 * Initialize Unlocker for a given Isolate. NULL means default isolate.
3507 */
3508 explicit Unlocker(Isolate* isolate = NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00003509 ~Unlocker();
Ben Murdoch257744e2011-11-30 15:57:28 +00003510 private:
3511 internal::Isolate* isolate_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003512};
3513
3514
3515class V8EXPORT Locker {
3516 public:
Ben Murdoch257744e2011-11-30 15:57:28 +00003517 /**
3518 * Initialize Locker for a given Isolate. NULL means default isolate.
3519 */
3520 explicit Locker(Isolate* isolate = NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00003521 ~Locker();
3522
3523 /**
3524 * Start preemption.
3525 *
Ben Murdoch257744e2011-11-30 15:57:28 +00003526 * When preemption is started, a timer is fired every n milliseconds
Steve Blocka7e24c12009-10-30 11:49:00 +00003527 * that will switch between multiple threads that are in contention
3528 * for the V8 lock.
3529 */
3530 static void StartPreemption(int every_n_ms);
3531
3532 /**
3533 * Stop preemption.
3534 */
3535 static void StopPreemption();
3536
3537 /**
Ben Murdoch257744e2011-11-30 15:57:28 +00003538 * Returns whether or not the locker for a given isolate, or default isolate if NULL is given,
3539 * is locked by the current thread.
Steve Blocka7e24c12009-10-30 11:49:00 +00003540 */
Ben Murdoch257744e2011-11-30 15:57:28 +00003541 static bool IsLocked(Isolate* isolate = NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00003542
3543 /**
3544 * Returns whether v8::Locker is being used by this V8 instance.
3545 */
3546 static bool IsActive() { return active_; }
3547
3548 private:
3549 bool has_lock_;
3550 bool top_level_;
Ben Murdoch257744e2011-11-30 15:57:28 +00003551 internal::Isolate* isolate_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003552
3553 static bool active_;
3554
3555 // Disallow copying and assigning.
3556 Locker(const Locker&);
3557 void operator=(const Locker&);
3558};
3559
3560
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003561/**
3562 * An interface for exporting data from V8, using "push" model.
3563 */
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003564class V8EXPORT OutputStream { // NOLINT
3565 public:
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003566 enum OutputEncoding {
3567 kAscii = 0 // 7-bit ASCII.
3568 };
3569 enum WriteResult {
3570 kContinue = 0,
3571 kAbort = 1
3572 };
3573 virtual ~OutputStream() {}
3574 /** Notify about the end of stream. */
3575 virtual void EndOfStream() = 0;
3576 /** Get preferred output chunk size. Called only once. */
3577 virtual int GetChunkSize() { return 1024; }
3578 /** Get preferred output encoding. Called only once. */
3579 virtual OutputEncoding GetOutputEncoding() { return kAscii; }
3580 /**
3581 * Writes the next chunk of snapshot data into the stream. Writing
3582 * can be stopped by returning kAbort as function result. EndOfStream
3583 * will not be called in case writing was aborted.
3584 */
3585 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3586};
3587
3588
Ben Murdochb0fe1622011-05-05 13:52:32 +01003589/**
3590 * An interface for reporting progress and controlling long-running
3591 * activities.
3592 */
3593class V8EXPORT ActivityControl { // NOLINT
3594 public:
3595 enum ControlOption {
3596 kContinue = 0,
3597 kAbort = 1
3598 };
3599 virtual ~ActivityControl() {}
3600 /**
3601 * Notify about current progress. The activity can be stopped by
3602 * returning kAbort as the callback result.
3603 */
3604 virtual ControlOption ReportProgressValue(int done, int total) = 0;
3605};
3606
Steve Blocka7e24c12009-10-30 11:49:00 +00003607
Ben Murdoch257744e2011-11-30 15:57:28 +00003608// --- Implementation ---
Steve Blocka7e24c12009-10-30 11:49:00 +00003609
3610
3611namespace internal {
3612
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003613static const int kApiPointerSize = sizeof(void*); // NOLINT
3614static const int kApiIntSize = sizeof(int); // NOLINT
Steve Blocka7e24c12009-10-30 11:49:00 +00003615
3616// Tag information for HeapObject.
3617const int kHeapObjectTag = 1;
3618const int kHeapObjectTagSize = 2;
3619const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3620
Steve Blocka7e24c12009-10-30 11:49:00 +00003621// Tag information for Smi.
3622const int kSmiTag = 0;
3623const int kSmiTagSize = 1;
3624const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3625
Ben Murdochb8e0da22011-05-16 14:20:40 +01003626template <size_t ptr_size> struct SmiTagging;
Steve Block3ce2e202009-11-05 08:53:23 +00003627
3628// Smi constants for 32-bit systems.
Ben Murdochb8e0da22011-05-16 14:20:40 +01003629template <> struct SmiTagging<4> {
Steve Block3ce2e202009-11-05 08:53:23 +00003630 static const int kSmiShiftSize = 0;
3631 static const int kSmiValueSize = 31;
3632 static inline int SmiToInt(internal::Object* value) {
3633 int shift_bits = kSmiTagSize + kSmiShiftSize;
3634 // Throw away top 32 bits and shift down (requires >> to be sign extending).
3635 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3636 }
Ben Murdochb8e0da22011-05-16 14:20:40 +01003637
3638 // For 32-bit systems any 2 bytes aligned pointer can be encoded as smi
3639 // with a plain reinterpret_cast.
Steve Block1e0659c2011-05-24 12:43:12 +01003640 static const uintptr_t kEncodablePointerMask = 0x1;
Ben Murdochb8e0da22011-05-16 14:20:40 +01003641 static const int kPointerToSmiShift = 0;
Steve Block3ce2e202009-11-05 08:53:23 +00003642};
3643
3644// Smi constants for 64-bit systems.
Ben Murdochb8e0da22011-05-16 14:20:40 +01003645template <> struct SmiTagging<8> {
Steve Block3ce2e202009-11-05 08:53:23 +00003646 static const int kSmiShiftSize = 31;
3647 static const int kSmiValueSize = 32;
3648 static inline int SmiToInt(internal::Object* value) {
3649 int shift_bits = kSmiTagSize + kSmiShiftSize;
3650 // Shift down and throw away top 32 bits.
3651 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3652 }
Ben Murdochb8e0da22011-05-16 14:20:40 +01003653
3654 // To maximize the range of pointers that can be encoded
3655 // in the available 32 bits, we require them to be 8 bytes aligned.
3656 // This gives 2 ^ (32 + 3) = 32G address space covered.
3657 // It might be not enough to cover stack allocated objects on some platforms.
3658 static const int kPointerAlignment = 3;
3659
Steve Block1e0659c2011-05-24 12:43:12 +01003660 static const uintptr_t kEncodablePointerMask =
3661 ~(uintptr_t(0xffffffff) << kPointerAlignment);
Ben Murdochb8e0da22011-05-16 14:20:40 +01003662
3663 static const int kPointerToSmiShift =
3664 kSmiTagSize + kSmiShiftSize - kPointerAlignment;
Steve Block3ce2e202009-11-05 08:53:23 +00003665};
3666
Ben Murdochb8e0da22011-05-16 14:20:40 +01003667typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
3668const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
3669const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
Steve Block1e0659c2011-05-24 12:43:12 +01003670const uintptr_t kEncodablePointerMask =
Ben Murdochb8e0da22011-05-16 14:20:40 +01003671 PlatformSmiTagging::kEncodablePointerMask;
3672const int kPointerToSmiShift = PlatformSmiTagging::kPointerToSmiShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00003673
Steve Blockd0582a62009-12-15 09:54:21 +00003674template <size_t ptr_size> struct InternalConstants;
3675
3676// Internal constants for 32-bit systems.
3677template <> struct InternalConstants<4> {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003678 static const int kStringResourceOffset = 3 * kApiPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003679};
3680
3681// Internal constants for 64-bit systems.
3682template <> struct InternalConstants<8> {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003683 static const int kStringResourceOffset = 3 * kApiPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003684};
3685
Steve Blocka7e24c12009-10-30 11:49:00 +00003686/**
3687 * This class exports constants and functionality from within v8 that
3688 * is necessary to implement inline functions in the v8 api. Don't
3689 * depend on functions and constants defined here.
3690 */
3691class Internals {
3692 public:
3693
3694 // These values match non-compiler-dependent values defined within
3695 // the implementation of v8.
3696 static const int kHeapObjectMapOffset = 0;
Steve Block44f0eee2011-05-26 01:26:41 +01003697 static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003698 static const int kStringResourceOffset =
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003699 InternalConstants<kApiPointerSize>::kStringResourceOffset;
Steve Blockd0582a62009-12-15 09:54:21 +00003700
Ben Murdoch257744e2011-11-30 15:57:28 +00003701 static const int kForeignAddressOffset = kApiPointerSize;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003702 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003703 static const int kFullStringRepresentationMask = 0x07;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003704 static const int kExternalTwoByteRepresentationTag = 0x02;
Steve Blocka7e24c12009-10-30 11:49:00 +00003705
Ben Murdoch257744e2011-11-30 15:57:28 +00003706 static const int kJSObjectType = 0xa2;
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003707 static const int kFirstNonstringType = 0x80;
Ben Murdoch257744e2011-11-30 15:57:28 +00003708 static const int kForeignType = 0x85;
Steve Blocka7e24c12009-10-30 11:49:00 +00003709
3710 static inline bool HasHeapObjectTag(internal::Object* value) {
3711 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3712 kHeapObjectTag);
3713 }
3714
3715 static inline bool HasSmiTag(internal::Object* value) {
3716 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3717 }
3718
3719 static inline int SmiValue(internal::Object* value) {
Ben Murdochb8e0da22011-05-16 14:20:40 +01003720 return PlatformSmiTagging::SmiToInt(value);
Steve Block3ce2e202009-11-05 08:53:23 +00003721 }
3722
3723 static inline int GetInstanceType(internal::Object* obj) {
3724 typedef internal::Object O;
3725 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3726 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3727 }
3728
Ben Murdochb8e0da22011-05-16 14:20:40 +01003729 static inline void* GetExternalPointerFromSmi(internal::Object* value) {
Steve Block1e0659c2011-05-24 12:43:12 +01003730 const uintptr_t address = reinterpret_cast<uintptr_t>(value);
Ben Murdochb8e0da22011-05-16 14:20:40 +01003731 return reinterpret_cast<void*>(address >> kPointerToSmiShift);
3732 }
3733
Steve Block3ce2e202009-11-05 08:53:23 +00003734 static inline void* GetExternalPointer(internal::Object* obj) {
3735 if (HasSmiTag(obj)) {
Ben Murdochb8e0da22011-05-16 14:20:40 +01003736 return GetExternalPointerFromSmi(obj);
Ben Murdoch257744e2011-11-30 15:57:28 +00003737 } else if (GetInstanceType(obj) == kForeignType) {
3738 return ReadField<void*>(obj, kForeignAddressOffset);
Steve Block3ce2e202009-11-05 08:53:23 +00003739 } else {
3740 return NULL;
3741 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003742 }
3743
3744 static inline bool IsExternalTwoByteString(int instance_type) {
3745 int representation = (instance_type & kFullStringRepresentationMask);
3746 return representation == kExternalTwoByteRepresentationTag;
3747 }
3748
3749 template <typename T>
3750 static inline T ReadField(Object* ptr, int offset) {
3751 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3752 return *reinterpret_cast<T*>(addr);
3753 }
Steve Block44f0eee2011-05-26 01:26:41 +01003754
3755 static inline bool CanCastToHeapObject(void* o) { return false; }
3756 static inline bool CanCastToHeapObject(Context* o) { return true; }
3757 static inline bool CanCastToHeapObject(String* o) { return true; }
3758 static inline bool CanCastToHeapObject(Object* o) { return true; }
3759 static inline bool CanCastToHeapObject(Message* o) { return true; }
3760 static inline bool CanCastToHeapObject(StackTrace* o) { return true; }
3761 static inline bool CanCastToHeapObject(StackFrame* o) { return true; }
Steve Blocka7e24c12009-10-30 11:49:00 +00003762};
3763
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003764} // namespace internal
Steve Blocka7e24c12009-10-30 11:49:00 +00003765
3766
3767template <class T>
3768Handle<T>::Handle() : val_(0) { }
3769
3770
3771template <class T>
3772Local<T>::Local() : Handle<T>() { }
3773
3774
3775template <class T>
3776Local<T> Local<T>::New(Handle<T> that) {
3777 if (that.IsEmpty()) return Local<T>();
Steve Block44f0eee2011-05-26 01:26:41 +01003778 T* that_ptr = *that;
3779 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
3780 if (internal::Internals::CanCastToHeapObject(that_ptr)) {
3781 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
3782 reinterpret_cast<internal::HeapObject*>(*p))));
3783 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003784 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3785}
3786
3787
3788template <class T>
3789Persistent<T> Persistent<T>::New(Handle<T> that) {
3790 if (that.IsEmpty()) return Persistent<T>();
3791 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3792 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3793}
3794
3795
3796template <class T>
3797bool Persistent<T>::IsNearDeath() const {
3798 if (this->IsEmpty()) return false;
3799 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3800}
3801
3802
3803template <class T>
3804bool Persistent<T>::IsWeak() const {
3805 if (this->IsEmpty()) return false;
3806 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3807}
3808
3809
3810template <class T>
3811void Persistent<T>::Dispose() {
3812 if (this->IsEmpty()) return;
3813 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3814}
3815
3816
3817template <class T>
3818Persistent<T>::Persistent() : Handle<T>() { }
3819
3820template <class T>
3821void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3822 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3823 parameters,
3824 callback);
3825}
3826
3827template <class T>
3828void Persistent<T>::ClearWeak() {
3829 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
3830}
3831
Steve Block44f0eee2011-05-26 01:26:41 +01003832template <class T>
Ben Murdoch257744e2011-11-30 15:57:28 +00003833void Persistent<T>::MarkIndependent() {
3834 V8::MarkIndependent(reinterpret_cast<internal::Object**>(**this));
3835}
3836
3837template <class T>
Steve Block44f0eee2011-05-26 01:26:41 +01003838void Persistent<T>::SetWrapperClassId(uint16_t class_id) {
3839 V8::SetWrapperClassId(reinterpret_cast<internal::Object**>(**this), class_id);
3840}
Steve Block8defd9f2010-07-08 12:39:36 +01003841
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003842Arguments::Arguments(internal::Object** implicit_args,
3843 internal::Object** values, int length,
3844 bool is_construct_call)
3845 : implicit_args_(implicit_args),
3846 values_(values),
3847 length_(length),
3848 is_construct_call_(is_construct_call) { }
Steve Block8defd9f2010-07-08 12:39:36 +01003849
3850
Steve Blocka7e24c12009-10-30 11:49:00 +00003851Local<Value> Arguments::operator[](int i) const {
3852 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
3853 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
3854}
3855
3856
3857Local<Function> Arguments::Callee() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003858 return Local<Function>(reinterpret_cast<Function*>(
3859 &implicit_args_[kCalleeIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003860}
3861
3862
3863Local<Object> Arguments::This() const {
3864 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
3865}
3866
3867
3868Local<Object> Arguments::Holder() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003869 return Local<Object>(reinterpret_cast<Object*>(
3870 &implicit_args_[kHolderIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003871}
3872
3873
3874Local<Value> Arguments::Data() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003875 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003876}
3877
3878
3879bool Arguments::IsConstructCall() const {
3880 return is_construct_call_;
3881}
3882
3883
3884int Arguments::Length() const {
3885 return length_;
3886}
3887
3888
3889template <class T>
3890Local<T> HandleScope::Close(Handle<T> value) {
3891 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
3892 internal::Object** after = RawClose(before);
3893 return Local<T>(reinterpret_cast<T*>(after));
3894}
3895
3896Handle<Value> ScriptOrigin::ResourceName() const {
3897 return resource_name_;
3898}
3899
3900
3901Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
3902 return resource_line_offset_;
3903}
3904
3905
3906Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
3907 return resource_column_offset_;
3908}
3909
3910
3911Handle<Boolean> Boolean::New(bool value) {
3912 return value ? True() : False();
3913}
3914
3915
3916void Template::Set(const char* name, v8::Handle<Data> value) {
3917 Set(v8::String::New(name), value);
3918}
3919
3920
3921Local<Value> Object::GetInternalField(int index) {
3922#ifndef V8_ENABLE_CHECKS
3923 Local<Value> quick_result = UncheckedGetInternalField(index);
3924 if (!quick_result.IsEmpty()) return quick_result;
3925#endif
3926 return CheckedGetInternalField(index);
3927}
3928
3929
3930Local<Value> Object::UncheckedGetInternalField(int index) {
3931 typedef internal::Object O;
3932 typedef internal::Internals I;
3933 O* obj = *reinterpret_cast<O**>(this);
Steve Block3ce2e202009-11-05 08:53:23 +00003934 if (I::GetInstanceType(obj) == I::kJSObjectType) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003935 // If the object is a plain JSObject, which is the common case,
3936 // we know where to find the internal fields and can return the
3937 // value directly.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003938 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003939 O* value = I::ReadField<O*>(obj, offset);
3940 O** result = HandleScope::CreateHandle(value);
3941 return Local<Value>(reinterpret_cast<Value*>(result));
3942 } else {
3943 return Local<Value>();
3944 }
3945}
3946
3947
3948void* External::Unwrap(Handle<v8::Value> obj) {
3949#ifdef V8_ENABLE_CHECKS
3950 return FullUnwrap(obj);
3951#else
3952 return QuickUnwrap(obj);
3953#endif
3954}
3955
3956
3957void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
3958 typedef internal::Object O;
Steve Blocka7e24c12009-10-30 11:49:00 +00003959 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
Steve Block3ce2e202009-11-05 08:53:23 +00003960 return internal::Internals::GetExternalPointer(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00003961}
3962
3963
3964void* Object::GetPointerFromInternalField(int index) {
Steve Block3ce2e202009-11-05 08:53:23 +00003965 typedef internal::Object O;
3966 typedef internal::Internals I;
3967
3968 O* obj = *reinterpret_cast<O**>(this);
3969
3970 if (I::GetInstanceType(obj) == I::kJSObjectType) {
3971 // If the object is a plain JSObject, which is the common case,
3972 // we know where to find the internal fields and can return the
3973 // value directly.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003974 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
Steve Block3ce2e202009-11-05 08:53:23 +00003975 O* value = I::ReadField<O*>(obj, offset);
3976 return I::GetExternalPointer(value);
3977 }
3978
3979 return SlowGetPointerFromInternalField(index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003980}
3981
3982
3983String* String::Cast(v8::Value* value) {
3984#ifdef V8_ENABLE_CHECKS
3985 CheckCast(value);
3986#endif
3987 return static_cast<String*>(value);
3988}
3989
3990
3991String::ExternalStringResource* String::GetExternalStringResource() const {
3992 typedef internal::Object O;
3993 typedef internal::Internals I;
3994 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
Steve Blocka7e24c12009-10-30 11:49:00 +00003995 String::ExternalStringResource* result;
Steve Block3ce2e202009-11-05 08:53:23 +00003996 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003997 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
3998 result = reinterpret_cast<String::ExternalStringResource*>(value);
3999 } else {
4000 result = NULL;
4001 }
4002#ifdef V8_ENABLE_CHECKS
4003 VerifyExternalStringResource(result);
4004#endif
4005 return result;
4006}
4007
4008
4009bool Value::IsString() const {
4010#ifdef V8_ENABLE_CHECKS
4011 return FullIsString();
4012#else
4013 return QuickIsString();
4014#endif
4015}
4016
4017bool Value::QuickIsString() const {
4018 typedef internal::Object O;
4019 typedef internal::Internals I;
4020 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
4021 if (!I::HasHeapObjectTag(obj)) return false;
Steve Block3ce2e202009-11-05 08:53:23 +00004022 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
Steve Blocka7e24c12009-10-30 11:49:00 +00004023}
4024
4025
4026Number* Number::Cast(v8::Value* value) {
4027#ifdef V8_ENABLE_CHECKS
4028 CheckCast(value);
4029#endif
4030 return static_cast<Number*>(value);
4031}
4032
4033
4034Integer* Integer::Cast(v8::Value* value) {
4035#ifdef V8_ENABLE_CHECKS
4036 CheckCast(value);
4037#endif
4038 return static_cast<Integer*>(value);
4039}
4040
4041
4042Date* Date::Cast(v8::Value* value) {
4043#ifdef V8_ENABLE_CHECKS
4044 CheckCast(value);
4045#endif
4046 return static_cast<Date*>(value);
4047}
4048
4049
Ben Murdochf87a2032010-10-22 12:50:53 +01004050RegExp* RegExp::Cast(v8::Value* value) {
4051#ifdef V8_ENABLE_CHECKS
4052 CheckCast(value);
4053#endif
4054 return static_cast<RegExp*>(value);
4055}
4056
4057
Steve Blocka7e24c12009-10-30 11:49:00 +00004058Object* Object::Cast(v8::Value* value) {
4059#ifdef V8_ENABLE_CHECKS
4060 CheckCast(value);
4061#endif
4062 return static_cast<Object*>(value);
4063}
4064
4065
4066Array* Array::Cast(v8::Value* value) {
4067#ifdef V8_ENABLE_CHECKS
4068 CheckCast(value);
4069#endif
4070 return static_cast<Array*>(value);
4071}
4072
4073
4074Function* Function::Cast(v8::Value* value) {
4075#ifdef V8_ENABLE_CHECKS
4076 CheckCast(value);
4077#endif
4078 return static_cast<Function*>(value);
4079}
4080
4081
4082External* External::Cast(v8::Value* value) {
4083#ifdef V8_ENABLE_CHECKS
4084 CheckCast(value);
4085#endif
4086 return static_cast<External*>(value);
4087}
4088
4089
4090Local<Value> AccessorInfo::Data() const {
Steve Block6ded16b2010-05-10 14:33:55 +01004091 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
Steve Blocka7e24c12009-10-30 11:49:00 +00004092}
4093
4094
4095Local<Object> AccessorInfo::This() const {
4096 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
4097}
4098
4099
4100Local<Object> AccessorInfo::Holder() const {
4101 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
4102}
4103
4104
4105/**
4106 * \example shell.cc
4107 * A simple shell that takes a list of expressions on the
4108 * command-line and executes them.
4109 */
4110
4111
4112/**
4113 * \example process.cc
4114 */
4115
4116
4117} // namespace v8
4118
4119
4120#undef V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00004121#undef TYPE_CHECK
4122
4123
4124#endif // V8_H_