blob: 08c2fa2b7eb9e96e35488f3b75a8a3897ddf6cef [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;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000083class StringObject;
Steve Blocka7e24c12009-10-30 11:49:00 +000084class Value;
85class Utils;
86class Number;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000087class NumberObject;
Steve Blocka7e24c12009-10-30 11:49:00 +000088class Object;
89class Array;
90class Int32;
91class Uint32;
92class External;
93class Primitive;
94class Boolean;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000095class BooleanObject;
Steve Blocka7e24c12009-10-30 11:49:00 +000096class Integer;
97class Function;
98class Date;
99class ImplementationUtilities;
100class Signature;
101template <class T> class Handle;
102template <class T> class Local;
103template <class T> class Persistent;
104class FunctionTemplate;
105class ObjectTemplate;
106class Data;
Leon Clarkef7060e22010-06-03 12:02:55 +0100107class AccessorInfo;
Kristian Monsen25f61362010-05-21 11:50:48 +0100108class StackTrace;
109class StackFrame;
Steve Blocka7e24c12009-10-30 11:49:00 +0000110
111namespace internal {
112
Steve Blocka7e24c12009-10-30 11:49:00 +0000113class Arguments;
Steve Blockd0582a62009-12-15 09:54:21 +0000114class Object;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100115class Heap;
Steve Block44f0eee2011-05-26 01:26:41 +0100116class HeapObject;
117class Isolate;
Steve Blocka7e24c12009-10-30 11:49:00 +0000118}
119
120
Ben Murdoch257744e2011-11-30 15:57:28 +0000121// --- Weak Handles ---
Steve Blocka7e24c12009-10-30 11:49:00 +0000122
123
124/**
125 * A weak reference callback function.
126 *
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100127 * This callback should either explicitly invoke Dispose on |object| if
128 * V8 wrapper is not needed anymore, or 'revive' it by invocation of MakeWeak.
129 *
Steve Blocka7e24c12009-10-30 11:49:00 +0000130 * \param object the weak global object to be reclaimed by the garbage collector
131 * \param parameter the value passed in when making the weak global object
132 */
133typedef void (*WeakReferenceCallback)(Persistent<Value> object,
134 void* parameter);
135
136
Ben Murdoch257744e2011-11-30 15:57:28 +0000137// --- Handles ---
Steve Blocka7e24c12009-10-30 11:49:00 +0000138
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100139#define TYPE_CHECK(T, S) \
140 while (false) { \
141 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
Steve Blocka7e24c12009-10-30 11:49:00 +0000142 }
143
144/**
145 * An object reference managed by the v8 garbage collector.
146 *
147 * All objects returned from v8 have to be tracked by the garbage
148 * collector so that it knows that the objects are still alive. Also,
149 * because the garbage collector may move objects, it is unsafe to
150 * point directly to an object. Instead, all objects are stored in
151 * handles which are known by the garbage collector and updated
152 * whenever an object moves. Handles should always be passed by value
153 * (except in cases like out-parameters) and they should never be
154 * allocated on the heap.
155 *
156 * There are two types of handles: local and persistent handles.
157 * Local handles are light-weight and transient and typically used in
158 * local operations. They are managed by HandleScopes. Persistent
159 * handles can be used when storing objects across several independent
160 * operations and have to be explicitly deallocated when they're no
161 * longer used.
162 *
163 * It is safe to extract the object stored in the handle by
164 * dereferencing the handle (for instance, to extract the Object* from
Ben Murdoch257744e2011-11-30 15:57:28 +0000165 * a Handle<Object>); the value will still be governed by a handle
Steve Blocka7e24c12009-10-30 11:49:00 +0000166 * behind the scenes and the same rules apply to these values as to
167 * their handles.
168 */
Steve Block8defd9f2010-07-08 12:39:36 +0100169template <class T> class Handle {
Steve Blocka7e24c12009-10-30 11:49:00 +0000170 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000171 /**
172 * Creates an empty handle.
173 */
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000174 inline Handle() : val_(0) {}
Steve Blocka7e24c12009-10-30 11:49:00 +0000175
176 /**
177 * Creates a new handle for the specified value.
178 */
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000179 inline explicit Handle(T* val) : val_(val) {}
Steve Blocka7e24c12009-10-30 11:49:00 +0000180
181 /**
182 * Creates a handle for the contents of the specified handle. This
183 * constructor allows you to pass handles as arguments by value and
184 * to assign between handles. However, if you try to assign between
185 * incompatible handles, for instance from a Handle<String> to a
Ben Murdoch257744e2011-11-30 15:57:28 +0000186 * Handle<Number> it will cause a compile-time error. Assigning
Steve Blocka7e24c12009-10-30 11:49:00 +0000187 * between compatible handles, for instance assigning a
188 * Handle<String> to a variable declared as Handle<Value>, is legal
189 * because String is a subclass of Value.
190 */
191 template <class S> inline Handle(Handle<S> that)
192 : val_(reinterpret_cast<T*>(*that)) {
193 /**
194 * This check fails when trying to convert between incompatible
195 * handles. For example, converting from a Handle<String> to a
196 * Handle<Number>.
197 */
198 TYPE_CHECK(T, S);
199 }
200
201 /**
202 * Returns true if the handle is empty.
203 */
Steve Block8defd9f2010-07-08 12:39:36 +0100204 inline bool IsEmpty() const { return val_ == 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000205
Steve Blocka7e24c12009-10-30 11:49:00 +0000206 /**
207 * Sets the handle to be empty. IsEmpty() will then return true.
208 */
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000209 inline void Clear() { val_ = 0; }
210
211 inline T* operator->() const { return val_; }
212
213 inline T* operator*() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000214
215 /**
216 * Checks whether two handles are the same.
217 * Returns true if both are empty, or if the objects
218 * to which they refer are identical.
219 * The handles' references are not checked.
220 */
Steve Block8defd9f2010-07-08 12:39:36 +0100221 template <class S> inline bool operator==(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000222 internal::Object** a = reinterpret_cast<internal::Object**>(**this);
223 internal::Object** b = reinterpret_cast<internal::Object**>(*that);
224 if (a == 0) return b == 0;
225 if (b == 0) return false;
226 return *a == *b;
227 }
228
229 /**
230 * Checks whether two handles are different.
231 * Returns true if only one of the handles is empty, or if
232 * the objects to which they refer are different.
233 * The handles' references are not checked.
234 */
Steve Block8defd9f2010-07-08 12:39:36 +0100235 template <class S> inline bool operator!=(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000236 return !operator==(that);
237 }
238
239 template <class S> static inline Handle<T> Cast(Handle<S> that) {
240#ifdef V8_ENABLE_CHECKS
241 // If we're going to perform the type check then we have to check
242 // that the handle isn't empty before doing the checked cast.
243 if (that.IsEmpty()) return Handle<T>();
244#endif
245 return Handle<T>(T::Cast(*that));
246 }
247
Steve Block6ded16b2010-05-10 14:33:55 +0100248 template <class S> inline Handle<S> As() {
249 return Handle<S>::Cast(*this);
250 }
251
Steve Blocka7e24c12009-10-30 11:49:00 +0000252 private:
253 T* val_;
254};
255
256
257/**
258 * A light-weight stack-allocated object handle. All operations
259 * that return objects from within v8 return them in local handles. They
260 * are created within HandleScopes, and all local handles allocated within a
261 * handle scope are destroyed when the handle scope is destroyed. Hence it
262 * is not necessary to explicitly deallocate local handles.
263 */
Steve Block8defd9f2010-07-08 12:39:36 +0100264template <class T> class Local : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000265 public:
266 inline Local();
267 template <class S> inline Local(Local<S> that)
268 : Handle<T>(reinterpret_cast<T*>(*that)) {
269 /**
270 * This check fails when trying to convert between incompatible
271 * handles. For example, converting from a Handle<String> to a
272 * Handle<Number>.
273 */
274 TYPE_CHECK(T, S);
275 }
276 template <class S> inline Local(S* that) : Handle<T>(that) { }
277 template <class S> static inline Local<T> Cast(Local<S> that) {
278#ifdef V8_ENABLE_CHECKS
279 // If we're going to perform the type check then we have to check
280 // that the handle isn't empty before doing the checked cast.
281 if (that.IsEmpty()) return Local<T>();
282#endif
283 return Local<T>(T::Cast(*that));
284 }
285
Steve Block6ded16b2010-05-10 14:33:55 +0100286 template <class S> inline Local<S> As() {
287 return Local<S>::Cast(*this);
288 }
289
Steve Blocka7e24c12009-10-30 11:49:00 +0000290 /** Create a local handle for the content of another handle.
291 * The referee is kept alive by the local handle even when
292 * the original handle is destroyed/disposed.
293 */
294 inline static Local<T> New(Handle<T> that);
295};
296
297
298/**
299 * An object reference that is independent of any handle scope. Where
300 * a Local handle only lives as long as the HandleScope in which it was
301 * allocated, a Persistent handle remains valid until it is explicitly
302 * disposed.
303 *
304 * A persistent handle contains a reference to a storage cell within
305 * the v8 engine which holds an object value and which is updated by
306 * the garbage collector whenever the object is moved. A new storage
307 * cell can be created using Persistent::New and existing handles can
308 * be disposed using Persistent::Dispose. Since persistent handles
309 * are passed by value you may have many persistent handle objects
310 * that point to the same storage cell. For instance, if you pass a
311 * persistent handle as an argument to a function you will not get two
312 * different storage cells but rather two references to the same
313 * storage cell.
314 */
Steve Block8defd9f2010-07-08 12:39:36 +0100315template <class T> class Persistent : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000316 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000317 /**
318 * Creates an empty persistent handle that doesn't point to any
319 * storage cell.
320 */
321 inline Persistent();
322
323 /**
324 * Creates a persistent handle for the same storage cell as the
325 * specified handle. This constructor allows you to pass persistent
326 * handles as arguments by value and to assign between persistent
327 * handles. However, attempting to assign between incompatible
328 * persistent handles, for instance from a Persistent<String> to a
Ben Murdoch257744e2011-11-30 15:57:28 +0000329 * Persistent<Number> will cause a compile-time error. Assigning
Steve Blocka7e24c12009-10-30 11:49:00 +0000330 * between compatible persistent handles, for instance assigning a
331 * Persistent<String> to a variable declared as Persistent<Value>,
332 * is allowed as String is a subclass of Value.
333 */
334 template <class S> inline Persistent(Persistent<S> that)
335 : Handle<T>(reinterpret_cast<T*>(*that)) {
336 /**
337 * This check fails when trying to convert between incompatible
338 * handles. For example, converting from a Handle<String> to a
339 * Handle<Number>.
340 */
341 TYPE_CHECK(T, S);
342 }
343
344 template <class S> inline Persistent(S* that) : Handle<T>(that) { }
345
346 /**
347 * "Casts" a plain handle which is known to be a persistent handle
348 * to a persistent handle.
349 */
350 template <class S> explicit inline Persistent(Handle<S> that)
351 : Handle<T>(*that) { }
352
353 template <class S> static inline Persistent<T> Cast(Persistent<S> that) {
354#ifdef V8_ENABLE_CHECKS
355 // If we're going to perform the type check then we have to check
356 // that the handle isn't empty before doing the checked cast.
357 if (that.IsEmpty()) return Persistent<T>();
358#endif
359 return Persistent<T>(T::Cast(*that));
360 }
361
Steve Block6ded16b2010-05-10 14:33:55 +0100362 template <class S> inline Persistent<S> As() {
363 return Persistent<S>::Cast(*this);
364 }
365
Steve Blocka7e24c12009-10-30 11:49:00 +0000366 /**
367 * Creates a new persistent handle for an existing local or
368 * persistent handle.
369 */
370 inline static Persistent<T> New(Handle<T> that);
371
372 /**
373 * Releases the storage cell referenced by this persistent handle.
374 * Does not remove the reference to the cell from any handles.
Ben Murdoch257744e2011-11-30 15:57:28 +0000375 * This handle's reference, and any other references to the storage
Steve Blocka7e24c12009-10-30 11:49:00 +0000376 * cell remain and IsEmpty will still return false.
377 */
378 inline void Dispose();
379
380 /**
381 * Make the reference to this object weak. When only weak handles
382 * refer to the object, the garbage collector will perform a
383 * callback to the given V8::WeakReferenceCallback function, passing
384 * it the object reference and the given parameters.
385 */
386 inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
387
388 /** Clears the weak reference to this object.*/
389 inline void ClearWeak();
390
391 /**
Ben Murdoch257744e2011-11-30 15:57:28 +0000392 * Marks the reference to this object independent. Garbage collector
393 * is free to ignore any object groups containing this object.
394 * Weak callback for an independent handle should not
395 * assume that it will be preceded by a global GC prologue callback
396 * or followed by a global GC epilogue callback.
397 */
398 inline void MarkIndependent();
399
400 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000401 *Checks if the handle holds the only reference to an object.
402 */
403 inline bool IsNearDeath() const;
404
405 /**
406 * Returns true if the handle's reference is weak.
407 */
408 inline bool IsWeak() const;
409
Steve Block44f0eee2011-05-26 01:26:41 +0100410 /**
411 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo
412 * interface description in v8-profiler.h for details.
413 */
414 inline void SetWrapperClassId(uint16_t class_id);
415
Steve Blocka7e24c12009-10-30 11:49:00 +0000416 private:
417 friend class ImplementationUtilities;
418 friend class ObjectTemplate;
419};
420
421
422 /**
423 * A stack-allocated class that governs a number of local handles.
424 * After a handle scope has been created, all local handles will be
425 * allocated within that handle scope until either the handle scope is
426 * deleted or another handle scope is created. If there is already a
427 * handle scope and a new one is created, all allocations will take
428 * place in the new handle scope until it is deleted. After that,
429 * new handles will again be allocated in the original handle scope.
430 *
431 * After the handle scope of a local handle has been deleted the
432 * garbage collector will no longer track the object stored in the
433 * handle and may deallocate it. The behavior of accessing a handle
434 * for which the handle scope has been deleted is undefined.
435 */
436class V8EXPORT HandleScope {
437 public:
438 HandleScope();
439
440 ~HandleScope();
441
442 /**
443 * Closes the handle scope and returns the value as a handle in the
444 * previous scope, which is the new current scope after the call.
445 */
446 template <class T> Local<T> Close(Handle<T> value);
447
448 /**
449 * Counts the number of allocated handles.
450 */
451 static int NumberOfHandles();
452
453 /**
454 * Creates a new handle with the given value.
455 */
456 static internal::Object** CreateHandle(internal::Object* value);
Steve Block44f0eee2011-05-26 01:26:41 +0100457 // Faster version, uses HeapObject to obtain the current Isolate.
458 static internal::Object** CreateHandle(internal::HeapObject* value);
Steve Blocka7e24c12009-10-30 11:49:00 +0000459
460 private:
461 // Make it impossible to create heap-allocated or illegal handle
462 // scopes by disallowing certain operations.
463 HandleScope(const HandleScope&);
464 void operator=(const HandleScope&);
465 void* operator new(size_t size);
466 void operator delete(void*, size_t);
467
Steve Blockd0582a62009-12-15 09:54:21 +0000468 // This Data class is accessible internally as HandleScopeData through a
469 // typedef in the ImplementationUtilities class.
Steve Blocka7e24c12009-10-30 11:49:00 +0000470 class V8EXPORT Data {
471 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000472 internal::Object** next;
473 internal::Object** limit;
John Reck59135872010-11-02 12:39:01 -0700474 int level;
Steve Blocka7e24c12009-10-30 11:49:00 +0000475 inline void Initialize() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000476 next = limit = NULL;
John Reck59135872010-11-02 12:39:01 -0700477 level = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000478 }
479 };
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800480
John Reck59135872010-11-02 12:39:01 -0700481 void Leave();
Steve Blocka7e24c12009-10-30 11:49:00 +0000482
Steve Block44f0eee2011-05-26 01:26:41 +0100483 internal::Isolate* isolate_;
John Reck59135872010-11-02 12:39:01 -0700484 internal::Object** prev_next_;
485 internal::Object** prev_limit_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000486
487 // Allow for the active closing of HandleScopes which allows to pass a handle
488 // from the HandleScope being closed to the next top most HandleScope.
489 bool is_closed_;
490 internal::Object** RawClose(internal::Object** value);
491
492 friend class ImplementationUtilities;
493};
494
495
Ben Murdoch257744e2011-11-30 15:57:28 +0000496// --- Special objects ---
Steve Blocka7e24c12009-10-30 11:49:00 +0000497
498
499/**
500 * The superclass of values and API object templates.
501 */
502class V8EXPORT Data {
503 private:
504 Data();
505};
506
507
508/**
509 * Pre-compilation data that can be associated with a script. This
510 * data can be calculated for a script in advance of actually
511 * compiling it, and can be stored between compilations. When script
512 * data is given to the compile method compilation will be faster.
513 */
514class V8EXPORT ScriptData { // NOLINT
515 public:
516 virtual ~ScriptData() { }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100517
Leon Clarkef7060e22010-06-03 12:02:55 +0100518 /**
519 * Pre-compiles the specified script (context-independent).
520 *
521 * \param input Pointer to UTF-8 script source code.
522 * \param length Length of UTF-8 script source code.
523 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000524 static ScriptData* PreCompile(const char* input, int length);
Steve Blocka7e24c12009-10-30 11:49:00 +0000525
Leon Clarkef7060e22010-06-03 12:02:55 +0100526 /**
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100527 * Pre-compiles the specified script (context-independent).
528 *
529 * NOTE: Pre-compilation using this method cannot happen on another thread
530 * without using Lockers.
531 *
532 * \param source Script source code.
533 */
534 static ScriptData* PreCompile(Handle<String> source);
535
536 /**
Leon Clarkef7060e22010-06-03 12:02:55 +0100537 * Load previous pre-compilation data.
538 *
539 * \param data Pointer to data returned by a call to Data() of a previous
540 * ScriptData. Ownership is not transferred.
541 * \param length Length of data.
542 */
543 static ScriptData* New(const char* data, int length);
544
545 /**
546 * Returns the length of Data().
547 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000548 virtual int Length() = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +0100549
550 /**
551 * Returns a serialized representation of this ScriptData that can later be
552 * passed to New(). NOTE: Serialized data is platform-dependent.
553 */
554 virtual const char* Data() = 0;
555
556 /**
557 * Returns true if the source code could not be parsed.
558 */
Leon Clarkee46be812010-01-19 14:06:41 +0000559 virtual bool HasError() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000560};
561
562
563/**
564 * The origin, within a file, of a script.
565 */
Steve Block8defd9f2010-07-08 12:39:36 +0100566class ScriptOrigin {
Steve Blocka7e24c12009-10-30 11:49:00 +0000567 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100568 inline ScriptOrigin(
569 Handle<Value> resource_name,
570 Handle<Integer> resource_line_offset = Handle<Integer>(),
571 Handle<Integer> resource_column_offset = Handle<Integer>())
Steve Blocka7e24c12009-10-30 11:49:00 +0000572 : resource_name_(resource_name),
573 resource_line_offset_(resource_line_offset),
574 resource_column_offset_(resource_column_offset) { }
575 inline Handle<Value> ResourceName() const;
576 inline Handle<Integer> ResourceLineOffset() const;
577 inline Handle<Integer> ResourceColumnOffset() const;
578 private:
579 Handle<Value> resource_name_;
580 Handle<Integer> resource_line_offset_;
581 Handle<Integer> resource_column_offset_;
582};
583
584
585/**
586 * A compiled JavaScript script.
587 */
588class V8EXPORT Script {
589 public:
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:
Steve Blocka7e24c12009-10-30 11:49:00 +0000861 /**
862 * Returns true if this value is the undefined value. See ECMA-262
863 * 4.3.10.
864 */
Steve Block8defd9f2010-07-08 12:39:36 +0100865 V8EXPORT bool IsUndefined() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000866
867 /**
868 * Returns true if this value is the null value. See ECMA-262
869 * 4.3.11.
870 */
Steve Block8defd9f2010-07-08 12:39:36 +0100871 V8EXPORT bool IsNull() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000872
873 /**
874 * Returns true if this value is true.
875 */
Steve Block8defd9f2010-07-08 12:39:36 +0100876 V8EXPORT bool IsTrue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000877
878 /**
879 * Returns true if this value is false.
880 */
Steve Block8defd9f2010-07-08 12:39:36 +0100881 V8EXPORT bool IsFalse() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000882
883 /**
884 * Returns true if this value is an instance of the String type.
885 * See ECMA-262 8.4.
886 */
887 inline bool IsString() const;
888
889 /**
890 * Returns true if this value is a function.
891 */
Steve Block8defd9f2010-07-08 12:39:36 +0100892 V8EXPORT bool IsFunction() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000893
894 /**
895 * Returns true if this value is an array.
896 */
Steve Block8defd9f2010-07-08 12:39:36 +0100897 V8EXPORT bool IsArray() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000898
899 /**
900 * Returns true if this value is an object.
901 */
Steve Block8defd9f2010-07-08 12:39:36 +0100902 V8EXPORT bool IsObject() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000903
904 /**
905 * Returns true if this value is boolean.
906 */
Steve Block8defd9f2010-07-08 12:39:36 +0100907 V8EXPORT bool IsBoolean() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000908
909 /**
910 * Returns true if this value is a number.
911 */
Steve Block8defd9f2010-07-08 12:39:36 +0100912 V8EXPORT bool IsNumber() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000913
914 /**
915 * Returns true if this value is external.
916 */
Steve Block8defd9f2010-07-08 12:39:36 +0100917 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000918
919 /**
920 * Returns true if this value is a 32-bit signed integer.
921 */
Steve Block8defd9f2010-07-08 12:39:36 +0100922 V8EXPORT bool IsInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000923
924 /**
Steve Block6ded16b2010-05-10 14:33:55 +0100925 * Returns true if this value is a 32-bit unsigned integer.
926 */
Steve Block8defd9f2010-07-08 12:39:36 +0100927 V8EXPORT bool IsUint32() const;
Steve Block6ded16b2010-05-10 14:33:55 +0100928
929 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000930 * Returns true if this value is a Date.
931 */
Steve Block8defd9f2010-07-08 12:39:36 +0100932 V8EXPORT bool IsDate() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000933
Iain Merrick75681382010-08-19 15:07:18 +0100934 /**
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000935 * Returns true if this value is a Boolean object.
936 */
937 V8EXPORT bool IsBooleanObject() const;
938
939 /**
940 * Returns true if this value is a Number object.
941 */
942 V8EXPORT bool IsNumberObject() const;
943
944 /**
945 * Returns true if this value is a String object.
946 */
947 V8EXPORT bool IsStringObject() const;
948
949 /**
950 * Returns true if this value is a NativeError.
951 */
952 V8EXPORT bool IsNativeError() const;
953
954 /**
Iain Merrick75681382010-08-19 15:07:18 +0100955 * Returns true if this value is a RegExp.
956 */
957 V8EXPORT bool IsRegExp() const;
958
Steve Block8defd9f2010-07-08 12:39:36 +0100959 V8EXPORT Local<Boolean> ToBoolean() const;
960 V8EXPORT Local<Number> ToNumber() const;
961 V8EXPORT Local<String> ToString() const;
962 V8EXPORT Local<String> ToDetailString() const;
963 V8EXPORT Local<Object> ToObject() const;
964 V8EXPORT Local<Integer> ToInteger() const;
965 V8EXPORT Local<Uint32> ToUint32() const;
966 V8EXPORT Local<Int32> ToInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000967
968 /**
969 * Attempts to convert a string to an array index.
970 * Returns an empty handle if the conversion fails.
971 */
Steve Block8defd9f2010-07-08 12:39:36 +0100972 V8EXPORT Local<Uint32> ToArrayIndex() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000973
Steve Block8defd9f2010-07-08 12:39:36 +0100974 V8EXPORT bool BooleanValue() const;
975 V8EXPORT double NumberValue() const;
976 V8EXPORT int64_t IntegerValue() const;
977 V8EXPORT uint32_t Uint32Value() const;
978 V8EXPORT int32_t Int32Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000979
980 /** JS == */
Steve Block8defd9f2010-07-08 12:39:36 +0100981 V8EXPORT bool Equals(Handle<Value> that) const;
982 V8EXPORT bool StrictEquals(Handle<Value> that) const;
Steve Block3ce2e202009-11-05 08:53:23 +0000983
Steve Blocka7e24c12009-10-30 11:49:00 +0000984 private:
985 inline bool QuickIsString() const;
Steve Block8defd9f2010-07-08 12:39:36 +0100986 V8EXPORT bool FullIsString() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000987};
988
989
990/**
991 * The superclass of primitive values. See ECMA-262 4.3.2.
992 */
Steve Block8defd9f2010-07-08 12:39:36 +0100993class Primitive : public Value { };
Steve Blocka7e24c12009-10-30 11:49:00 +0000994
995
996/**
997 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
998 * or false value.
999 */
Steve Block8defd9f2010-07-08 12:39:36 +01001000class Boolean : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +00001001 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001002 V8EXPORT bool Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001003 static inline Handle<Boolean> New(bool value);
1004};
1005
1006
1007/**
1008 * A JavaScript string value (ECMA-262, 4.3.17).
1009 */
Steve Block8defd9f2010-07-08 12:39:36 +01001010class String : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +00001011 public:
Steve Blocka7e24c12009-10-30 11:49:00 +00001012 /**
1013 * Returns the number of characters in this string.
1014 */
Steve Block8defd9f2010-07-08 12:39:36 +01001015 V8EXPORT int Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001016
1017 /**
1018 * Returns the number of bytes in the UTF-8 encoded
1019 * representation of this string.
1020 */
Steve Block8defd9f2010-07-08 12:39:36 +01001021 V8EXPORT int Utf8Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001022
1023 /**
1024 * Write the contents of the string to an external buffer.
1025 * If no arguments are given, expects the buffer to be large
1026 * enough to hold the entire string and NULL terminator. Copies
1027 * the contents of the string and the NULL terminator into the
1028 * buffer.
1029 *
Ben Murdochb0fe1622011-05-05 13:52:32 +01001030 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1031 * before the end of the buffer.
1032 *
Steve Blocka7e24c12009-10-30 11:49:00 +00001033 * Copies up to length characters into the output buffer.
1034 * Only null-terminates if there is enough space in the buffer.
1035 *
1036 * \param buffer The buffer into which the string will be copied.
1037 * \param start The starting position within the string at which
1038 * copying begins.
Ben Murdochb0fe1622011-05-05 13:52:32 +01001039 * \param length The number of characters to copy from the string. For
1040 * WriteUtf8 the number of bytes in the buffer.
Steve Block6ded16b2010-05-10 14:33:55 +01001041 * \param nchars_ref The number of characters written, can be NULL.
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001042 * \param options Various options that might affect performance of this or
Steve Block6ded16b2010-05-10 14:33:55 +01001043 * subsequent operations.
Ben Murdochb0fe1622011-05-05 13:52:32 +01001044 * \return The number of characters copied to the buffer excluding the null
1045 * terminator. For WriteUtf8: The number of bytes copied to the buffer
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001046 * including the null terminator (if written).
Steve Blocka7e24c12009-10-30 11:49:00 +00001047 */
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001048 enum WriteOptions {
1049 NO_OPTIONS = 0,
1050 HINT_MANY_WRITES_EXPECTED = 1,
1051 NO_NULL_TERMINATION = 2
Steve Block6ded16b2010-05-10 14:33:55 +01001052 };
1053
Ben Murdoch589d6972011-11-30 16:04:58 +00001054 // 16-bit character codes.
Steve Block8defd9f2010-07-08 12:39:36 +01001055 V8EXPORT int Write(uint16_t* buffer,
1056 int start = 0,
1057 int length = -1,
Ben Murdoch589d6972011-11-30 16:04:58 +00001058 int options = NO_OPTIONS) const;
1059 // ASCII characters.
Steve Block8defd9f2010-07-08 12:39:36 +01001060 V8EXPORT int WriteAscii(char* buffer,
1061 int start = 0,
1062 int length = -1,
Ben Murdoch589d6972011-11-30 16:04:58 +00001063 int options = NO_OPTIONS) const;
1064 // UTF-8 encoded characters.
Steve Block8defd9f2010-07-08 12:39:36 +01001065 V8EXPORT int WriteUtf8(char* buffer,
1066 int length = -1,
1067 int* nchars_ref = NULL,
Ben Murdoch589d6972011-11-30 16:04:58 +00001068 int options = NO_OPTIONS) const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001069
1070 /**
1071 * A zero length string.
1072 */
Steve Block8defd9f2010-07-08 12:39:36 +01001073 V8EXPORT static v8::Local<v8::String> Empty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001074
1075 /**
1076 * Returns true if the string is external
1077 */
Steve Block8defd9f2010-07-08 12:39:36 +01001078 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001079
1080 /**
Ben Murdoch589d6972011-11-30 16:04:58 +00001081 * Returns true if the string is both external and ASCII
Steve Blocka7e24c12009-10-30 11:49:00 +00001082 */
Steve Block8defd9f2010-07-08 12:39:36 +01001083 V8EXPORT bool IsExternalAscii() const;
Leon Clarkee46be812010-01-19 14:06:41 +00001084
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001085 class V8EXPORT ExternalStringResourceBase { // NOLINT
Leon Clarkee46be812010-01-19 14:06:41 +00001086 public:
1087 virtual ~ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001088
Leon Clarkee46be812010-01-19 14:06:41 +00001089 protected:
1090 ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001091
1092 /**
1093 * Internally V8 will call this Dispose method when the external string
1094 * resource is no longer needed. The default implementation will use the
1095 * delete operator. This method can be overridden in subclasses to
1096 * control how allocated external string resources are disposed.
1097 */
1098 virtual void Dispose() { delete this; }
1099
Leon Clarkee46be812010-01-19 14:06:41 +00001100 private:
1101 // Disallow copying and assigning.
1102 ExternalStringResourceBase(const ExternalStringResourceBase&);
1103 void operator=(const ExternalStringResourceBase&);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001104
1105 friend class v8::internal::Heap;
Leon Clarkee46be812010-01-19 14:06:41 +00001106 };
1107
Steve Blocka7e24c12009-10-30 11:49:00 +00001108 /**
1109 * An ExternalStringResource is a wrapper around a two-byte string
1110 * buffer that resides outside V8's heap. Implement an
1111 * ExternalStringResource to manage the life cycle of the underlying
1112 * buffer. Note that the string data must be immutable.
1113 */
Leon Clarkee46be812010-01-19 14:06:41 +00001114 class V8EXPORT ExternalStringResource
1115 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001116 public:
1117 /**
1118 * Override the destructor to manage the life cycle of the underlying
1119 * buffer.
1120 */
1121 virtual ~ExternalStringResource() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001122
1123 /**
1124 * The string data from the underlying buffer.
1125 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001126 virtual const uint16_t* data() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001127
1128 /**
1129 * The length of the string. That is, the number of two-byte characters.
1130 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001131 virtual size_t length() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001132
Steve Blocka7e24c12009-10-30 11:49:00 +00001133 protected:
1134 ExternalStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001135 };
1136
1137 /**
Ben Murdoch589d6972011-11-30 16:04:58 +00001138 * An ExternalAsciiStringResource is a wrapper around an ASCII
Steve Blocka7e24c12009-10-30 11:49:00 +00001139 * string buffer that resides outside V8's heap. Implement an
1140 * ExternalAsciiStringResource to manage the life cycle of the
1141 * underlying buffer. Note that the string data must be immutable
Ben Murdoch589d6972011-11-30 16:04:58 +00001142 * and that the data must be strict (7-bit) ASCII, not Latin-1 or
Steve Blocka7e24c12009-10-30 11:49:00 +00001143 * UTF-8, which would require special treatment internally in the
1144 * engine and, in the case of UTF-8, do not allow efficient indexing.
1145 * Use String::New or convert to 16 bit data for non-ASCII.
1146 */
1147
Leon Clarkee46be812010-01-19 14:06:41 +00001148 class V8EXPORT ExternalAsciiStringResource
1149 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001150 public:
1151 /**
1152 * Override the destructor to manage the life cycle of the underlying
1153 * buffer.
1154 */
1155 virtual ~ExternalAsciiStringResource() {}
1156 /** The string data from the underlying buffer.*/
1157 virtual const char* data() const = 0;
Ben Murdoch589d6972011-11-30 16:04:58 +00001158 /** The number of ASCII characters in the string.*/
Steve Blocka7e24c12009-10-30 11:49:00 +00001159 virtual size_t length() const = 0;
1160 protected:
1161 ExternalAsciiStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001162 };
1163
1164 /**
1165 * Get the ExternalStringResource for an external string. Returns
1166 * NULL if IsExternal() doesn't return true.
1167 */
1168 inline ExternalStringResource* GetExternalStringResource() const;
1169
1170 /**
Ben Murdoch589d6972011-11-30 16:04:58 +00001171 * Get the ExternalAsciiStringResource for an external ASCII string.
Steve Blocka7e24c12009-10-30 11:49:00 +00001172 * Returns NULL if IsExternalAscii() doesn't return true.
1173 */
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001174 V8EXPORT const ExternalAsciiStringResource* GetExternalAsciiStringResource()
1175 const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001176
1177 static inline String* Cast(v8::Value* obj);
1178
1179 /**
Ben Murdoch589d6972011-11-30 16:04:58 +00001180 * Allocates a new string from either UTF-8 encoded or ASCII data.
Steve Blocka7e24c12009-10-30 11:49:00 +00001181 * The second parameter 'length' gives the buffer length.
Ben Murdoch589d6972011-11-30 16:04:58 +00001182 * If the data is UTF-8 encoded, the caller must
Steve Blocka7e24c12009-10-30 11:49:00 +00001183 * be careful to supply the length parameter.
1184 * If it is not given, the function calls
1185 * 'strlen' to determine the buffer length, it might be
1186 * wrong if 'data' contains a null character.
1187 */
Steve Block8defd9f2010-07-08 12:39:36 +01001188 V8EXPORT static Local<String> New(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001189
Ben Murdoch589d6972011-11-30 16:04:58 +00001190 /** Allocates a new string from 16-bit character codes.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001191 V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001192
1193 /** Creates a symbol. Returns one if it exists already.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001194 V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001195
1196 /**
Steve Block3ce2e202009-11-05 08:53:23 +00001197 * Creates a new string by concatenating the left and the right strings
1198 * passed in as parameters.
1199 */
Steve Block8defd9f2010-07-08 12:39:36 +01001200 V8EXPORT static Local<String> Concat(Handle<String> left,
1201 Handle<String>right);
Steve Block3ce2e202009-11-05 08:53:23 +00001202
1203 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001204 * Creates a new external string using the data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001205 * resource. When the external string is no longer live on V8's heap the
1206 * resource will be disposed by calling its Dispose method. The caller of
1207 * this function should not otherwise delete or modify the resource. Neither
1208 * should the underlying buffer be deallocated or modified except through the
1209 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001210 */
Steve Block8defd9f2010-07-08 12:39:36 +01001211 V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001212
1213 /**
1214 * Associate an external string resource with this string by transforming it
1215 * in place so that existing references to this string in the JavaScript heap
1216 * will use the external string resource. The external string resource's
Ben Murdoch257744e2011-11-30 15:57:28 +00001217 * character contents need to be equivalent to this string.
Steve Blocka7e24c12009-10-30 11:49:00 +00001218 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001219 * The string is not modified if the operation fails. See NewExternal for
1220 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001221 */
Steve Block8defd9f2010-07-08 12:39:36 +01001222 V8EXPORT bool MakeExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001223
1224 /**
Ben Murdoch589d6972011-11-30 16:04:58 +00001225 * Creates a new external string using the ASCII data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001226 * resource. When the external string is no longer live on V8's heap the
1227 * resource will be disposed by calling its Dispose method. The caller of
1228 * this function should not otherwise delete or modify the resource. Neither
1229 * should the underlying buffer be deallocated or modified except through the
1230 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001231 */
Steve Block8defd9f2010-07-08 12:39:36 +01001232 V8EXPORT static Local<String> NewExternal(
1233 ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001234
1235 /**
1236 * Associate an external string resource with this string by transforming it
1237 * in place so that existing references to this string in the JavaScript heap
1238 * will use the external string resource. The external string resource's
Ben Murdoch257744e2011-11-30 15:57:28 +00001239 * character contents need to be equivalent to this string.
Steve Blocka7e24c12009-10-30 11:49:00 +00001240 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001241 * The string is not modified if the operation fails. See NewExternal for
1242 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001243 */
Steve Block8defd9f2010-07-08 12:39:36 +01001244 V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001245
1246 /**
1247 * Returns true if this string can be made external.
1248 */
Steve Block8defd9f2010-07-08 12:39:36 +01001249 V8EXPORT bool CanMakeExternal();
Steve Blocka7e24c12009-10-30 11:49:00 +00001250
Ben Murdoch589d6972011-11-30 16:04:58 +00001251 /** Creates an undetectable string from the supplied ASCII or UTF-8 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001252 V8EXPORT static Local<String> NewUndetectable(const char* data,
1253 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001254
Ben Murdoch589d6972011-11-30 16:04:58 +00001255 /** Creates an undetectable string from the supplied 16-bit character codes.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001256 V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1257 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001258
1259 /**
Ben Murdoch589d6972011-11-30 16:04:58 +00001260 * Converts an object to a UTF-8-encoded character array. Useful if
Steve Blocka7e24c12009-10-30 11:49:00 +00001261 * you want to print the object. If conversion to a string fails
Ben Murdoch589d6972011-11-30 16:04:58 +00001262 * (e.g. due to an exception in the toString() method of the object)
Steve Blocka7e24c12009-10-30 11:49:00 +00001263 * then the length() method returns 0 and the * operator returns
1264 * NULL.
1265 */
1266 class V8EXPORT Utf8Value {
1267 public:
1268 explicit Utf8Value(Handle<v8::Value> obj);
1269 ~Utf8Value();
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 Utf8Value(const Utf8Value&);
1279 void operator=(const Utf8Value&);
1280 };
1281
1282 /**
Ben Murdoch589d6972011-11-30 16:04:58 +00001283 * Converts an object to an ASCII string.
Steve Blocka7e24c12009-10-30 11:49:00 +00001284 * Useful if you want to print the object.
1285 * If conversion to a string fails (eg. due to an exception in the toString()
1286 * method of the object) then the length() method returns 0 and the * operator
1287 * returns NULL.
1288 */
1289 class V8EXPORT AsciiValue {
1290 public:
1291 explicit AsciiValue(Handle<v8::Value> obj);
1292 ~AsciiValue();
1293 char* operator*() { return str_; }
1294 const char* operator*() const { return str_; }
1295 int length() const { return length_; }
1296 private:
1297 char* str_;
1298 int length_;
1299
1300 // Disallow copying and assigning.
1301 AsciiValue(const AsciiValue&);
1302 void operator=(const AsciiValue&);
1303 };
1304
1305 /**
1306 * Converts an object to a two-byte string.
1307 * If conversion to a string fails (eg. due to an exception in the toString()
1308 * method of the object) then the length() method returns 0 and the * operator
1309 * returns NULL.
1310 */
1311 class V8EXPORT Value {
1312 public:
1313 explicit Value(Handle<v8::Value> obj);
1314 ~Value();
1315 uint16_t* operator*() { return str_; }
1316 const uint16_t* operator*() const { return str_; }
1317 int length() const { return length_; }
1318 private:
1319 uint16_t* str_;
1320 int length_;
1321
1322 // Disallow copying and assigning.
1323 Value(const Value&);
1324 void operator=(const Value&);
1325 };
Steve Block3ce2e202009-11-05 08:53:23 +00001326
Steve Blocka7e24c12009-10-30 11:49:00 +00001327 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001328 V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1329 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001330};
1331
1332
1333/**
1334 * A JavaScript number value (ECMA-262, 4.3.20)
1335 */
Steve Block8defd9f2010-07-08 12:39:36 +01001336class Number : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +00001337 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001338 V8EXPORT double Value() const;
1339 V8EXPORT static Local<Number> New(double value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001340 static inline Number* Cast(v8::Value* obj);
1341 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001342 V8EXPORT Number();
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001343 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001344};
1345
1346
1347/**
1348 * A JavaScript value representing a signed integer.
1349 */
Steve Block8defd9f2010-07-08 12:39:36 +01001350class Integer : public Number {
Steve Blocka7e24c12009-10-30 11:49:00 +00001351 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001352 V8EXPORT static Local<Integer> New(int32_t value);
1353 V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1354 V8EXPORT int64_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001355 static inline Integer* Cast(v8::Value* obj);
1356 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001357 V8EXPORT Integer();
1358 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001359};
1360
1361
1362/**
1363 * A JavaScript value representing a 32-bit signed integer.
1364 */
Steve Block8defd9f2010-07-08 12:39:36 +01001365class Int32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001366 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001367 V8EXPORT int32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001368 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001369 V8EXPORT Int32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001370};
1371
1372
1373/**
1374 * A JavaScript value representing a 32-bit unsigned integer.
1375 */
Steve Block8defd9f2010-07-08 12:39:36 +01001376class Uint32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001377 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001378 V8EXPORT uint32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001379 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001380 V8EXPORT Uint32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001381};
1382
1383
Steve Blocka7e24c12009-10-30 11:49:00 +00001384enum PropertyAttribute {
1385 None = 0,
1386 ReadOnly = 1 << 0,
1387 DontEnum = 1 << 1,
1388 DontDelete = 1 << 2
1389};
1390
Steve Block3ce2e202009-11-05 08:53:23 +00001391enum ExternalArrayType {
1392 kExternalByteArray = 1,
1393 kExternalUnsignedByteArray,
1394 kExternalShortArray,
1395 kExternalUnsignedShortArray,
1396 kExternalIntArray,
1397 kExternalUnsignedIntArray,
Steve Block44f0eee2011-05-26 01:26:41 +01001398 kExternalFloatArray,
Ben Murdoch257744e2011-11-30 15:57:28 +00001399 kExternalDoubleArray,
Steve Block44f0eee2011-05-26 01:26:41 +01001400 kExternalPixelArray
Steve Block3ce2e202009-11-05 08:53:23 +00001401};
1402
Steve Blocka7e24c12009-10-30 11:49:00 +00001403/**
Leon Clarkef7060e22010-06-03 12:02:55 +01001404 * Accessor[Getter|Setter] are used as callback functions when
1405 * setting|getting a particular property. See Object and ObjectTemplate's
1406 * method SetAccessor.
1407 */
1408typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1409 const AccessorInfo& info);
1410
1411
1412typedef void (*AccessorSetter)(Local<String> property,
1413 Local<Value> value,
1414 const AccessorInfo& info);
1415
1416
1417/**
1418 * Access control specifications.
1419 *
1420 * Some accessors should be accessible across contexts. These
1421 * accessors have an explicit access control parameter which specifies
1422 * the kind of cross-context access that should be allowed.
1423 *
1424 * Additionally, for security, accessors can prohibit overwriting by
1425 * accessors defined in JavaScript. For objects that have such
1426 * accessors either locally or in their prototype chain it is not
1427 * possible to overwrite the accessor by using __defineGetter__ or
1428 * __defineSetter__ from JavaScript code.
1429 */
1430enum AccessControl {
1431 DEFAULT = 0,
1432 ALL_CAN_READ = 1,
1433 ALL_CAN_WRITE = 1 << 1,
1434 PROHIBITS_OVERWRITING = 1 << 2
1435};
1436
1437
1438/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001439 * A JavaScript object (ECMA-262, 4.3.3)
1440 */
Steve Block8defd9f2010-07-08 12:39:36 +01001441class Object : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001442 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001443 V8EXPORT bool Set(Handle<Value> key,
1444 Handle<Value> value,
1445 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001446
Steve Block8defd9f2010-07-08 12:39:36 +01001447 V8EXPORT bool Set(uint32_t index,
1448 Handle<Value> value);
Steve Block6ded16b2010-05-10 14:33:55 +01001449
Steve Blocka7e24c12009-10-30 11:49:00 +00001450 // Sets a local property on this object bypassing interceptors and
1451 // overriding accessors or read-only properties.
1452 //
1453 // Note that if the object has an interceptor the property will be set
1454 // locally, but since the interceptor takes precedence the local property
1455 // will only be returned if the interceptor doesn't return a value.
1456 //
1457 // Note also that this only works for named properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001458 V8EXPORT bool ForceSet(Handle<Value> key,
1459 Handle<Value> value,
1460 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001461
Steve Block8defd9f2010-07-08 12:39:36 +01001462 V8EXPORT Local<Value> Get(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001463
Steve Block8defd9f2010-07-08 12:39:36 +01001464 V8EXPORT Local<Value> Get(uint32_t index);
Steve Block6ded16b2010-05-10 14:33:55 +01001465
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001466 /**
1467 * Gets the property attributes of a property which can be None or
1468 * any combination of ReadOnly, DontEnum and DontDelete. Returns
1469 * None when the property doesn't exist.
1470 */
1471 V8EXPORT PropertyAttribute GetPropertyAttributes(Handle<Value> key);
1472
Steve Blocka7e24c12009-10-30 11:49:00 +00001473 // TODO(1245389): Replace the type-specific versions of these
1474 // functions with generic ones that accept a Handle<Value> key.
Steve Block8defd9f2010-07-08 12:39:36 +01001475 V8EXPORT bool Has(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001476
Steve Block8defd9f2010-07-08 12:39:36 +01001477 V8EXPORT bool Delete(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001478
1479 // Delete a property on this object bypassing interceptors and
1480 // ignoring dont-delete attributes.
Steve Block8defd9f2010-07-08 12:39:36 +01001481 V8EXPORT bool ForceDelete(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001482
Steve Block8defd9f2010-07-08 12:39:36 +01001483 V8EXPORT bool Has(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001484
Steve Block8defd9f2010-07-08 12:39:36 +01001485 V8EXPORT bool Delete(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001486
Steve Block8defd9f2010-07-08 12:39:36 +01001487 V8EXPORT bool SetAccessor(Handle<String> name,
1488 AccessorGetter getter,
1489 AccessorSetter setter = 0,
1490 Handle<Value> data = Handle<Value>(),
1491 AccessControl settings = DEFAULT,
1492 PropertyAttribute attribute = None);
Leon Clarkef7060e22010-06-03 12:02:55 +01001493
Steve Blocka7e24c12009-10-30 11:49:00 +00001494 /**
1495 * Returns an array containing the names of the enumerable properties
1496 * of this object, including properties from prototype objects. The
1497 * array returned by this method contains the same values as would
1498 * be enumerated by a for-in statement over this object.
1499 */
Steve Block8defd9f2010-07-08 12:39:36 +01001500 V8EXPORT Local<Array> GetPropertyNames();
Steve Blocka7e24c12009-10-30 11:49:00 +00001501
1502 /**
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001503 * This function has the same functionality as GetPropertyNames but
1504 * the returned array doesn't contain the names of properties from
1505 * prototype objects.
1506 */
1507 V8EXPORT Local<Array> GetOwnPropertyNames();
1508
1509 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001510 * Get the prototype object. This does not skip objects marked to
1511 * be skipped by __proto__ and it does not consult the security
1512 * handler.
1513 */
Steve Block8defd9f2010-07-08 12:39:36 +01001514 V8EXPORT Local<Value> GetPrototype();
Steve Blocka7e24c12009-10-30 11:49:00 +00001515
1516 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00001517 * Set the prototype object. This does not skip objects marked to
1518 * be skipped by __proto__ and it does not consult the security
1519 * handler.
1520 */
Steve Block8defd9f2010-07-08 12:39:36 +01001521 V8EXPORT bool SetPrototype(Handle<Value> prototype);
Andrei Popescu402d9372010-02-26 13:31:12 +00001522
1523 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001524 * Finds an instance of the given function template in the prototype
1525 * chain.
1526 */
Steve Block8defd9f2010-07-08 12:39:36 +01001527 V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1528 Handle<FunctionTemplate> tmpl);
Steve Blocka7e24c12009-10-30 11:49:00 +00001529
1530 /**
1531 * Call builtin Object.prototype.toString on this object.
1532 * This is different from Value::ToString() that may call
1533 * user-defined toString function. This one does not.
1534 */
Steve Block8defd9f2010-07-08 12:39:36 +01001535 V8EXPORT Local<String> ObjectProtoToString();
Steve Blocka7e24c12009-10-30 11:49:00 +00001536
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08001537 /**
1538 * Returns the name of the function invoked as a constructor for this object.
1539 */
1540 V8EXPORT Local<String> GetConstructorName();
1541
Steve Blocka7e24c12009-10-30 11:49:00 +00001542 /** Gets the number of internal fields for this Object. */
Steve Block8defd9f2010-07-08 12:39:36 +01001543 V8EXPORT int InternalFieldCount();
Steve Blocka7e24c12009-10-30 11:49:00 +00001544 /** Gets the value in an internal field. */
1545 inline Local<Value> GetInternalField(int index);
1546 /** Sets the value in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001547 V8EXPORT void SetInternalField(int index, Handle<Value> value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001548
1549 /** Gets a native pointer from an internal field. */
1550 inline void* GetPointerFromInternalField(int index);
Steve Block3ce2e202009-11-05 08:53:23 +00001551
Steve Blocka7e24c12009-10-30 11:49:00 +00001552 /** Sets a native pointer in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001553 V8EXPORT void SetPointerInInternalField(int index, void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001554
1555 // Testers for local properties.
Ben Murdoch257744e2011-11-30 15:57:28 +00001556 V8EXPORT bool HasOwnProperty(Handle<String> key);
Steve Block8defd9f2010-07-08 12:39:36 +01001557 V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1558 V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1559 V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001560
1561 /**
1562 * If result.IsEmpty() no real property was located in the prototype chain.
1563 * This means interceptors in the prototype chain are not called.
1564 */
Steve Block8defd9f2010-07-08 12:39:36 +01001565 V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1566 Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001567
1568 /**
1569 * If result.IsEmpty() no real property was located on the object or
1570 * in the prototype chain.
1571 * This means interceptors in the prototype chain are not called.
1572 */
Steve Block8defd9f2010-07-08 12:39:36 +01001573 V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001574
1575 /** Tests for a named lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001576 V8EXPORT bool HasNamedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001577
1578 /** Tests for an index lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001579 V8EXPORT bool HasIndexedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001580
1581 /**
1582 * Turns on access check on the object if the object is an instance of
1583 * a template that has access check callbacks. If an object has no
1584 * access check info, the object cannot be accessed by anyone.
1585 */
Steve Block8defd9f2010-07-08 12:39:36 +01001586 V8EXPORT void TurnOnAccessCheck();
Steve Blocka7e24c12009-10-30 11:49:00 +00001587
1588 /**
Ben Murdoch257744e2011-11-30 15:57:28 +00001589 * Returns the identity hash for this object. The current implementation
1590 * uses a hidden property on the object to store the identity hash.
Steve Blocka7e24c12009-10-30 11:49:00 +00001591 *
1592 * The return value will never be 0. Also, it is not guaranteed to be
1593 * unique.
1594 */
Steve Block8defd9f2010-07-08 12:39:36 +01001595 V8EXPORT int GetIdentityHash();
Steve Blocka7e24c12009-10-30 11:49:00 +00001596
1597 /**
1598 * Access hidden properties on JavaScript objects. These properties are
1599 * hidden from the executing JavaScript and only accessible through the V8
1600 * C++ API. Hidden properties introduced by V8 internally (for example the
1601 * identity hash) are prefixed with "v8::".
1602 */
Steve Block8defd9f2010-07-08 12:39:36 +01001603 V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1604 V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1605 V8EXPORT bool DeleteHiddenValue(Handle<String> key);
Steve Block3ce2e202009-11-05 08:53:23 +00001606
Steve Blocka7e24c12009-10-30 11:49:00 +00001607 /**
1608 * Returns true if this is an instance of an api function (one
1609 * created from a function created from a function template) and has
1610 * been modified since it was created. Note that this method is
1611 * conservative and may return true for objects that haven't actually
1612 * been modified.
1613 */
Steve Block8defd9f2010-07-08 12:39:36 +01001614 V8EXPORT bool IsDirty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001615
1616 /**
1617 * Clone this object with a fast but shallow copy. Values will point
1618 * to the same values as the original object.
1619 */
Steve Block8defd9f2010-07-08 12:39:36 +01001620 V8EXPORT Local<Object> Clone();
Steve Blocka7e24c12009-10-30 11:49:00 +00001621
1622 /**
Ben Murdoch8b112d22011-06-08 16:22:53 +01001623 * Returns the context in which the object was created.
1624 */
1625 V8EXPORT Local<Context> CreationContext();
1626
1627 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001628 * Set the backing store of the indexed properties to be managed by the
1629 * embedding layer. Access to the indexed properties will follow the rules
1630 * spelled out in CanvasPixelArray.
1631 * Note: The embedding program still owns the data and needs to ensure that
1632 * the backing store is preserved while V8 has a reference.
1633 */
Steve Block8defd9f2010-07-08 12:39:36 +01001634 V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
Steve Block9fac8402011-05-12 15:51:54 +01001635 V8EXPORT bool HasIndexedPropertiesInPixelData();
1636 V8EXPORT uint8_t* GetIndexedPropertiesPixelData();
1637 V8EXPORT int GetIndexedPropertiesPixelDataLength();
Steve Blocka7e24c12009-10-30 11:49:00 +00001638
Steve Block3ce2e202009-11-05 08:53:23 +00001639 /**
1640 * Set the backing store of the indexed properties to be managed by the
1641 * embedding layer. Access to the indexed properties will follow the rules
1642 * spelled out for the CanvasArray subtypes in the WebGL specification.
1643 * Note: The embedding program still owns the data and needs to ensure that
1644 * the backing store is preserved while V8 has a reference.
1645 */
Steve Block8defd9f2010-07-08 12:39:36 +01001646 V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1647 void* data,
1648 ExternalArrayType array_type,
1649 int number_of_elements);
Steve Block9fac8402011-05-12 15:51:54 +01001650 V8EXPORT bool HasIndexedPropertiesInExternalArrayData();
1651 V8EXPORT void* GetIndexedPropertiesExternalArrayData();
1652 V8EXPORT ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1653 V8EXPORT int GetIndexedPropertiesExternalArrayDataLength();
Steve Block3ce2e202009-11-05 08:53:23 +00001654
Ben Murdoch257744e2011-11-30 15:57:28 +00001655 /**
1656 * Checks whether a callback is set by the
1657 * ObjectTemplate::SetCallAsFunctionHandler method.
1658 * When an Object is callable this method returns true.
1659 */
1660 V8EXPORT bool IsCallable();
1661
1662 /**
Ben Murdoch589d6972011-11-30 16:04:58 +00001663 * Call an Object as a function if a callback is set by the
Ben Murdoch257744e2011-11-30 15:57:28 +00001664 * ObjectTemplate::SetCallAsFunctionHandler method.
1665 */
1666 V8EXPORT Local<Value> CallAsFunction(Handle<Object> recv,
1667 int argc,
1668 Handle<Value> argv[]);
1669
1670 /**
1671 * Call an Object as a constructor if a callback is set by the
1672 * ObjectTemplate::SetCallAsFunctionHandler method.
1673 * Note: This method behaves like the Function::NewInstance method.
1674 */
1675 V8EXPORT Local<Value> CallAsConstructor(int argc,
1676 Handle<Value> argv[]);
1677
Steve Block8defd9f2010-07-08 12:39:36 +01001678 V8EXPORT static Local<Object> New();
Steve Blocka7e24c12009-10-30 11:49:00 +00001679 static inline Object* Cast(Value* obj);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001680
Steve Blocka7e24c12009-10-30 11:49:00 +00001681 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001682 V8EXPORT Object();
1683 V8EXPORT static void CheckCast(Value* obj);
1684 V8EXPORT Local<Value> CheckedGetInternalField(int index);
1685 V8EXPORT void* SlowGetPointerFromInternalField(int index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001686
1687 /**
1688 * If quick access to the internal field is possible this method
Steve Block3ce2e202009-11-05 08:53:23 +00001689 * returns the value. Otherwise an empty handle is returned.
Steve Blocka7e24c12009-10-30 11:49:00 +00001690 */
1691 inline Local<Value> UncheckedGetInternalField(int index);
1692};
1693
1694
1695/**
1696 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1697 */
Steve Block8defd9f2010-07-08 12:39:36 +01001698class Array : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001699 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001700 V8EXPORT uint32_t Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001701
1702 /**
1703 * Clones an element at index |index|. Returns an empty
1704 * handle if cloning fails (for any reason).
1705 */
Steve Block8defd9f2010-07-08 12:39:36 +01001706 V8EXPORT Local<Object> CloneElementAt(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001707
Steve Block44f0eee2011-05-26 01:26:41 +01001708 /**
1709 * Creates a JavaScript array with the given length. If the length
1710 * is negative the returned array will have length 0.
1711 */
Steve Block8defd9f2010-07-08 12:39:36 +01001712 V8EXPORT static Local<Array> New(int length = 0);
Steve Block44f0eee2011-05-26 01:26:41 +01001713
Steve Blocka7e24c12009-10-30 11:49:00 +00001714 static inline Array* Cast(Value* obj);
1715 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001716 V8EXPORT Array();
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001717 V8EXPORT static void CheckCast(Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001718};
1719
1720
1721/**
1722 * A JavaScript function object (ECMA-262, 15.3).
1723 */
Steve Block8defd9f2010-07-08 12:39:36 +01001724class Function : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001725 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001726 V8EXPORT Local<Object> NewInstance() const;
1727 V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1728 V8EXPORT Local<Value> Call(Handle<Object> recv,
1729 int argc,
1730 Handle<Value> argv[]);
1731 V8EXPORT void SetName(Handle<String> name);
1732 V8EXPORT Handle<Value> GetName() const;
Andrei Popescu402d9372010-02-26 13:31:12 +00001733
1734 /**
Ben Murdochc7cc0282012-03-05 14:35:55 +00001735 * Name inferred from variable or property assignment of this function.
1736 * Used to facilitate debugging and profiling of JavaScript code written
1737 * in an OO style, where many functions are anonymous but are assigned
1738 * to object properties.
1739 */
1740 V8EXPORT Handle<Value> GetInferredName() const;
1741
1742 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00001743 * Returns zero based line number of function body and
1744 * kLineOffsetNotFound if no information available.
1745 */
Steve Block8defd9f2010-07-08 12:39:36 +01001746 V8EXPORT int GetScriptLineNumber() const;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001747 /**
1748 * Returns zero based column number of function body and
1749 * kLineOffsetNotFound if no information available.
1750 */
1751 V8EXPORT int GetScriptColumnNumber() const;
1752 V8EXPORT Handle<Value> GetScriptId() const;
Steve Block8defd9f2010-07-08 12:39:36 +01001753 V8EXPORT ScriptOrigin GetScriptOrigin() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001754 static inline Function* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001755 V8EXPORT static const int kLineOffsetNotFound;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001756
Steve Blocka7e24c12009-10-30 11:49:00 +00001757 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001758 V8EXPORT Function();
1759 V8EXPORT static void CheckCast(Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001760};
1761
1762
1763/**
Ben Murdoch257744e2011-11-30 15:57:28 +00001764 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1765 */
1766class Date : public Object {
1767 public:
1768 V8EXPORT static Local<Value> New(double time);
1769
1770 /**
1771 * A specialization of Value::NumberValue that is more efficient
1772 * because we know the structure of this object.
1773 */
1774 V8EXPORT double NumberValue() const;
1775
1776 static inline Date* Cast(v8::Value* obj);
1777
1778 /**
1779 * Notification that the embedder has changed the time zone,
1780 * daylight savings time, or other date / time configuration
1781 * parameters. V8 keeps a cache of various values used for
1782 * date / time computation. This notification will reset
1783 * those cached values for the current context so that date /
1784 * time configuration changes would be reflected in the Date
1785 * object.
1786 *
1787 * This API should not be called more than needed as it will
1788 * negatively impact the performance of date operations.
1789 */
1790 V8EXPORT static void DateTimeConfigurationChangeNotification();
1791
1792 private:
1793 V8EXPORT static void CheckCast(v8::Value* obj);
1794};
1795
1796
1797/**
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001798 * A Number object (ECMA-262, 4.3.21).
1799 */
1800class NumberObject : public Object {
1801 public:
1802 V8EXPORT static Local<Value> New(double value);
1803
1804 /**
1805 * Returns the Number held by the object.
1806 */
1807 V8EXPORT double NumberValue() const;
1808
1809 static inline NumberObject* Cast(v8::Value* obj);
1810
1811 private:
1812 V8EXPORT static void CheckCast(v8::Value* obj);
1813};
1814
1815
1816/**
1817 * A Boolean object (ECMA-262, 4.3.15).
1818 */
1819class BooleanObject : public Object {
1820 public:
1821 V8EXPORT static Local<Value> New(bool value);
1822
1823 /**
1824 * Returns the Boolean held by the object.
1825 */
1826 V8EXPORT bool BooleanValue() const;
1827
1828 static inline BooleanObject* Cast(v8::Value* obj);
1829
1830 private:
1831 V8EXPORT static void CheckCast(v8::Value* obj);
1832};
1833
1834
1835/**
1836 * A String object (ECMA-262, 4.3.18).
1837 */
1838class StringObject : public Object {
1839 public:
1840 V8EXPORT static Local<Value> New(Handle<String> value);
1841
1842 /**
1843 * Returns the String held by the object.
1844 */
1845 V8EXPORT Local<String> StringValue() const;
1846
1847 static inline StringObject* Cast(v8::Value* obj);
1848
1849 private:
1850 V8EXPORT static void CheckCast(v8::Value* obj);
1851};
1852
1853
1854/**
Ben Murdoch257744e2011-11-30 15:57:28 +00001855 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1856 */
1857class RegExp : public Object {
1858 public:
1859 /**
1860 * Regular expression flag bits. They can be or'ed to enable a set
1861 * of flags.
1862 */
1863 enum Flags {
1864 kNone = 0,
1865 kGlobal = 1,
1866 kIgnoreCase = 2,
1867 kMultiline = 4
1868 };
1869
1870 /**
1871 * Creates a regular expression from the given pattern string and
1872 * the flags bit field. May throw a JavaScript exception as
1873 * described in ECMA-262, 15.10.4.1.
1874 *
1875 * For example,
1876 * RegExp::New(v8::String::New("foo"),
1877 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
1878 * is equivalent to evaluating "/foo/gm".
1879 */
1880 V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1881 Flags flags);
1882
1883 /**
1884 * Returns the value of the source property: a string representing
1885 * the regular expression.
1886 */
1887 V8EXPORT Local<String> GetSource() const;
1888
1889 /**
1890 * Returns the flags bit field.
1891 */
1892 V8EXPORT Flags GetFlags() const;
1893
1894 static inline RegExp* Cast(v8::Value* obj);
1895
1896 private:
1897 V8EXPORT static void CheckCast(v8::Value* obj);
1898};
1899
1900
1901/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001902 * A JavaScript value that wraps a C++ void*. This type of value is
1903 * mainly used to associate C++ data structures with JavaScript
1904 * objects.
1905 *
1906 * The Wrap function V8 will return the most optimal Value object wrapping the
1907 * C++ void*. The type of the value is not guaranteed to be an External object
1908 * and no assumptions about its type should be made. To access the wrapped
1909 * value Unwrap should be used, all other operations on that object will lead
1910 * to unpredictable results.
1911 */
Steve Block8defd9f2010-07-08 12:39:36 +01001912class External : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001913 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001914 V8EXPORT static Local<Value> Wrap(void* data);
Steve Blocka7e24c12009-10-30 11:49:00 +00001915 static inline void* Unwrap(Handle<Value> obj);
1916
Steve Block8defd9f2010-07-08 12:39:36 +01001917 V8EXPORT static Local<External> New(void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001918 static inline External* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001919 V8EXPORT void* Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001920 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001921 V8EXPORT External();
1922 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001923 static inline void* QuickUnwrap(Handle<v8::Value> obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001924 V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001925};
1926
1927
Ben Murdoch257744e2011-11-30 15:57:28 +00001928// --- Templates ---
Steve Blocka7e24c12009-10-30 11:49:00 +00001929
1930
1931/**
1932 * The superclass of object and function templates.
1933 */
1934class V8EXPORT Template : public Data {
1935 public:
1936 /** Adds a property to each instance created by this template.*/
1937 void Set(Handle<String> name, Handle<Data> value,
1938 PropertyAttribute attributes = None);
1939 inline void Set(const char* name, Handle<Data> value);
1940 private:
1941 Template();
1942
1943 friend class ObjectTemplate;
1944 friend class FunctionTemplate;
1945};
1946
1947
1948/**
1949 * The argument information given to function call callbacks. This
1950 * class provides access to information about the context of the call,
1951 * including the receiver, the number and values of arguments, and
1952 * the holder of the function.
1953 */
Steve Block8defd9f2010-07-08 12:39:36 +01001954class Arguments {
Steve Blocka7e24c12009-10-30 11:49:00 +00001955 public:
1956 inline int Length() const;
1957 inline Local<Value> operator[](int i) const;
1958 inline Local<Function> Callee() const;
1959 inline Local<Object> This() const;
1960 inline Local<Object> Holder() const;
1961 inline bool IsConstructCall() const;
1962 inline Local<Value> Data() const;
1963 private:
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001964 static const int kDataIndex = 0;
1965 static const int kCalleeIndex = -1;
1966 static const int kHolderIndex = -2;
1967
Steve Blocka7e24c12009-10-30 11:49:00 +00001968 friend class ImplementationUtilities;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001969 inline Arguments(internal::Object** implicit_args,
1970 internal::Object** values,
1971 int length,
1972 bool is_construct_call);
1973 internal::Object** implicit_args_;
1974 internal::Object** values_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001975 int length_;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001976 bool is_construct_call_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001977};
1978
1979
1980/**
1981 * The information passed to an accessor callback about the context
1982 * of the property access.
1983 */
1984class V8EXPORT AccessorInfo {
1985 public:
1986 inline AccessorInfo(internal::Object** args)
1987 : args_(args) { }
1988 inline Local<Value> Data() const;
1989 inline Local<Object> This() const;
1990 inline Local<Object> Holder() const;
1991 private:
1992 internal::Object** args_;
1993};
1994
1995
1996typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
1997
Steve Blocka7e24c12009-10-30 11:49:00 +00001998/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001999 * NamedProperty[Getter|Setter] are used as interceptors on object.
2000 * See ObjectTemplate::SetNamedPropertyHandler.
2001 */
2002typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
2003 const AccessorInfo& info);
2004
2005
2006/**
2007 * Returns the value if the setter intercepts the request.
2008 * Otherwise, returns an empty handle.
2009 */
2010typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
2011 Local<Value> value,
2012 const AccessorInfo& info);
2013
Steve Blocka7e24c12009-10-30 11:49:00 +00002014/**
2015 * Returns a non-empty handle if the interceptor intercepts the request.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002016 * The result is an integer encoding property attributes (like v8::None,
2017 * v8::DontEnum, etc.)
Steve Blocka7e24c12009-10-30 11:49:00 +00002018 */
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002019typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
2020 const AccessorInfo& info);
Steve Blocka7e24c12009-10-30 11:49:00 +00002021
2022
2023/**
2024 * Returns a non-empty handle if the deleter intercepts the request.
2025 * The return value is true if the property could be deleted and false
2026 * otherwise.
2027 */
2028typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
2029 const AccessorInfo& info);
2030
2031/**
2032 * Returns an array containing the names of the properties the named
2033 * property getter intercepts.
2034 */
2035typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
2036
2037
2038/**
2039 * Returns the value of the property if the getter intercepts the
2040 * request. Otherwise, returns an empty handle.
2041 */
2042typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
2043 const AccessorInfo& info);
2044
2045
2046/**
2047 * Returns the value if the setter intercepts the request.
2048 * Otherwise, returns an empty handle.
2049 */
2050typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
2051 Local<Value> value,
2052 const AccessorInfo& info);
2053
2054
2055/**
2056 * Returns a non-empty handle if the interceptor intercepts the request.
Iain Merrick75681382010-08-19 15:07:18 +01002057 * The result is an integer encoding property attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00002058 */
Iain Merrick75681382010-08-19 15:07:18 +01002059typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
Steve Blocka7e24c12009-10-30 11:49:00 +00002060 const AccessorInfo& info);
2061
2062/**
2063 * Returns a non-empty handle if the deleter intercepts the request.
2064 * The return value is true if the property could be deleted and false
2065 * otherwise.
2066 */
2067typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
2068 const AccessorInfo& info);
2069
2070/**
2071 * Returns an array containing the indices of the properties the
2072 * indexed property getter intercepts.
2073 */
2074typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
2075
2076
2077/**
Steve Blocka7e24c12009-10-30 11:49:00 +00002078 * Access type specification.
2079 */
2080enum AccessType {
2081 ACCESS_GET,
2082 ACCESS_SET,
2083 ACCESS_HAS,
2084 ACCESS_DELETE,
2085 ACCESS_KEYS
2086};
2087
2088
2089/**
2090 * Returns true if cross-context access should be allowed to the named
2091 * property with the given key on the host object.
2092 */
2093typedef bool (*NamedSecurityCallback)(Local<Object> host,
2094 Local<Value> key,
2095 AccessType type,
2096 Local<Value> data);
2097
2098
2099/**
2100 * Returns true if cross-context access should be allowed to the indexed
2101 * property with the given index on the host object.
2102 */
2103typedef bool (*IndexedSecurityCallback)(Local<Object> host,
2104 uint32_t index,
2105 AccessType type,
2106 Local<Value> data);
2107
2108
2109/**
2110 * A FunctionTemplate is used to create functions at runtime. There
2111 * can only be one function created from a FunctionTemplate in a
2112 * context. The lifetime of the created function is equal to the
2113 * lifetime of the context. So in case the embedder needs to create
2114 * temporary functions that can be collected using Scripts is
2115 * preferred.
2116 *
2117 * A FunctionTemplate can have properties, these properties are added to the
2118 * function object when it is created.
2119 *
2120 * A FunctionTemplate has a corresponding instance template which is
2121 * used to create object instances when the function is used as a
2122 * constructor. Properties added to the instance template are added to
2123 * each object instance.
2124 *
2125 * A FunctionTemplate can have a prototype template. The prototype template
2126 * is used to create the prototype object of the function.
2127 *
2128 * The following example shows how to use a FunctionTemplate:
2129 *
2130 * \code
2131 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
2132 * t->Set("func_property", v8::Number::New(1));
2133 *
2134 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
2135 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
2136 * proto_t->Set("proto_const", v8::Number::New(2));
2137 *
2138 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
2139 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
2140 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
2141 * instance_t->Set("instance_property", Number::New(3));
2142 *
2143 * v8::Local<v8::Function> function = t->GetFunction();
2144 * v8::Local<v8::Object> instance = function->NewInstance();
2145 * \endcode
2146 *
2147 * Let's use "function" as the JS variable name of the function object
2148 * and "instance" for the instance object created above. The function
2149 * and the instance will have the following properties:
2150 *
2151 * \code
2152 * func_property in function == true;
2153 * function.func_property == 1;
2154 *
2155 * function.prototype.proto_method() invokes 'InvokeCallback'
2156 * function.prototype.proto_const == 2;
2157 *
2158 * instance instanceof function == true;
2159 * instance.instance_accessor calls 'InstanceAccessorCallback'
2160 * instance.instance_property == 3;
2161 * \endcode
2162 *
2163 * A FunctionTemplate can inherit from another one by calling the
2164 * FunctionTemplate::Inherit method. The following graph illustrates
2165 * the semantics of inheritance:
2166 *
2167 * \code
2168 * FunctionTemplate Parent -> Parent() . prototype -> { }
2169 * ^ ^
2170 * | Inherit(Parent) | .__proto__
2171 * | |
2172 * FunctionTemplate Child -> Child() . prototype -> { }
2173 * \endcode
2174 *
2175 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
2176 * object of the Child() function has __proto__ pointing to the
2177 * Parent() function's prototype object. An instance of the Child
2178 * function has all properties on Parent's instance templates.
2179 *
2180 * Let Parent be the FunctionTemplate initialized in the previous
2181 * section and create a Child FunctionTemplate by:
2182 *
2183 * \code
2184 * Local<FunctionTemplate> parent = t;
2185 * Local<FunctionTemplate> child = FunctionTemplate::New();
2186 * child->Inherit(parent);
2187 *
2188 * Local<Function> child_function = child->GetFunction();
2189 * Local<Object> child_instance = child_function->NewInstance();
2190 * \endcode
2191 *
2192 * The Child function and Child instance will have the following
2193 * properties:
2194 *
2195 * \code
2196 * child_func.prototype.__proto__ == function.prototype;
2197 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
2198 * child_instance.instance_property == 3;
2199 * \endcode
2200 */
2201class V8EXPORT FunctionTemplate : public Template {
2202 public:
2203 /** Creates a function template.*/
2204 static Local<FunctionTemplate> New(
2205 InvocationCallback callback = 0,
2206 Handle<Value> data = Handle<Value>(),
2207 Handle<Signature> signature = Handle<Signature>());
2208 /** Returns the unique function instance in the current execution context.*/
2209 Local<Function> GetFunction();
2210
2211 /**
2212 * Set the call-handler callback for a FunctionTemplate. This
2213 * callback is called whenever the function created from this
2214 * FunctionTemplate is called.
2215 */
2216 void SetCallHandler(InvocationCallback callback,
2217 Handle<Value> data = Handle<Value>());
2218
2219 /** Get the InstanceTemplate. */
2220 Local<ObjectTemplate> InstanceTemplate();
2221
2222 /** Causes the function template to inherit from a parent function template.*/
2223 void Inherit(Handle<FunctionTemplate> parent);
2224
2225 /**
2226 * A PrototypeTemplate is the template used to create the prototype object
2227 * of the function created by this template.
2228 */
2229 Local<ObjectTemplate> PrototypeTemplate();
2230
2231
2232 /**
2233 * Set the class name of the FunctionTemplate. This is used for
2234 * printing objects created with the function created from the
2235 * FunctionTemplate as its constructor.
2236 */
2237 void SetClassName(Handle<String> name);
2238
2239 /**
2240 * Determines whether the __proto__ accessor ignores instances of
2241 * the function template. If instances of the function template are
2242 * ignored, __proto__ skips all instances and instead returns the
2243 * next object in the prototype chain.
2244 *
2245 * Call with a value of true to make the __proto__ accessor ignore
2246 * instances of the function template. Call with a value of false
2247 * to make the __proto__ accessor not ignore instances of the
2248 * function template. By default, instances of a function template
2249 * are not ignored.
2250 */
2251 void SetHiddenPrototype(bool value);
2252
2253 /**
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002254 * Sets the ReadOnly flag in the attributes of the 'prototype' property
2255 * of functions created from this FunctionTemplate to true.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002256 */
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002257 void ReadOnlyPrototype();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002258
2259 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002260 * Returns true if the given object is an instance of this function
2261 * template.
2262 */
2263 bool HasInstance(Handle<Value> object);
2264
2265 private:
2266 FunctionTemplate();
2267 void AddInstancePropertyAccessor(Handle<String> name,
2268 AccessorGetter getter,
2269 AccessorSetter setter,
2270 Handle<Value> data,
2271 AccessControl settings,
2272 PropertyAttribute attributes);
2273 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2274 NamedPropertySetter setter,
2275 NamedPropertyQuery query,
2276 NamedPropertyDeleter remover,
2277 NamedPropertyEnumerator enumerator,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002278 Handle<Value> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00002279 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2280 IndexedPropertySetter setter,
2281 IndexedPropertyQuery query,
2282 IndexedPropertyDeleter remover,
2283 IndexedPropertyEnumerator enumerator,
2284 Handle<Value> data);
2285 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2286 Handle<Value> data);
2287
2288 friend class Context;
2289 friend class ObjectTemplate;
2290};
2291
2292
2293/**
2294 * An ObjectTemplate is used to create objects at runtime.
2295 *
2296 * Properties added to an ObjectTemplate are added to each object
2297 * created from the ObjectTemplate.
2298 */
2299class V8EXPORT ObjectTemplate : public Template {
2300 public:
2301 /** Creates an ObjectTemplate. */
2302 static Local<ObjectTemplate> New();
2303
2304 /** Creates a new instance of this template.*/
2305 Local<Object> NewInstance();
2306
2307 /**
2308 * Sets an accessor on the object template.
2309 *
2310 * Whenever the property with the given name is accessed on objects
2311 * created from this ObjectTemplate the getter and setter callbacks
2312 * are called instead of getting and setting the property directly
2313 * on the JavaScript object.
2314 *
2315 * \param name The name of the property for which an accessor is added.
2316 * \param getter The callback to invoke when getting the property.
2317 * \param setter The callback to invoke when setting the property.
2318 * \param data A piece of data that will be passed to the getter and setter
2319 * callbacks whenever they are invoked.
2320 * \param settings Access control settings for the accessor. This is a bit
2321 * field consisting of one of more of
2322 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2323 * The default is to not allow cross-context access.
2324 * ALL_CAN_READ means that all cross-context reads are allowed.
2325 * ALL_CAN_WRITE means that all cross-context writes are allowed.
2326 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2327 * cross-context access.
2328 * \param attribute The attributes of the property for which an accessor
2329 * is added.
2330 */
2331 void SetAccessor(Handle<String> name,
2332 AccessorGetter getter,
2333 AccessorSetter setter = 0,
2334 Handle<Value> data = Handle<Value>(),
2335 AccessControl settings = DEFAULT,
2336 PropertyAttribute attribute = None);
2337
2338 /**
2339 * Sets a named property handler on the object template.
2340 *
2341 * Whenever a named property is accessed on objects created from
2342 * this object template, the provided callback is invoked instead of
2343 * accessing the property directly on the JavaScript object.
2344 *
2345 * \param getter The callback to invoke when getting a property.
2346 * \param setter The callback to invoke when setting a property.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002347 * \param query The callback to invoke to check if a property is present,
2348 * and if present, get its attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00002349 * \param deleter The callback to invoke when deleting a property.
2350 * \param enumerator The callback to invoke to enumerate all the named
2351 * properties of an object.
2352 * \param data A piece of data that will be passed to the callbacks
2353 * whenever they are invoked.
2354 */
2355 void SetNamedPropertyHandler(NamedPropertyGetter getter,
2356 NamedPropertySetter setter = 0,
2357 NamedPropertyQuery query = 0,
2358 NamedPropertyDeleter deleter = 0,
2359 NamedPropertyEnumerator enumerator = 0,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002360 Handle<Value> data = Handle<Value>());
Steve Blocka7e24c12009-10-30 11:49:00 +00002361
2362 /**
2363 * Sets an indexed property handler on the object template.
2364 *
2365 * Whenever an indexed property is accessed on objects created from
2366 * this object template, the provided callback is invoked instead of
2367 * accessing the property directly on the JavaScript object.
2368 *
2369 * \param getter The callback to invoke when getting a property.
2370 * \param setter The callback to invoke when setting a property.
Ben Murdoch257744e2011-11-30 15:57:28 +00002371 * \param query The callback to invoke to check if an object has a property.
Steve Blocka7e24c12009-10-30 11:49:00 +00002372 * \param deleter The callback to invoke when deleting a property.
2373 * \param enumerator The callback to invoke to enumerate all the indexed
2374 * properties of an object.
2375 * \param data A piece of data that will be passed to the callbacks
2376 * whenever they are invoked.
2377 */
2378 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2379 IndexedPropertySetter setter = 0,
2380 IndexedPropertyQuery query = 0,
2381 IndexedPropertyDeleter deleter = 0,
2382 IndexedPropertyEnumerator enumerator = 0,
2383 Handle<Value> data = Handle<Value>());
Iain Merrick75681382010-08-19 15:07:18 +01002384
Steve Blocka7e24c12009-10-30 11:49:00 +00002385 /**
2386 * Sets the callback to be used when calling instances created from
2387 * this template as a function. If no callback is set, instances
2388 * behave like normal JavaScript objects that cannot be called as a
2389 * function.
2390 */
2391 void SetCallAsFunctionHandler(InvocationCallback callback,
2392 Handle<Value> data = Handle<Value>());
2393
2394 /**
2395 * Mark object instances of the template as undetectable.
2396 *
2397 * In many ways, undetectable objects behave as though they are not
2398 * there. They behave like 'undefined' in conditionals and when
2399 * printed. However, properties can be accessed and called as on
2400 * normal objects.
2401 */
2402 void MarkAsUndetectable();
2403
2404 /**
2405 * Sets access check callbacks on the object template.
2406 *
2407 * When accessing properties on instances of this object template,
2408 * the access check callback will be called to determine whether or
2409 * not to allow cross-context access to the properties.
2410 * The last parameter specifies whether access checks are turned
2411 * on by default on instances. If access checks are off by default,
2412 * they can be turned on on individual instances by calling
2413 * Object::TurnOnAccessCheck().
2414 */
2415 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2416 IndexedSecurityCallback indexed_handler,
2417 Handle<Value> data = Handle<Value>(),
2418 bool turned_on_by_default = true);
2419
2420 /**
2421 * Gets the number of internal fields for objects generated from
2422 * this template.
2423 */
2424 int InternalFieldCount();
2425
2426 /**
2427 * Sets the number of internal fields for objects generated from
2428 * this template.
2429 */
2430 void SetInternalFieldCount(int value);
2431
2432 private:
2433 ObjectTemplate();
2434 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2435 friend class FunctionTemplate;
2436};
2437
2438
2439/**
2440 * A Signature specifies which receivers and arguments a function can
2441 * legally be called with.
2442 */
2443class V8EXPORT Signature : public Data {
2444 public:
2445 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2446 Handle<FunctionTemplate>(),
2447 int argc = 0,
2448 Handle<FunctionTemplate> argv[] = 0);
2449 private:
2450 Signature();
2451};
2452
2453
2454/**
2455 * A utility for determining the type of objects based on the template
2456 * they were constructed from.
2457 */
2458class V8EXPORT TypeSwitch : public Data {
2459 public:
2460 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2461 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2462 int match(Handle<Value> value);
2463 private:
2464 TypeSwitch();
2465};
2466
2467
Ben Murdoch257744e2011-11-30 15:57:28 +00002468// --- Extensions ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002469
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002470class V8EXPORT ExternalAsciiStringResourceImpl
2471 : public String::ExternalAsciiStringResource {
2472 public:
2473 ExternalAsciiStringResourceImpl() : data_(0), length_(0) {}
2474 ExternalAsciiStringResourceImpl(const char* data, size_t length)
2475 : data_(data), length_(length) {}
2476 const char* data() const { return data_; }
2477 size_t length() const { return length_; }
2478
2479 private:
2480 const char* data_;
2481 size_t length_;
2482};
Steve Blocka7e24c12009-10-30 11:49:00 +00002483
2484/**
2485 * Ignore
2486 */
2487class V8EXPORT Extension { // NOLINT
2488 public:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002489 // Note that the strings passed into this constructor must live as long
2490 // as the Extension itself.
Steve Blocka7e24c12009-10-30 11:49:00 +00002491 Extension(const char* name,
2492 const char* source = 0,
2493 int dep_count = 0,
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002494 const char** deps = 0,
2495 int source_length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00002496 virtual ~Extension() { }
2497 virtual v8::Handle<v8::FunctionTemplate>
2498 GetNativeFunction(v8::Handle<v8::String> name) {
2499 return v8::Handle<v8::FunctionTemplate>();
2500 }
2501
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002502 const char* name() const { return name_; }
2503 size_t source_length() const { return source_length_; }
2504 const String::ExternalAsciiStringResource* source() const {
2505 return &source_; }
Steve Blocka7e24c12009-10-30 11:49:00 +00002506 int dependency_count() { return dep_count_; }
2507 const char** dependencies() { return deps_; }
2508 void set_auto_enable(bool value) { auto_enable_ = value; }
2509 bool auto_enable() { return auto_enable_; }
2510
2511 private:
2512 const char* name_;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002513 size_t source_length_; // expected to initialize before source_
2514 ExternalAsciiStringResourceImpl source_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002515 int dep_count_;
2516 const char** deps_;
2517 bool auto_enable_;
2518
2519 // Disallow copying and assigning.
2520 Extension(const Extension&);
2521 void operator=(const Extension&);
2522};
2523
2524
2525void V8EXPORT RegisterExtension(Extension* extension);
2526
2527
2528/**
2529 * Ignore
2530 */
2531class V8EXPORT DeclareExtension {
2532 public:
2533 inline DeclareExtension(Extension* extension) {
2534 RegisterExtension(extension);
2535 }
2536};
2537
2538
Ben Murdoch257744e2011-11-30 15:57:28 +00002539// --- Statics ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002540
2541
2542Handle<Primitive> V8EXPORT Undefined();
2543Handle<Primitive> V8EXPORT Null();
2544Handle<Boolean> V8EXPORT True();
2545Handle<Boolean> V8EXPORT False();
2546
2547
2548/**
2549 * A set of constraints that specifies the limits of the runtime's memory use.
2550 * You must set the heap size before initializing the VM - the size cannot be
2551 * adjusted after the VM is initialized.
2552 *
2553 * If you are using threads then you should hold the V8::Locker lock while
2554 * setting the stack limit and you must set a non-default stack limit separately
2555 * for each thread.
2556 */
2557class V8EXPORT ResourceConstraints {
2558 public:
2559 ResourceConstraints();
2560 int max_young_space_size() const { return max_young_space_size_; }
2561 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2562 int max_old_space_size() const { return max_old_space_size_; }
2563 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
Russell Brenner90bac252010-11-18 13:33:46 -08002564 int max_executable_size() { return max_executable_size_; }
2565 void set_max_executable_size(int value) { max_executable_size_ = value; }
Steve Blocka7e24c12009-10-30 11:49:00 +00002566 uint32_t* stack_limit() const { return stack_limit_; }
2567 // Sets an address beyond which the VM's stack may not grow.
2568 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2569 private:
2570 int max_young_space_size_;
2571 int max_old_space_size_;
Russell Brenner90bac252010-11-18 13:33:46 -08002572 int max_executable_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002573 uint32_t* stack_limit_;
2574};
2575
2576
Kristian Monsen25f61362010-05-21 11:50:48 +01002577bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
Steve Blocka7e24c12009-10-30 11:49:00 +00002578
2579
Ben Murdoch257744e2011-11-30 15:57:28 +00002580// --- Exceptions ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002581
2582
2583typedef void (*FatalErrorCallback)(const char* location, const char* message);
2584
2585
2586typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2587
2588
2589/**
2590 * Schedules an exception to be thrown when returning to JavaScript. When an
2591 * exception has been scheduled it is illegal to invoke any JavaScript
2592 * operation; the caller must return immediately and only after the exception
2593 * has been handled does it become legal to invoke JavaScript operations.
2594 */
2595Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2596
2597/**
2598 * Create new error objects by calling the corresponding error object
2599 * constructor with the message.
2600 */
2601class V8EXPORT Exception {
2602 public:
2603 static Local<Value> RangeError(Handle<String> message);
2604 static Local<Value> ReferenceError(Handle<String> message);
2605 static Local<Value> SyntaxError(Handle<String> message);
2606 static Local<Value> TypeError(Handle<String> message);
2607 static Local<Value> Error(Handle<String> message);
2608};
2609
2610
Ben Murdoch257744e2011-11-30 15:57:28 +00002611// --- Counters Callbacks ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002612
2613typedef int* (*CounterLookupCallback)(const char* name);
2614
2615typedef void* (*CreateHistogramCallback)(const char* name,
2616 int min,
2617 int max,
2618 size_t buckets);
2619
2620typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2621
Ben Murdoch257744e2011-11-30 15:57:28 +00002622// --- Memory Allocation Callback ---
Iain Merrick9ac36c92010-09-13 15:29:50 +01002623 enum ObjectSpace {
2624 kObjectSpaceNewSpace = 1 << 0,
2625 kObjectSpaceOldPointerSpace = 1 << 1,
2626 kObjectSpaceOldDataSpace = 1 << 2,
2627 kObjectSpaceCodeSpace = 1 << 3,
2628 kObjectSpaceMapSpace = 1 << 4,
2629 kObjectSpaceLoSpace = 1 << 5,
2630
2631 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2632 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2633 kObjectSpaceLoSpace
2634 };
2635
2636 enum AllocationAction {
2637 kAllocationActionAllocate = 1 << 0,
2638 kAllocationActionFree = 1 << 1,
2639 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2640 };
2641
2642typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2643 AllocationAction action,
2644 int size);
2645
Ben Murdochc7cc0282012-03-05 14:35:55 +00002646// --- Leave Script Callback ---
2647typedef void (*CallCompletedCallback)();
2648
Ben Murdoch257744e2011-11-30 15:57:28 +00002649// --- Failed Access Check Callback ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002650typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2651 AccessType type,
2652 Local<Value> data);
2653
Ben Murdoch257744e2011-11-30 15:57:28 +00002654// --- AllowCodeGenerationFromStrings callbacks ---
2655
2656/**
2657 * Callback to check if code generation from strings is allowed. See
2658 * Context::AllowCodeGenerationFromStrings.
2659 */
2660typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
2661
2662// --- Garbage Collection Callbacks ---
Steve Blocka7e24c12009-10-30 11:49:00 +00002663
2664/**
Steve Block6ded16b2010-05-10 14:33:55 +01002665 * Applications can register callback functions which will be called
2666 * before and after a garbage collection. Allocations are not
2667 * allowed in the callback functions, you therefore cannot manipulate
Steve Blocka7e24c12009-10-30 11:49:00 +00002668 * objects (set or delete properties for example) since it is possible
2669 * such operations will result in the allocation of objects.
2670 */
Steve Block6ded16b2010-05-10 14:33:55 +01002671enum GCType {
2672 kGCTypeScavenge = 1 << 0,
2673 kGCTypeMarkSweepCompact = 1 << 1,
2674 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2675};
2676
2677enum GCCallbackFlags {
2678 kNoGCCallbackFlags = 0,
2679 kGCCallbackFlagCompacted = 1 << 0
2680};
2681
2682typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2683typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2684
Steve Blocka7e24c12009-10-30 11:49:00 +00002685typedef void (*GCCallback)();
2686
2687
Steve Blocka7e24c12009-10-30 11:49:00 +00002688/**
Steve Block3ce2e202009-11-05 08:53:23 +00002689 * Collection of V8 heap information.
2690 *
2691 * Instances of this class can be passed to v8::V8::HeapStatistics to
2692 * get heap statistics from V8.
2693 */
2694class V8EXPORT HeapStatistics {
2695 public:
2696 HeapStatistics();
2697 size_t total_heap_size() { return total_heap_size_; }
Russell Brenner90bac252010-11-18 13:33:46 -08002698 size_t total_heap_size_executable() { return total_heap_size_executable_; }
Steve Block3ce2e202009-11-05 08:53:23 +00002699 size_t used_heap_size() { return used_heap_size_; }
Ben Murdochb8e0da22011-05-16 14:20:40 +01002700 size_t heap_size_limit() { return heap_size_limit_; }
Steve Block3ce2e202009-11-05 08:53:23 +00002701
2702 private:
2703 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
Russell Brenner90bac252010-11-18 13:33:46 -08002704 void set_total_heap_size_executable(size_t size) {
2705 total_heap_size_executable_ = size;
2706 }
Steve Block3ce2e202009-11-05 08:53:23 +00002707 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
Ben Murdochb8e0da22011-05-16 14:20:40 +01002708 void set_heap_size_limit(size_t size) { heap_size_limit_ = size; }
Steve Block3ce2e202009-11-05 08:53:23 +00002709
2710 size_t total_heap_size_;
Russell Brenner90bac252010-11-18 13:33:46 -08002711 size_t total_heap_size_executable_;
Steve Block3ce2e202009-11-05 08:53:23 +00002712 size_t used_heap_size_;
Ben Murdochb8e0da22011-05-16 14:20:40 +01002713 size_t heap_size_limit_;
Steve Block3ce2e202009-11-05 08:53:23 +00002714
2715 friend class V8;
2716};
2717
2718
Steve Block44f0eee2011-05-26 01:26:41 +01002719class RetainedObjectInfo;
2720
2721/**
2722 * Isolate represents an isolated instance of the V8 engine. V8
2723 * isolates have completely separate states. Objects from one isolate
2724 * must not be used in other isolates. When V8 is initialized a
2725 * default isolate is implicitly created and entered. The embedder
2726 * can create additional isolates and use them in parallel in multiple
2727 * threads. An isolate can be entered by at most one thread at any
Ben Murdochc7cc0282012-03-05 14:35:55 +00002728 * given time. The Locker/Unlocker API must be used to synchronize.
Steve Block44f0eee2011-05-26 01:26:41 +01002729 */
2730class V8EXPORT Isolate {
2731 public:
2732 /**
2733 * Stack-allocated class which sets the isolate for all operations
2734 * executed within a local scope.
2735 */
2736 class V8EXPORT Scope {
2737 public:
2738 explicit Scope(Isolate* isolate) : isolate_(isolate) {
2739 isolate->Enter();
2740 }
2741
2742 ~Scope() { isolate_->Exit(); }
2743
2744 private:
2745 Isolate* const isolate_;
2746
2747 // Prevent copying of Scope objects.
2748 Scope(const Scope&);
2749 Scope& operator=(const Scope&);
2750 };
2751
2752 /**
2753 * Creates a new isolate. Does not change the currently entered
2754 * isolate.
2755 *
2756 * When an isolate is no longer used its resources should be freed
2757 * by calling Dispose(). Using the delete operator is not allowed.
2758 */
2759 static Isolate* New();
2760
2761 /**
2762 * Returns the entered isolate for the current thread or NULL in
2763 * case there is no current isolate.
2764 */
2765 static Isolate* GetCurrent();
2766
2767 /**
2768 * Methods below this point require holding a lock (using Locker) in
2769 * a multi-threaded environment.
2770 */
2771
2772 /**
2773 * Sets this isolate as the entered one for the current thread.
2774 * Saves the previously entered one (if any), so that it can be
2775 * restored when exiting. Re-entering an isolate is allowed.
2776 */
2777 void Enter();
2778
2779 /**
2780 * Exits this isolate by restoring the previously entered one in the
2781 * current thread. The isolate may still stay the same, if it was
2782 * entered more than once.
2783 *
2784 * Requires: this == Isolate::GetCurrent().
2785 */
2786 void Exit();
2787
2788 /**
2789 * Disposes the isolate. The isolate must not be entered by any
2790 * thread to be disposable.
2791 */
2792 void Dispose();
2793
Ben Murdoch257744e2011-11-30 15:57:28 +00002794 /**
2795 * Associate embedder-specific data with the isolate
2796 */
2797 void SetData(void* data);
2798
2799 /**
2800 * Retrive embedder-specific data from the isolate.
2801 * Returns NULL if SetData has never been called.
2802 */
2803 void* GetData();
2804
Steve Block44f0eee2011-05-26 01:26:41 +01002805 private:
Steve Block44f0eee2011-05-26 01:26:41 +01002806 Isolate();
2807 Isolate(const Isolate&);
2808 ~Isolate();
2809 Isolate& operator=(const Isolate&);
2810 void* operator new(size_t size);
2811 void operator delete(void*, size_t);
2812};
2813
2814
Ben Murdoch257744e2011-11-30 15:57:28 +00002815class StartupData {
2816 public:
2817 enum CompressionAlgorithm {
2818 kUncompressed,
2819 kBZip2
2820 };
2821
2822 const char* data;
2823 int compressed_size;
2824 int raw_size;
2825};
2826
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002827
2828/**
2829 * A helper class for driving V8 startup data decompression. It is based on
2830 * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
2831 * for an embedder to use this class, instead, API functions can be used
2832 * directly.
2833 *
2834 * For an example of the class usage, see the "shell.cc" sample application.
2835 */
2836class V8EXPORT StartupDataDecompressor { // NOLINT
2837 public:
2838 StartupDataDecompressor();
2839 virtual ~StartupDataDecompressor();
2840 int Decompress();
2841
2842 protected:
2843 virtual int DecompressData(char* raw_data,
2844 int* raw_data_size,
2845 const char* compressed_data,
2846 int compressed_data_size) = 0;
2847
2848 private:
2849 char** raw_data;
2850};
2851
2852
2853/**
2854 * EntropySource is used as a callback function when v8 needs a source
2855 * of entropy.
2856 */
2857typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
2858
Ben Murdochc7cc0282012-03-05 14:35:55 +00002859
2860/**
2861 * Interface for iterating though all external resources in the heap.
2862 */
2863class V8EXPORT ExternalResourceVisitor { // NOLINT
2864 public:
2865 virtual ~ExternalResourceVisitor() {}
2866 virtual void VisitExternalString(Handle<String> string) {}
2867};
2868
2869
Steve Block3ce2e202009-11-05 08:53:23 +00002870/**
Steve Blocka7e24c12009-10-30 11:49:00 +00002871 * Container class for static utility functions.
2872 */
2873class V8EXPORT V8 {
2874 public:
2875 /** Set the callback to invoke in case of fatal errors. */
2876 static void SetFatalErrorHandler(FatalErrorCallback that);
2877
2878 /**
Ben Murdoch257744e2011-11-30 15:57:28 +00002879 * Set the callback to invoke to check if code generation from
2880 * strings should be allowed.
2881 */
2882 static void SetAllowCodeGenerationFromStringsCallback(
2883 AllowCodeGenerationFromStringsCallback that);
2884
2885 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002886 * Ignore out-of-memory exceptions.
2887 *
2888 * V8 running out of memory is treated as a fatal error by default.
2889 * This means that the fatal error handler is called and that V8 is
2890 * terminated.
2891 *
Ben Murdoch257744e2011-11-30 15:57:28 +00002892 * IgnoreOutOfMemoryException can be used to not treat an
Steve Blocka7e24c12009-10-30 11:49:00 +00002893 * out-of-memory situation as a fatal error. This way, the contexts
2894 * that did not cause the out of memory problem might be able to
2895 * continue execution.
2896 */
2897 static void IgnoreOutOfMemoryException();
2898
2899 /**
2900 * Check if V8 is dead and therefore unusable. This is the case after
2901 * fatal errors such as out-of-memory situations.
2902 */
2903 static bool IsDead();
2904
2905 /**
Ben Murdoch257744e2011-11-30 15:57:28 +00002906 * The following 4 functions are to be used when V8 is built with
2907 * the 'compress_startup_data' flag enabled. In this case, the
2908 * embedder must decompress startup data prior to initializing V8.
2909 *
2910 * This is how interaction with V8 should look like:
2911 * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
2912 * v8::StartupData* compressed_data =
2913 * new v8::StartupData[compressed_data_count];
2914 * v8::V8::GetCompressedStartupData(compressed_data);
2915 * ... decompress data (compressed_data can be updated in-place) ...
2916 * v8::V8::SetDecompressedStartupData(compressed_data);
2917 * ... now V8 can be initialized
2918 * ... make sure the decompressed data stays valid until V8 shutdown
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002919 *
2920 * A helper class StartupDataDecompressor is provided. It implements
2921 * the protocol of the interaction described above, and can be used in
2922 * most cases instead of calling these API functions directly.
Ben Murdoch257744e2011-11-30 15:57:28 +00002923 */
2924 static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
2925 static int GetCompressedStartupDataCount();
2926 static void GetCompressedStartupData(StartupData* compressed_data);
2927 static void SetDecompressedStartupData(StartupData* decompressed_data);
2928
2929 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002930 * Adds a message listener.
2931 *
Ben Murdoch257744e2011-11-30 15:57:28 +00002932 * The same message listener can be added more than once and in that
Steve Blocka7e24c12009-10-30 11:49:00 +00002933 * case it will be called more than once for each message.
2934 */
2935 static bool AddMessageListener(MessageCallback that,
2936 Handle<Value> data = Handle<Value>());
2937
2938 /**
2939 * Remove all message listeners from the specified callback function.
2940 */
2941 static void RemoveMessageListeners(MessageCallback that);
2942
2943 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002944 * Tells V8 to capture current stack trace when uncaught exception occurs
2945 * and report it to the message listeners. The option is off by default.
2946 */
2947 static void SetCaptureStackTraceForUncaughtExceptions(
2948 bool capture,
2949 int frame_limit = 10,
2950 StackTrace::StackTraceOptions options = StackTrace::kOverview);
2951
2952 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002953 * Sets V8 flags from a string.
2954 */
2955 static void SetFlagsFromString(const char* str, int length);
2956
2957 /**
2958 * Sets V8 flags from the command line.
2959 */
2960 static void SetFlagsFromCommandLine(int* argc,
2961 char** argv,
2962 bool remove_flags);
2963
2964 /** Get the version string. */
2965 static const char* GetVersion();
2966
2967 /**
2968 * Enables the host application to provide a mechanism for recording
2969 * statistics counters.
2970 */
2971 static void SetCounterFunction(CounterLookupCallback);
2972
2973 /**
2974 * Enables the host application to provide a mechanism for recording
2975 * histograms. The CreateHistogram function returns a
2976 * histogram which will later be passed to the AddHistogramSample
2977 * function.
2978 */
2979 static void SetCreateHistogramFunction(CreateHistogramCallback);
2980 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
2981
2982 /**
2983 * Enables the computation of a sliding window of states. The sliding
2984 * window information is recorded in statistics counters.
2985 */
2986 static void EnableSlidingStateWindow();
2987
2988 /** Callback function for reporting failed access checks.*/
2989 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
2990
2991 /**
2992 * Enables the host application to receive a notification before a
Steve Block6ded16b2010-05-10 14:33:55 +01002993 * garbage collection. Allocations are not allowed in the
2994 * callback function, you therefore cannot manipulate objects (set
2995 * or delete properties for example) since it is possible such
2996 * operations will result in the allocation of objects. It is possible
2997 * to specify the GCType filter for your callback. But it is not possible to
2998 * register the same callback function two times with different
2999 * GCType filters.
3000 */
3001 static void AddGCPrologueCallback(
3002 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
3003
3004 /**
3005 * This function removes callback which was installed by
3006 * AddGCPrologueCallback function.
3007 */
3008 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
3009
3010 /**
3011 * The function is deprecated. Please use AddGCPrologueCallback instead.
3012 * Enables the host application to receive a notification before a
3013 * garbage collection. Allocations are not allowed in the
Steve Blocka7e24c12009-10-30 11:49:00 +00003014 * callback function, you therefore cannot manipulate objects (set
3015 * or delete properties for example) since it is possible such
3016 * operations will result in the allocation of objects.
3017 */
3018 static void SetGlobalGCPrologueCallback(GCCallback);
3019
3020 /**
3021 * Enables the host application to receive a notification after a
Steve Block6ded16b2010-05-10 14:33:55 +01003022 * garbage collection. Allocations are not allowed in the
3023 * callback function, you therefore cannot manipulate objects (set
3024 * or delete properties for example) since it is possible such
3025 * operations will result in the allocation of objects. It is possible
3026 * to specify the GCType filter for your callback. But it is not possible to
3027 * register the same callback function two times with different
3028 * GCType filters.
3029 */
3030 static void AddGCEpilogueCallback(
3031 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
3032
3033 /**
3034 * This function removes callback which was installed by
3035 * AddGCEpilogueCallback function.
3036 */
3037 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
3038
3039 /**
3040 * The function is deprecated. Please use AddGCEpilogueCallback instead.
3041 * Enables the host application to receive a notification after a
Steve Blocka7e24c12009-10-30 11:49:00 +00003042 * major garbage collection. Allocations are not allowed in the
3043 * callback function, you therefore cannot manipulate objects (set
3044 * or delete properties for example) since it is possible such
3045 * operations will result in the allocation of objects.
3046 */
3047 static void SetGlobalGCEpilogueCallback(GCCallback);
3048
3049 /**
Iain Merrick9ac36c92010-09-13 15:29:50 +01003050 * Enables the host application to provide a mechanism to be notified
3051 * and perform custom logging when V8 Allocates Executable Memory.
3052 */
3053 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
3054 ObjectSpace space,
3055 AllocationAction action);
3056
3057 /**
Ben Murdochc7cc0282012-03-05 14:35:55 +00003058 * Removes callback that was installed by AddMemoryAllocationCallback.
Iain Merrick9ac36c92010-09-13 15:29:50 +01003059 */
3060 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
3061
3062 /**
Ben Murdochc7cc0282012-03-05 14:35:55 +00003063 * Adds a callback to notify the host application when a script finished
3064 * running. If a script re-enters the runtime during executing, the
3065 * CallCompletedCallback is only invoked when the outer-most script
3066 * execution ends. Executing scripts inside the callback do not trigger
3067 * further callbacks.
3068 */
3069 static void AddCallCompletedCallback(CallCompletedCallback callback);
3070
3071 /**
3072 * Removes callback that was installed by AddCallCompletedCallback.
3073 */
3074 static void RemoveCallCompletedCallback(CallCompletedCallback callback);
3075
3076 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003077 * Allows the host application to group objects together. If one
3078 * object in the group is alive, all objects in the group are alive.
3079 * After each garbage collection, object groups are removed. It is
3080 * intended to be used in the before-garbage-collection callback
3081 * function, for instance to simulate DOM tree connections among JS
3082 * wrapper objects.
Steve Block44f0eee2011-05-26 01:26:41 +01003083 * See v8-profiler.h for RetainedObjectInfo interface description.
Steve Blocka7e24c12009-10-30 11:49:00 +00003084 */
Steve Block44f0eee2011-05-26 01:26:41 +01003085 static void AddObjectGroup(Persistent<Value>* objects,
3086 size_t length,
3087 RetainedObjectInfo* info = NULL);
3088
3089 /**
3090 * Allows the host application to declare implicit references between
3091 * the objects: if |parent| is alive, all |children| are alive too.
3092 * After each garbage collection, all implicit references
3093 * are removed. It is intended to be used in the before-garbage-collection
3094 * callback function.
3095 */
3096 static void AddImplicitReferences(Persistent<Object> parent,
3097 Persistent<Value>* children,
3098 size_t length);
Steve Blocka7e24c12009-10-30 11:49:00 +00003099
3100 /**
3101 * Initializes from snapshot if possible. Otherwise, attempts to
3102 * initialize from scratch. This function is called implicitly if
3103 * you use the API without calling it first.
3104 */
3105 static bool Initialize();
3106
3107 /**
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003108 * Allows the host application to provide a callback which can be used
3109 * as a source of entropy for random number generators.
3110 */
3111 static void SetEntropySource(EntropySource source);
3112
3113 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003114 * Adjusts the amount of registered external memory. Used to give
3115 * V8 an indication of the amount of externally allocated memory
3116 * that is kept alive by JavaScript objects. V8 uses this to decide
3117 * when to perform global garbage collections. Registering
3118 * externally allocated memory will trigger global garbage
3119 * collections more often than otherwise in an attempt to garbage
3120 * collect the JavaScript objects keeping the externally allocated
3121 * memory alive.
3122 *
3123 * \param change_in_bytes the change in externally allocated memory
3124 * that is kept alive by JavaScript objects.
3125 * \returns the adjusted value.
3126 */
3127 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
3128
3129 /**
3130 * Suspends recording of tick samples in the profiler.
3131 * When the V8 profiling mode is enabled (usually via command line
3132 * switches) this function suspends recording of tick samples.
3133 * Profiling ticks are discarded until ResumeProfiler() is called.
3134 *
3135 * See also the --prof and --prof_auto command line switches to
3136 * enable V8 profiling.
3137 */
3138 static void PauseProfiler();
3139
3140 /**
3141 * Resumes recording of tick samples in the profiler.
3142 * See also PauseProfiler().
3143 */
3144 static void ResumeProfiler();
3145
3146 /**
3147 * Return whether profiler is currently paused.
3148 */
3149 static bool IsProfilerPaused();
3150
3151 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003152 * Retrieve the V8 thread id of the calling thread.
3153 *
3154 * The thread id for a thread should only be retrieved after the V8
3155 * lock has been acquired with a Locker object with that thread.
3156 */
3157 static int GetCurrentThreadId();
3158
3159 /**
3160 * Forcefully terminate execution of a JavaScript thread. This can
3161 * be used to terminate long-running scripts.
3162 *
3163 * TerminateExecution should only be called when then V8 lock has
3164 * been acquired with a Locker object. Therefore, in order to be
3165 * able to terminate long-running threads, preemption must be
3166 * enabled to allow the user of TerminateExecution to acquire the
3167 * lock.
3168 *
3169 * The termination is achieved by throwing an exception that is
3170 * uncatchable by JavaScript exception handlers. Termination
3171 * exceptions act as if they were caught by a C++ TryCatch exception
Ben Murdoch257744e2011-11-30 15:57:28 +00003172 * handler. If forceful termination is used, any C++ TryCatch
Steve Blocka7e24c12009-10-30 11:49:00 +00003173 * exception handler that catches an exception should check if that
3174 * exception is a termination exception and immediately return if
3175 * that is the case. Returning immediately in that case will
3176 * continue the propagation of the termination exception if needed.
3177 *
3178 * The thread id passed to TerminateExecution must have been
3179 * obtained by calling GetCurrentThreadId on the thread in question.
3180 *
3181 * \param thread_id The thread id of the thread to terminate.
3182 */
3183 static void TerminateExecution(int thread_id);
3184
3185 /**
Steve Block44f0eee2011-05-26 01:26:41 +01003186 * Forcefully terminate the current thread of JavaScript execution
3187 * in the given isolate. If no isolate is provided, the default
3188 * isolate is used.
Steve Blocka7e24c12009-10-30 11:49:00 +00003189 *
3190 * This method can be used by any thread even if that thread has not
3191 * acquired the V8 lock with a Locker object.
Steve Block44f0eee2011-05-26 01:26:41 +01003192 *
3193 * \param isolate The isolate in which to terminate the current JS execution.
Steve Blocka7e24c12009-10-30 11:49:00 +00003194 */
Steve Block44f0eee2011-05-26 01:26:41 +01003195 static void TerminateExecution(Isolate* isolate = NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00003196
3197 /**
Steve Block6ded16b2010-05-10 14:33:55 +01003198 * Is V8 terminating JavaScript execution.
3199 *
3200 * Returns true if JavaScript execution is currently terminating
3201 * because of a call to TerminateExecution. In that case there are
3202 * still JavaScript frames on the stack and the termination
3203 * exception is still active.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003204 *
3205 * \param isolate The isolate in which to check.
Steve Block6ded16b2010-05-10 14:33:55 +01003206 */
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003207 static bool IsExecutionTerminating(Isolate* isolate = NULL);
Steve Block6ded16b2010-05-10 14:33:55 +01003208
3209 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003210 * Releases any resources used by v8 and stops any utility threads
3211 * that may be running. Note that disposing v8 is permanent, it
3212 * cannot be reinitialized.
3213 *
3214 * It should generally not be necessary to dispose v8 before exiting
3215 * a process, this should happen automatically. It is only necessary
3216 * to use if the process needs the resources taken up by v8.
3217 */
3218 static bool Dispose();
3219
Steve Block3ce2e202009-11-05 08:53:23 +00003220 /**
3221 * Get statistics about the heap memory usage.
3222 */
3223 static void GetHeapStatistics(HeapStatistics* heap_statistics);
Steve Blocka7e24c12009-10-30 11:49:00 +00003224
3225 /**
Ben Murdochc7cc0282012-03-05 14:35:55 +00003226 * Iterates through all external resources referenced from current isolate
3227 * heap. This method is not expected to be used except for debugging purposes
3228 * and may be quite slow.
3229 */
3230 static void VisitExternalResources(ExternalResourceVisitor* visitor);
3231
3232 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003233 * Optional notification that the embedder is idle.
3234 * V8 uses the notification to reduce memory footprint.
3235 * This call can be used repeatedly if the embedder remains idle.
Steve Blocka7e24c12009-10-30 11:49:00 +00003236 * Returns true if the embedder should stop calling IdleNotification
3237 * until real work has been done. This indicates that V8 has done
3238 * as much cleanup as it will be able to do.
Ben Murdochc7cc0282012-03-05 14:35:55 +00003239 *
3240 * The hint argument specifies the amount of work to be done in the function
3241 * on scale from 1 to 1000. There is no guarantee that the actual work will
3242 * match the hint.
Steve Blocka7e24c12009-10-30 11:49:00 +00003243 */
Ben Murdochc7cc0282012-03-05 14:35:55 +00003244 static bool IdleNotification(int hint = 1000);
Steve Blocka7e24c12009-10-30 11:49:00 +00003245
3246 /**
3247 * Optional notification that the system is running low on memory.
3248 * V8 uses these notifications to attempt to free memory.
3249 */
3250 static void LowMemoryNotification();
3251
Steve Block6ded16b2010-05-10 14:33:55 +01003252 /**
3253 * Optional notification that a context has been disposed. V8 uses
3254 * these notifications to guide the GC heuristic. Returns the number
3255 * of context disposals - including this one - since the last time
3256 * V8 had a chance to clean up.
3257 */
3258 static int ContextDisposedNotification();
3259
Steve Blocka7e24c12009-10-30 11:49:00 +00003260 private:
3261 V8();
3262
3263 static internal::Object** GlobalizeReference(internal::Object** handle);
3264 static void DisposeGlobal(internal::Object** global_handle);
3265 static void MakeWeak(internal::Object** global_handle,
3266 void* data,
3267 WeakReferenceCallback);
3268 static void ClearWeak(internal::Object** global_handle);
Ben Murdoch257744e2011-11-30 15:57:28 +00003269 static void MarkIndependent(internal::Object** global_handle);
Steve Blocka7e24c12009-10-30 11:49:00 +00003270 static bool IsGlobalNearDeath(internal::Object** global_handle);
3271 static bool IsGlobalWeak(internal::Object** global_handle);
Steve Block44f0eee2011-05-26 01:26:41 +01003272 static void SetWrapperClassId(internal::Object** global_handle,
3273 uint16_t class_id);
Steve Blocka7e24c12009-10-30 11:49:00 +00003274
3275 template <class T> friend class Handle;
3276 template <class T> friend class Local;
3277 template <class T> friend class Persistent;
3278 friend class Context;
3279};
3280
3281
3282/**
3283 * An external exception handler.
3284 */
3285class V8EXPORT TryCatch {
3286 public:
Steve Blocka7e24c12009-10-30 11:49:00 +00003287 /**
3288 * Creates a new try/catch block and registers it with v8.
3289 */
3290 TryCatch();
3291
3292 /**
3293 * Unregisters and deletes this try/catch block.
3294 */
3295 ~TryCatch();
3296
3297 /**
3298 * Returns true if an exception has been caught by this try/catch block.
3299 */
3300 bool HasCaught() const;
3301
3302 /**
3303 * For certain types of exceptions, it makes no sense to continue
3304 * execution.
3305 *
3306 * Currently, the only type of exception that can be caught by a
3307 * TryCatch handler and for which it does not make sense to continue
3308 * is termination exception. Such exceptions are thrown when the
3309 * TerminateExecution methods are called to terminate a long-running
3310 * script.
3311 *
3312 * If CanContinue returns false, the correct action is to perform
3313 * any C++ cleanup needed and then return.
3314 */
3315 bool CanContinue() const;
3316
3317 /**
Steve Blockd0582a62009-12-15 09:54:21 +00003318 * Throws the exception caught by this TryCatch in a way that avoids
3319 * it being caught again by this same TryCatch. As with ThrowException
3320 * it is illegal to execute any JavaScript operations after calling
3321 * ReThrow; the caller must return immediately to where the exception
3322 * is caught.
3323 */
3324 Handle<Value> ReThrow();
3325
3326 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003327 * Returns the exception caught by this try/catch block. If no exception has
3328 * been caught an empty handle is returned.
3329 *
3330 * The returned handle is valid until this TryCatch block has been destroyed.
3331 */
3332 Local<Value> Exception() const;
3333
3334 /**
3335 * Returns the .stack property of the thrown object. If no .stack
3336 * property is present an empty handle is returned.
3337 */
3338 Local<Value> StackTrace() const;
3339
3340 /**
3341 * Returns the message associated with this exception. If there is
3342 * no message associated an empty handle is returned.
3343 *
3344 * The returned handle is valid until this TryCatch block has been
3345 * destroyed.
3346 */
3347 Local<v8::Message> Message() const;
3348
3349 /**
3350 * Clears any exceptions that may have been caught by this try/catch block.
3351 * After this method has been called, HasCaught() will return false.
3352 *
3353 * It is not necessary to clear a try/catch block before using it again; if
3354 * another exception is thrown the previously caught exception will just be
3355 * overwritten. However, it is often a good idea since it makes it easier
3356 * to determine which operation threw a given exception.
3357 */
3358 void Reset();
3359
3360 /**
3361 * Set verbosity of the external exception handler.
3362 *
3363 * By default, exceptions that are caught by an external exception
3364 * handler are not reported. Call SetVerbose with true on an
3365 * external exception handler to have exceptions caught by the
3366 * handler reported as if they were not caught.
3367 */
3368 void SetVerbose(bool value);
3369
3370 /**
3371 * Set whether or not this TryCatch should capture a Message object
3372 * which holds source information about where the exception
3373 * occurred. True by default.
3374 */
3375 void SetCaptureMessage(bool value);
3376
Steve Blockd0582a62009-12-15 09:54:21 +00003377 private:
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00003378 v8::internal::Isolate* isolate_;
Steve Blockd0582a62009-12-15 09:54:21 +00003379 void* next_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003380 void* exception_;
3381 void* message_;
Steve Blockd0582a62009-12-15 09:54:21 +00003382 bool is_verbose_ : 1;
3383 bool can_continue_ : 1;
3384 bool capture_message_ : 1;
3385 bool rethrow_ : 1;
3386
Steve Block44f0eee2011-05-26 01:26:41 +01003387 friend class v8::internal::Isolate;
Steve Blocka7e24c12009-10-30 11:49:00 +00003388};
3389
3390
Ben Murdoch257744e2011-11-30 15:57:28 +00003391// --- Context ---
Steve Blocka7e24c12009-10-30 11:49:00 +00003392
3393
3394/**
3395 * Ignore
3396 */
3397class V8EXPORT ExtensionConfiguration {
3398 public:
3399 ExtensionConfiguration(int name_count, const char* names[])
3400 : name_count_(name_count), names_(names) { }
3401 private:
3402 friend class ImplementationUtilities;
3403 int name_count_;
3404 const char** names_;
3405};
3406
3407
3408/**
3409 * A sandboxed execution context with its own set of built-in objects
3410 * and functions.
3411 */
3412class V8EXPORT Context {
3413 public:
Steve Block1e0659c2011-05-24 12:43:12 +01003414 /**
3415 * Returns the global proxy object or global object itself for
3416 * detached contexts.
3417 *
3418 * Global proxy object is a thin wrapper whose prototype points to
3419 * actual context's global object with the properties like Object, etc.
3420 * This is done that way for security reasons (for more details see
3421 * https://wiki.mozilla.org/Gecko:SplitWindow).
3422 *
3423 * Please note that changes to global proxy object prototype most probably
3424 * would break VM---v8 expects only global object as a prototype of
3425 * global proxy object.
3426 *
3427 * If DetachGlobal() has been invoked, Global() would return actual global
3428 * object until global is reattached with ReattachGlobal().
3429 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003430 Local<Object> Global();
3431
3432 /**
3433 * Detaches the global object from its context before
3434 * the global object can be reused to create a new context.
3435 */
3436 void DetachGlobal();
3437
Andrei Popescu74b3c142010-03-29 12:03:09 +01003438 /**
3439 * Reattaches a global object to a context. This can be used to
3440 * restore the connection between a global object and a context
3441 * after DetachGlobal has been called.
3442 *
3443 * \param global_object The global object to reattach to the
3444 * context. For this to work, the global object must be the global
3445 * object that was associated with this context before a call to
3446 * DetachGlobal.
3447 */
3448 void ReattachGlobal(Handle<Object> global_object);
3449
Leon Clarkef7060e22010-06-03 12:02:55 +01003450 /** Creates a new context.
3451 *
3452 * Returns a persistent handle to the newly allocated context. This
3453 * persistent handle has to be disposed when the context is no
3454 * longer used so the context can be garbage collected.
Steve Block9fac8402011-05-12 15:51:54 +01003455 *
3456 * \param extensions An optional extension configuration containing
3457 * the extensions to be installed in the newly created context.
3458 *
3459 * \param global_template An optional object template from which the
3460 * global object for the newly created context will be created.
3461 *
3462 * \param global_object An optional global object to be reused for
3463 * the newly created context. This global object must have been
3464 * created by a previous call to Context::New with the same global
3465 * template. The state of the global object will be completely reset
3466 * and only object identify will remain.
Leon Clarkef7060e22010-06-03 12:02:55 +01003467 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003468 static Persistent<Context> New(
Andrei Popescu31002712010-02-23 13:46:05 +00003469 ExtensionConfiguration* extensions = NULL,
Steve Blocka7e24c12009-10-30 11:49:00 +00003470 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3471 Handle<Value> global_object = Handle<Value>());
3472
3473 /** Returns the last entered context. */
3474 static Local<Context> GetEntered();
3475
3476 /** Returns the context that is on the top of the stack. */
3477 static Local<Context> GetCurrent();
3478
3479 /**
3480 * Returns the context of the calling JavaScript code. That is the
3481 * context of the top-most JavaScript frame. If there are no
3482 * JavaScript frames an empty handle is returned.
3483 */
3484 static Local<Context> GetCalling();
3485
3486 /**
3487 * Sets the security token for the context. To access an object in
3488 * another context, the security tokens must match.
3489 */
3490 void SetSecurityToken(Handle<Value> token);
3491
3492 /** Restores the security token to the default value. */
3493 void UseDefaultSecurityToken();
3494
3495 /** Returns the security token of this context.*/
3496 Handle<Value> GetSecurityToken();
3497
3498 /**
3499 * Enter this context. After entering a context, all code compiled
3500 * and run is compiled and run in this context. If another context
3501 * is already entered, this old context is saved so it can be
3502 * restored when the new context is exited.
3503 */
3504 void Enter();
3505
3506 /**
3507 * Exit this context. Exiting the current context restores the
3508 * context that was in place when entering the current context.
3509 */
3510 void Exit();
3511
3512 /** Returns true if the context has experienced an out of memory situation. */
3513 bool HasOutOfMemoryException();
3514
3515 /** Returns true if V8 has a current context. */
3516 static bool InContext();
3517
3518 /**
3519 * Associate an additional data object with the context. This is mainly used
3520 * with the debugger to provide additional information on the context through
3521 * the debugger API.
3522 */
Steve Blockd0582a62009-12-15 09:54:21 +00003523 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00003524 Local<Value> GetData();
3525
3526 /**
Ben Murdoch257744e2011-11-30 15:57:28 +00003527 * Control whether code generation from strings is allowed. Calling
3528 * this method with false will disable 'eval' and the 'Function'
3529 * constructor for code running in this context. If 'eval' or the
3530 * 'Function' constructor are used an exception will be thrown.
3531 *
3532 * If code generation from strings is not allowed the
3533 * V8::AllowCodeGenerationFromStrings callback will be invoked if
3534 * set before blocking the call to 'eval' or the 'Function'
3535 * constructor. If that callback returns true, the call will be
3536 * allowed, otherwise an exception will be thrown. If no callback is
3537 * set an exception will be thrown.
3538 */
3539 void AllowCodeGenerationFromStrings(bool allow);
3540
3541 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00003542 * Stack-allocated class which sets the execution context for all
3543 * operations executed within a local scope.
3544 */
Steve Block8defd9f2010-07-08 12:39:36 +01003545 class Scope {
Steve Blocka7e24c12009-10-30 11:49:00 +00003546 public:
Ben Murdoch8b112d22011-06-08 16:22:53 +01003547 explicit inline Scope(Handle<Context> context) : context_(context) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003548 context_->Enter();
3549 }
3550 inline ~Scope() { context_->Exit(); }
3551 private:
3552 Handle<Context> context_;
3553 };
3554
3555 private:
3556 friend class Value;
3557 friend class Script;
3558 friend class Object;
3559 friend class Function;
3560};
3561
3562
3563/**
3564 * Multiple threads in V8 are allowed, but only one thread at a time
Steve Block44f0eee2011-05-26 01:26:41 +01003565 * is allowed to use any given V8 isolate. See Isolate class
3566 * comments. The definition of 'using V8 isolate' includes
3567 * accessing handles or holding onto object pointers obtained
3568 * from V8 handles while in the particular V8 isolate. It is up
3569 * to the user of V8 to ensure (perhaps with locking) that this
Ben Murdochc7cc0282012-03-05 14:35:55 +00003570 * constraint is not violated. In addition to any other synchronization
3571 * mechanism that may be used, the v8::Locker and v8::Unlocker classes
3572 * must be used to signal thead switches to V8.
Steve Blocka7e24c12009-10-30 11:49:00 +00003573 *
Ben Murdoch257744e2011-11-30 15:57:28 +00003574 * v8::Locker is a scoped lock object. While it's
3575 * active (i.e. between its construction and destruction) the current thread is
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003576 * allowed to use the locked isolate. V8 guarantees that an isolate can be
3577 * locked by at most one thread at any time. In other words, the scope of a
3578 * v8::Locker is a critical section.
Steve Block44f0eee2011-05-26 01:26:41 +01003579 *
Ben Murdoch257744e2011-11-30 15:57:28 +00003580 * Sample usage:
3581* \code
Steve Blocka7e24c12009-10-30 11:49:00 +00003582 * ...
3583 * {
Ben Murdoch257744e2011-11-30 15:57:28 +00003584 * v8::Locker locker(isolate);
3585 * v8::Isolate::Scope isolate_scope(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00003586 * ...
Ben Murdoch257744e2011-11-30 15:57:28 +00003587 * // Code using V8 and isolate goes here.
Steve Blocka7e24c12009-10-30 11:49:00 +00003588 * ...
3589 * } // Destructor called here
3590 * \endcode
3591 *
Ben Murdoch257744e2011-11-30 15:57:28 +00003592 * If you wish to stop using V8 in a thread A you can do this either
Steve Blocka7e24c12009-10-30 11:49:00 +00003593 * by destroying the v8::Locker object as above or by constructing a
3594 * v8::Unlocker object:
3595 *
3596 * \code
3597 * {
Ben Murdoch257744e2011-11-30 15:57:28 +00003598 * isolate->Exit();
3599 * v8::Unlocker unlocker(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00003600 * ...
3601 * // Code not using V8 goes here while V8 can run in another thread.
3602 * ...
3603 * } // Destructor called here.
Ben Murdoch257744e2011-11-30 15:57:28 +00003604 * isolate->Enter();
Steve Blocka7e24c12009-10-30 11:49:00 +00003605 * \endcode
3606 *
3607 * The Unlocker object is intended for use in a long-running callback
3608 * from V8, where you want to release the V8 lock for other threads to
3609 * use.
3610 *
3611 * The v8::Locker is a recursive lock. That is, you can lock more than
3612 * once in a given thread. This can be useful if you have code that can
3613 * be called either from code that holds the lock or from code that does
3614 * not. The Unlocker is not recursive so you can not have several
3615 * Unlockers on the stack at once, and you can not use an Unlocker in a
3616 * thread that is not inside a Locker's scope.
3617 *
3618 * An unlocker will unlock several lockers if it has to and reinstate
3619 * the correct depth of locking on its destruction. eg.:
3620 *
3621 * \code
3622 * // V8 not locked.
3623 * {
Ben Murdoch257744e2011-11-30 15:57:28 +00003624 * v8::Locker locker(isolate);
3625 * Isolate::Scope isolate_scope(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00003626 * // V8 locked.
3627 * {
Ben Murdoch257744e2011-11-30 15:57:28 +00003628 * v8::Locker another_locker(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00003629 * // V8 still locked (2 levels).
3630 * {
Ben Murdoch257744e2011-11-30 15:57:28 +00003631 * isolate->Exit();
3632 * v8::Unlocker unlocker(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00003633 * // V8 not locked.
3634 * }
Ben Murdoch257744e2011-11-30 15:57:28 +00003635 * isolate->Enter();
Steve Blocka7e24c12009-10-30 11:49:00 +00003636 * // V8 locked again (2 levels).
3637 * }
3638 * // V8 still locked (1 level).
3639 * }
3640 * // V8 Now no longer locked.
3641 * \endcode
Ben Murdoch257744e2011-11-30 15:57:28 +00003642 *
Ben Murdoch589d6972011-11-30 16:04:58 +00003643 *
Steve Blocka7e24c12009-10-30 11:49:00 +00003644 */
3645class V8EXPORT Unlocker {
3646 public:
Ben Murdoch257744e2011-11-30 15:57:28 +00003647 /**
3648 * Initialize Unlocker for a given Isolate. NULL means default isolate.
3649 */
3650 explicit Unlocker(Isolate* isolate = NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00003651 ~Unlocker();
Ben Murdoch257744e2011-11-30 15:57:28 +00003652 private:
3653 internal::Isolate* isolate_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003654};
3655
3656
3657class V8EXPORT Locker {
3658 public:
Ben Murdoch257744e2011-11-30 15:57:28 +00003659 /**
3660 * Initialize Locker for a given Isolate. NULL means default isolate.
3661 */
3662 explicit Locker(Isolate* isolate = NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00003663 ~Locker();
3664
3665 /**
3666 * Start preemption.
3667 *
Ben Murdoch257744e2011-11-30 15:57:28 +00003668 * When preemption is started, a timer is fired every n milliseconds
Steve Blocka7e24c12009-10-30 11:49:00 +00003669 * that will switch between multiple threads that are in contention
3670 * for the V8 lock.
3671 */
3672 static void StartPreemption(int every_n_ms);
3673
3674 /**
3675 * Stop preemption.
3676 */
3677 static void StopPreemption();
3678
3679 /**
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003680 * Returns whether or not the locker for a given isolate, or default isolate
3681 * if NULL is given, is locked by the current thread.
Steve Blocka7e24c12009-10-30 11:49:00 +00003682 */
Ben Murdoch257744e2011-11-30 15:57:28 +00003683 static bool IsLocked(Isolate* isolate = NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00003684
3685 /**
3686 * Returns whether v8::Locker is being used by this V8 instance.
3687 */
Ben Murdoch69a99ed2011-11-30 16:03:39 +00003688 static bool IsActive();
Steve Blocka7e24c12009-10-30 11:49:00 +00003689
3690 private:
3691 bool has_lock_;
3692 bool top_level_;
Ben Murdoch257744e2011-11-30 15:57:28 +00003693 internal::Isolate* isolate_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003694
3695 static bool active_;
3696
3697 // Disallow copying and assigning.
3698 Locker(const Locker&);
3699 void operator=(const Locker&);
3700};
3701
3702
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003703/**
3704 * An interface for exporting data from V8, using "push" model.
3705 */
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003706class V8EXPORT OutputStream { // NOLINT
3707 public:
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003708 enum OutputEncoding {
3709 kAscii = 0 // 7-bit ASCII.
3710 };
3711 enum WriteResult {
3712 kContinue = 0,
3713 kAbort = 1
3714 };
3715 virtual ~OutputStream() {}
3716 /** Notify about the end of stream. */
3717 virtual void EndOfStream() = 0;
3718 /** Get preferred output chunk size. Called only once. */
3719 virtual int GetChunkSize() { return 1024; }
3720 /** Get preferred output encoding. Called only once. */
3721 virtual OutputEncoding GetOutputEncoding() { return kAscii; }
3722 /**
3723 * Writes the next chunk of snapshot data into the stream. Writing
3724 * can be stopped by returning kAbort as function result. EndOfStream
3725 * will not be called in case writing was aborted.
3726 */
3727 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3728};
3729
3730
Ben Murdochb0fe1622011-05-05 13:52:32 +01003731/**
3732 * An interface for reporting progress and controlling long-running
3733 * activities.
3734 */
3735class V8EXPORT ActivityControl { // NOLINT
3736 public:
3737 enum ControlOption {
3738 kContinue = 0,
3739 kAbort = 1
3740 };
3741 virtual ~ActivityControl() {}
3742 /**
3743 * Notify about current progress. The activity can be stopped by
3744 * returning kAbort as the callback result.
3745 */
3746 virtual ControlOption ReportProgressValue(int done, int total) = 0;
3747};
3748
Steve Blocka7e24c12009-10-30 11:49:00 +00003749
Ben Murdoch257744e2011-11-30 15:57:28 +00003750// --- Implementation ---
Steve Blocka7e24c12009-10-30 11:49:00 +00003751
3752
3753namespace internal {
3754
Ben Murdoch592a9fc2012-03-05 11:04:45 +00003755const int kApiPointerSize = sizeof(void*); // NOLINT
3756const int kApiIntSize = sizeof(int); // NOLINT
Steve Blocka7e24c12009-10-30 11:49:00 +00003757
3758// Tag information for HeapObject.
3759const int kHeapObjectTag = 1;
3760const int kHeapObjectTagSize = 2;
3761const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3762
Steve Blocka7e24c12009-10-30 11:49:00 +00003763// Tag information for Smi.
3764const int kSmiTag = 0;
3765const int kSmiTagSize = 1;
3766const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3767
Ben Murdochb8e0da22011-05-16 14:20:40 +01003768template <size_t ptr_size> struct SmiTagging;
Steve Block3ce2e202009-11-05 08:53:23 +00003769
3770// Smi constants for 32-bit systems.
Ben Murdochb8e0da22011-05-16 14:20:40 +01003771template <> struct SmiTagging<4> {
Steve Block3ce2e202009-11-05 08:53:23 +00003772 static const int kSmiShiftSize = 0;
3773 static const int kSmiValueSize = 31;
3774 static inline int SmiToInt(internal::Object* value) {
3775 int shift_bits = kSmiTagSize + kSmiShiftSize;
3776 // Throw away top 32 bits and shift down (requires >> to be sign extending).
3777 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3778 }
Ben Murdochb8e0da22011-05-16 14:20:40 +01003779
3780 // For 32-bit systems any 2 bytes aligned pointer can be encoded as smi
3781 // with a plain reinterpret_cast.
Steve Block1e0659c2011-05-24 12:43:12 +01003782 static const uintptr_t kEncodablePointerMask = 0x1;
Ben Murdochb8e0da22011-05-16 14:20:40 +01003783 static const int kPointerToSmiShift = 0;
Steve Block3ce2e202009-11-05 08:53:23 +00003784};
3785
3786// Smi constants for 64-bit systems.
Ben Murdochb8e0da22011-05-16 14:20:40 +01003787template <> struct SmiTagging<8> {
Steve Block3ce2e202009-11-05 08:53:23 +00003788 static const int kSmiShiftSize = 31;
3789 static const int kSmiValueSize = 32;
3790 static inline int SmiToInt(internal::Object* value) {
3791 int shift_bits = kSmiTagSize + kSmiShiftSize;
3792 // Shift down and throw away top 32 bits.
3793 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3794 }
Ben Murdochb8e0da22011-05-16 14:20:40 +01003795
3796 // To maximize the range of pointers that can be encoded
3797 // in the available 32 bits, we require them to be 8 bytes aligned.
3798 // This gives 2 ^ (32 + 3) = 32G address space covered.
3799 // It might be not enough to cover stack allocated objects on some platforms.
3800 static const int kPointerAlignment = 3;
3801
Steve Block1e0659c2011-05-24 12:43:12 +01003802 static const uintptr_t kEncodablePointerMask =
3803 ~(uintptr_t(0xffffffff) << kPointerAlignment);
Ben Murdochb8e0da22011-05-16 14:20:40 +01003804
3805 static const int kPointerToSmiShift =
3806 kSmiTagSize + kSmiShiftSize - kPointerAlignment;
Steve Block3ce2e202009-11-05 08:53:23 +00003807};
3808
Ben Murdochb8e0da22011-05-16 14:20:40 +01003809typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
3810const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
3811const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
Steve Block1e0659c2011-05-24 12:43:12 +01003812const uintptr_t kEncodablePointerMask =
Ben Murdochb8e0da22011-05-16 14:20:40 +01003813 PlatformSmiTagging::kEncodablePointerMask;
3814const int kPointerToSmiShift = PlatformSmiTagging::kPointerToSmiShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00003815
Steve Blockd0582a62009-12-15 09:54:21 +00003816template <size_t ptr_size> struct InternalConstants;
3817
3818// Internal constants for 32-bit systems.
3819template <> struct InternalConstants<4> {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003820 static const int kStringResourceOffset = 3 * kApiPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003821};
3822
3823// Internal constants for 64-bit systems.
3824template <> struct InternalConstants<8> {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003825 static const int kStringResourceOffset = 3 * kApiPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003826};
3827
Steve Blocka7e24c12009-10-30 11:49:00 +00003828/**
3829 * This class exports constants and functionality from within v8 that
3830 * is necessary to implement inline functions in the v8 api. Don't
3831 * depend on functions and constants defined here.
3832 */
3833class Internals {
3834 public:
Steve Blocka7e24c12009-10-30 11:49:00 +00003835 // These values match non-compiler-dependent values defined within
3836 // the implementation of v8.
3837 static const int kHeapObjectMapOffset = 0;
Steve Block44f0eee2011-05-26 01:26:41 +01003838 static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003839 static const int kStringResourceOffset =
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003840 InternalConstants<kApiPointerSize>::kStringResourceOffset;
Steve Blockd0582a62009-12-15 09:54:21 +00003841
Ben Murdoch257744e2011-11-30 15:57:28 +00003842 static const int kForeignAddressOffset = kApiPointerSize;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003843 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003844 static const int kFullStringRepresentationMask = 0x07;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003845 static const int kExternalTwoByteRepresentationTag = 0x02;
Steve Blocka7e24c12009-10-30 11:49:00 +00003846
Ben Murdochc7cc0282012-03-05 14:35:55 +00003847 static const int kJSObjectType = 0xa7;
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003848 static const int kFirstNonstringType = 0x80;
Ben Murdoch257744e2011-11-30 15:57:28 +00003849 static const int kForeignType = 0x85;
Steve Blocka7e24c12009-10-30 11:49:00 +00003850
3851 static inline bool HasHeapObjectTag(internal::Object* value) {
3852 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3853 kHeapObjectTag);
3854 }
3855
3856 static inline bool HasSmiTag(internal::Object* value) {
3857 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3858 }
3859
3860 static inline int SmiValue(internal::Object* value) {
Ben Murdochb8e0da22011-05-16 14:20:40 +01003861 return PlatformSmiTagging::SmiToInt(value);
Steve Block3ce2e202009-11-05 08:53:23 +00003862 }
3863
3864 static inline int GetInstanceType(internal::Object* obj) {
3865 typedef internal::Object O;
3866 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3867 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3868 }
3869
Ben Murdochb8e0da22011-05-16 14:20:40 +01003870 static inline void* GetExternalPointerFromSmi(internal::Object* value) {
Steve Block1e0659c2011-05-24 12:43:12 +01003871 const uintptr_t address = reinterpret_cast<uintptr_t>(value);
Ben Murdochb8e0da22011-05-16 14:20:40 +01003872 return reinterpret_cast<void*>(address >> kPointerToSmiShift);
3873 }
3874
Steve Block3ce2e202009-11-05 08:53:23 +00003875 static inline void* GetExternalPointer(internal::Object* obj) {
3876 if (HasSmiTag(obj)) {
Ben Murdochb8e0da22011-05-16 14:20:40 +01003877 return GetExternalPointerFromSmi(obj);
Ben Murdoch257744e2011-11-30 15:57:28 +00003878 } else if (GetInstanceType(obj) == kForeignType) {
3879 return ReadField<void*>(obj, kForeignAddressOffset);
Steve Block3ce2e202009-11-05 08:53:23 +00003880 } else {
3881 return NULL;
3882 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003883 }
3884
3885 static inline bool IsExternalTwoByteString(int instance_type) {
3886 int representation = (instance_type & kFullStringRepresentationMask);
3887 return representation == kExternalTwoByteRepresentationTag;
3888 }
3889
3890 template <typename T>
3891 static inline T ReadField(Object* ptr, int offset) {
3892 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3893 return *reinterpret_cast<T*>(addr);
3894 }
Steve Block44f0eee2011-05-26 01:26:41 +01003895
3896 static inline bool CanCastToHeapObject(void* o) { return false; }
3897 static inline bool CanCastToHeapObject(Context* o) { return true; }
3898 static inline bool CanCastToHeapObject(String* o) { return true; }
3899 static inline bool CanCastToHeapObject(Object* o) { return true; }
3900 static inline bool CanCastToHeapObject(Message* o) { return true; }
3901 static inline bool CanCastToHeapObject(StackTrace* o) { return true; }
3902 static inline bool CanCastToHeapObject(StackFrame* o) { return true; }
Steve Blocka7e24c12009-10-30 11:49:00 +00003903};
3904
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003905} // namespace internal
Steve Blocka7e24c12009-10-30 11:49:00 +00003906
3907
3908template <class T>
Steve Blocka7e24c12009-10-30 11:49:00 +00003909Local<T>::Local() : Handle<T>() { }
3910
3911
3912template <class T>
3913Local<T> Local<T>::New(Handle<T> that) {
3914 if (that.IsEmpty()) return Local<T>();
Steve Block44f0eee2011-05-26 01:26:41 +01003915 T* that_ptr = *that;
3916 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
3917 if (internal::Internals::CanCastToHeapObject(that_ptr)) {
3918 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
3919 reinterpret_cast<internal::HeapObject*>(*p))));
3920 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003921 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3922}
3923
3924
3925template <class T>
3926Persistent<T> Persistent<T>::New(Handle<T> that) {
3927 if (that.IsEmpty()) return Persistent<T>();
3928 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3929 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3930}
3931
3932
3933template <class T>
3934bool Persistent<T>::IsNearDeath() const {
3935 if (this->IsEmpty()) return false;
3936 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3937}
3938
3939
3940template <class T>
3941bool Persistent<T>::IsWeak() const {
3942 if (this->IsEmpty()) return false;
3943 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3944}
3945
3946
3947template <class T>
3948void Persistent<T>::Dispose() {
3949 if (this->IsEmpty()) return;
3950 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3951}
3952
3953
3954template <class T>
3955Persistent<T>::Persistent() : Handle<T>() { }
3956
3957template <class T>
3958void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3959 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3960 parameters,
3961 callback);
3962}
3963
3964template <class T>
3965void Persistent<T>::ClearWeak() {
3966 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
3967}
3968
Steve Block44f0eee2011-05-26 01:26:41 +01003969template <class T>
Ben Murdoch257744e2011-11-30 15:57:28 +00003970void Persistent<T>::MarkIndependent() {
3971 V8::MarkIndependent(reinterpret_cast<internal::Object**>(**this));
3972}
3973
3974template <class T>
Steve Block44f0eee2011-05-26 01:26:41 +01003975void Persistent<T>::SetWrapperClassId(uint16_t class_id) {
3976 V8::SetWrapperClassId(reinterpret_cast<internal::Object**>(**this), class_id);
3977}
Steve Block8defd9f2010-07-08 12:39:36 +01003978
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003979Arguments::Arguments(internal::Object** implicit_args,
3980 internal::Object** values, int length,
3981 bool is_construct_call)
3982 : implicit_args_(implicit_args),
3983 values_(values),
3984 length_(length),
3985 is_construct_call_(is_construct_call) { }
Steve Block8defd9f2010-07-08 12:39:36 +01003986
3987
Steve Blocka7e24c12009-10-30 11:49:00 +00003988Local<Value> Arguments::operator[](int i) const {
3989 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
3990 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
3991}
3992
3993
3994Local<Function> Arguments::Callee() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003995 return Local<Function>(reinterpret_cast<Function*>(
3996 &implicit_args_[kCalleeIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003997}
3998
3999
4000Local<Object> Arguments::This() const {
4001 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
4002}
4003
4004
4005Local<Object> Arguments::Holder() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08004006 return Local<Object>(reinterpret_cast<Object*>(
4007 &implicit_args_[kHolderIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00004008}
4009
4010
4011Local<Value> Arguments::Data() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08004012 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00004013}
4014
4015
4016bool Arguments::IsConstructCall() const {
4017 return is_construct_call_;
4018}
4019
4020
4021int Arguments::Length() const {
4022 return length_;
4023}
4024
4025
4026template <class T>
4027Local<T> HandleScope::Close(Handle<T> value) {
4028 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
4029 internal::Object** after = RawClose(before);
4030 return Local<T>(reinterpret_cast<T*>(after));
4031}
4032
4033Handle<Value> ScriptOrigin::ResourceName() const {
4034 return resource_name_;
4035}
4036
4037
4038Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
4039 return resource_line_offset_;
4040}
4041
4042
4043Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
4044 return resource_column_offset_;
4045}
4046
4047
4048Handle<Boolean> Boolean::New(bool value) {
4049 return value ? True() : False();
4050}
4051
4052
4053void Template::Set(const char* name, v8::Handle<Data> value) {
4054 Set(v8::String::New(name), value);
4055}
4056
4057
4058Local<Value> Object::GetInternalField(int index) {
4059#ifndef V8_ENABLE_CHECKS
4060 Local<Value> quick_result = UncheckedGetInternalField(index);
4061 if (!quick_result.IsEmpty()) return quick_result;
4062#endif
4063 return CheckedGetInternalField(index);
4064}
4065
4066
4067Local<Value> Object::UncheckedGetInternalField(int index) {
4068 typedef internal::Object O;
4069 typedef internal::Internals I;
4070 O* obj = *reinterpret_cast<O**>(this);
Steve Block3ce2e202009-11-05 08:53:23 +00004071 if (I::GetInstanceType(obj) == I::kJSObjectType) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004072 // If the object is a plain JSObject, which is the common case,
4073 // we know where to find the internal fields and can return the
4074 // value directly.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004075 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
Steve Blocka7e24c12009-10-30 11:49:00 +00004076 O* value = I::ReadField<O*>(obj, offset);
4077 O** result = HandleScope::CreateHandle(value);
4078 return Local<Value>(reinterpret_cast<Value*>(result));
4079 } else {
4080 return Local<Value>();
4081 }
4082}
4083
4084
4085void* External::Unwrap(Handle<v8::Value> obj) {
4086#ifdef V8_ENABLE_CHECKS
4087 return FullUnwrap(obj);
4088#else
4089 return QuickUnwrap(obj);
4090#endif
4091}
4092
4093
4094void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
4095 typedef internal::Object O;
Steve Blocka7e24c12009-10-30 11:49:00 +00004096 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
Steve Block3ce2e202009-11-05 08:53:23 +00004097 return internal::Internals::GetExternalPointer(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00004098}
4099
4100
4101void* Object::GetPointerFromInternalField(int index) {
Steve Block3ce2e202009-11-05 08:53:23 +00004102 typedef internal::Object O;
4103 typedef internal::Internals I;
4104
4105 O* obj = *reinterpret_cast<O**>(this);
4106
4107 if (I::GetInstanceType(obj) == I::kJSObjectType) {
4108 // If the object is a plain JSObject, which is the common case,
4109 // we know where to find the internal fields and can return the
4110 // value directly.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004111 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
Steve Block3ce2e202009-11-05 08:53:23 +00004112 O* value = I::ReadField<O*>(obj, offset);
4113 return I::GetExternalPointer(value);
4114 }
4115
4116 return SlowGetPointerFromInternalField(index);
Steve Blocka7e24c12009-10-30 11:49:00 +00004117}
4118
4119
4120String* String::Cast(v8::Value* value) {
4121#ifdef V8_ENABLE_CHECKS
4122 CheckCast(value);
4123#endif
4124 return static_cast<String*>(value);
4125}
4126
4127
4128String::ExternalStringResource* String::GetExternalStringResource() const {
4129 typedef internal::Object O;
4130 typedef internal::Internals I;
4131 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
Steve Blocka7e24c12009-10-30 11:49:00 +00004132 String::ExternalStringResource* result;
Steve Block3ce2e202009-11-05 08:53:23 +00004133 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004134 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
4135 result = reinterpret_cast<String::ExternalStringResource*>(value);
4136 } else {
4137 result = NULL;
4138 }
4139#ifdef V8_ENABLE_CHECKS
4140 VerifyExternalStringResource(result);
4141#endif
4142 return result;
4143}
4144
4145
4146bool Value::IsString() const {
4147#ifdef V8_ENABLE_CHECKS
4148 return FullIsString();
4149#else
4150 return QuickIsString();
4151#endif
4152}
4153
4154bool Value::QuickIsString() const {
4155 typedef internal::Object O;
4156 typedef internal::Internals I;
4157 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
4158 if (!I::HasHeapObjectTag(obj)) return false;
Steve Block3ce2e202009-11-05 08:53:23 +00004159 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
Steve Blocka7e24c12009-10-30 11:49:00 +00004160}
4161
4162
4163Number* Number::Cast(v8::Value* value) {
4164#ifdef V8_ENABLE_CHECKS
4165 CheckCast(value);
4166#endif
4167 return static_cast<Number*>(value);
4168}
4169
4170
4171Integer* Integer::Cast(v8::Value* value) {
4172#ifdef V8_ENABLE_CHECKS
4173 CheckCast(value);
4174#endif
4175 return static_cast<Integer*>(value);
4176}
4177
4178
4179Date* Date::Cast(v8::Value* value) {
4180#ifdef V8_ENABLE_CHECKS
4181 CheckCast(value);
4182#endif
4183 return static_cast<Date*>(value);
4184}
4185
4186
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00004187StringObject* StringObject::Cast(v8::Value* value) {
4188#ifdef V8_ENABLE_CHECKS
4189 CheckCast(value);
4190#endif
4191 return static_cast<StringObject*>(value);
4192}
4193
4194
4195NumberObject* NumberObject::Cast(v8::Value* value) {
4196#ifdef V8_ENABLE_CHECKS
4197 CheckCast(value);
4198#endif
4199 return static_cast<NumberObject*>(value);
4200}
4201
4202
4203BooleanObject* BooleanObject::Cast(v8::Value* value) {
4204#ifdef V8_ENABLE_CHECKS
4205 CheckCast(value);
4206#endif
4207 return static_cast<BooleanObject*>(value);
4208}
4209
4210
Ben Murdochf87a2032010-10-22 12:50:53 +01004211RegExp* RegExp::Cast(v8::Value* value) {
4212#ifdef V8_ENABLE_CHECKS
4213 CheckCast(value);
4214#endif
4215 return static_cast<RegExp*>(value);
4216}
4217
4218
Steve Blocka7e24c12009-10-30 11:49:00 +00004219Object* Object::Cast(v8::Value* value) {
4220#ifdef V8_ENABLE_CHECKS
4221 CheckCast(value);
4222#endif
4223 return static_cast<Object*>(value);
4224}
4225
4226
4227Array* Array::Cast(v8::Value* value) {
4228#ifdef V8_ENABLE_CHECKS
4229 CheckCast(value);
4230#endif
4231 return static_cast<Array*>(value);
4232}
4233
4234
4235Function* Function::Cast(v8::Value* value) {
4236#ifdef V8_ENABLE_CHECKS
4237 CheckCast(value);
4238#endif
4239 return static_cast<Function*>(value);
4240}
4241
4242
4243External* External::Cast(v8::Value* value) {
4244#ifdef V8_ENABLE_CHECKS
4245 CheckCast(value);
4246#endif
4247 return static_cast<External*>(value);
4248}
4249
4250
4251Local<Value> AccessorInfo::Data() const {
Steve Block6ded16b2010-05-10 14:33:55 +01004252 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
Steve Blocka7e24c12009-10-30 11:49:00 +00004253}
4254
4255
4256Local<Object> AccessorInfo::This() const {
4257 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
4258}
4259
4260
4261Local<Object> AccessorInfo::Holder() const {
4262 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
4263}
4264
4265
4266/**
4267 * \example shell.cc
4268 * A simple shell that takes a list of expressions on the
4269 * command-line and executes them.
4270 */
4271
4272
4273/**
4274 * \example process.cc
4275 */
4276
4277
4278} // namespace v8
4279
4280
4281#undef V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00004282#undef TYPE_CHECK
4283
4284
4285#endif // V8_H_