blob: 83a5744278afe03f7a7869379f17217e74a80ea4 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2007-2009 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28/** \mainpage V8 API Reference Guide
29 *
30 * V8 is Google's open source JavaScript engine.
31 *
32 * This set of documents provides reference material generated from the
33 * V8 header file, include/v8.h.
34 *
35 * For other documentation see http://code.google.com/apis/v8/
36 */
37
38#ifndef V8_H_
39#define V8_H_
40
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080041#include "v8stdint.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000042
43#ifdef _WIN32
Steve Blocka7e24c12009-10-30 11:49:00 +000044
45// Setup for Windows DLL export/import. When building the V8 DLL the
46// BUILDING_V8_SHARED needs to be defined. When building a program which uses
47// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
48// static library or building a program which uses the V8 static library neither
49// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
Steve Blocka7e24c12009-10-30 11:49:00 +000050#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
51#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
52 build configuration to ensure that at most one of these is set
53#endif
54
55#ifdef BUILDING_V8_SHARED
56#define V8EXPORT __declspec(dllexport)
Steve Blocka7e24c12009-10-30 11:49:00 +000057#elif USING_V8_SHARED
58#define V8EXPORT __declspec(dllimport)
Steve Blocka7e24c12009-10-30 11:49:00 +000059#else
60#define V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +000061#endif // BUILDING_V8_SHARED
62
63#else // _WIN32
64
Steve Blocka7e24c12009-10-30 11:49:00 +000065// Setup for Linux shared library export. There is no need to distinguish
66// between building or using the V8 shared library, but we should not
67// export symbols when we are building a static library.
68#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
69#define V8EXPORT __attribute__ ((visibility("default")))
Steve Blocka7e24c12009-10-30 11:49:00 +000070#else // defined(__GNUC__) && (__GNUC__ >= 4)
71#define V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +000072#endif // defined(__GNUC__) && (__GNUC__ >= 4)
73
74#endif // _WIN32
75
76/**
77 * The v8 JavaScript engine.
78 */
79namespace v8 {
80
81class Context;
82class String;
83class Value;
84class Utils;
85class Number;
86class Object;
87class Array;
88class Int32;
89class Uint32;
90class External;
91class Primitive;
92class Boolean;
93class Integer;
94class Function;
95class Date;
96class ImplementationUtilities;
97class Signature;
98template <class T> class Handle;
99template <class T> class Local;
100template <class T> class Persistent;
101class FunctionTemplate;
102class ObjectTemplate;
103class Data;
Leon Clarkef7060e22010-06-03 12:02:55 +0100104class AccessorInfo;
Kristian Monsen25f61362010-05-21 11:50:48 +0100105class StackTrace;
106class StackFrame;
Steve Blocka7e24c12009-10-30 11:49:00 +0000107
108namespace internal {
109
Steve Blocka7e24c12009-10-30 11:49:00 +0000110class Arguments;
Steve Blockd0582a62009-12-15 09:54:21 +0000111class Object;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100112class Heap;
Steve Blockd0582a62009-12-15 09:54:21 +0000113class Top;
Steve Blocka7e24c12009-10-30 11:49:00 +0000114}
115
116
117// --- W e a k H a n d l e s
118
119
120/**
121 * A weak reference callback function.
122 *
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100123 * This callback should either explicitly invoke Dispose on |object| if
124 * V8 wrapper is not needed anymore, or 'revive' it by invocation of MakeWeak.
125 *
Steve Blocka7e24c12009-10-30 11:49:00 +0000126 * \param object the weak global object to be reclaimed by the garbage collector
127 * \param parameter the value passed in when making the weak global object
128 */
129typedef void (*WeakReferenceCallback)(Persistent<Value> object,
130 void* parameter);
131
132
133// --- H a n d l e s ---
134
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100135#define TYPE_CHECK(T, S) \
136 while (false) { \
137 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
Steve Blocka7e24c12009-10-30 11:49:00 +0000138 }
139
140/**
141 * An object reference managed by the v8 garbage collector.
142 *
143 * All objects returned from v8 have to be tracked by the garbage
144 * collector so that it knows that the objects are still alive. Also,
145 * because the garbage collector may move objects, it is unsafe to
146 * point directly to an object. Instead, all objects are stored in
147 * handles which are known by the garbage collector and updated
148 * whenever an object moves. Handles should always be passed by value
149 * (except in cases like out-parameters) and they should never be
150 * allocated on the heap.
151 *
152 * There are two types of handles: local and persistent handles.
153 * Local handles are light-weight and transient and typically used in
154 * local operations. They are managed by HandleScopes. Persistent
155 * handles can be used when storing objects across several independent
156 * operations and have to be explicitly deallocated when they're no
157 * longer used.
158 *
159 * It is safe to extract the object stored in the handle by
160 * dereferencing the handle (for instance, to extract the Object* from
161 * an Handle<Object>); the value will still be governed by a handle
162 * behind the scenes and the same rules apply to these values as to
163 * their handles.
164 */
Steve Block8defd9f2010-07-08 12:39:36 +0100165template <class T> class Handle {
Steve Blocka7e24c12009-10-30 11:49:00 +0000166 public:
167
168 /**
169 * Creates an empty handle.
170 */
171 inline Handle();
172
173 /**
174 * Creates a new handle for the specified value.
175 */
Steve Block8defd9f2010-07-08 12:39:36 +0100176 inline explicit Handle(T* val) : val_(val) { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000177
178 /**
179 * Creates a handle for the contents of the specified handle. This
180 * constructor allows you to pass handles as arguments by value and
181 * to assign between handles. However, if you try to assign between
182 * incompatible handles, for instance from a Handle<String> to a
183 * Handle<Number> it will cause a compiletime error. Assigning
184 * between compatible handles, for instance assigning a
185 * Handle<String> to a variable declared as Handle<Value>, is legal
186 * because String is a subclass of Value.
187 */
188 template <class S> inline Handle(Handle<S> that)
189 : val_(reinterpret_cast<T*>(*that)) {
190 /**
191 * This check fails when trying to convert between incompatible
192 * handles. For example, converting from a Handle<String> to a
193 * Handle<Number>.
194 */
195 TYPE_CHECK(T, S);
196 }
197
198 /**
199 * Returns true if the handle is empty.
200 */
Steve Block8defd9f2010-07-08 12:39:36 +0100201 inline bool IsEmpty() const { return val_ == 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000202
Steve Block8defd9f2010-07-08 12:39:36 +0100203 inline T* operator->() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000204
Steve Block8defd9f2010-07-08 12:39:36 +0100205 inline T* operator*() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000206
207 /**
208 * Sets the handle to be empty. IsEmpty() will then return true.
209 */
Steve Block8defd9f2010-07-08 12:39:36 +0100210 inline void Clear() { this->val_ = 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000211
212 /**
213 * Checks whether two handles are the same.
214 * Returns true if both are empty, or if the objects
215 * to which they refer are identical.
216 * The handles' references are not checked.
217 */
Steve Block8defd9f2010-07-08 12:39:36 +0100218 template <class S> inline bool operator==(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000219 internal::Object** a = reinterpret_cast<internal::Object**>(**this);
220 internal::Object** b = reinterpret_cast<internal::Object**>(*that);
221 if (a == 0) return b == 0;
222 if (b == 0) return false;
223 return *a == *b;
224 }
225
226 /**
227 * Checks whether two handles are different.
228 * Returns true if only one of the handles is empty, or if
229 * the objects to which they refer are different.
230 * The handles' references are not checked.
231 */
Steve Block8defd9f2010-07-08 12:39:36 +0100232 template <class S> inline bool operator!=(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000233 return !operator==(that);
234 }
235
236 template <class S> static inline Handle<T> Cast(Handle<S> that) {
237#ifdef V8_ENABLE_CHECKS
238 // If we're going to perform the type check then we have to check
239 // that the handle isn't empty before doing the checked cast.
240 if (that.IsEmpty()) return Handle<T>();
241#endif
242 return Handle<T>(T::Cast(*that));
243 }
244
Steve Block6ded16b2010-05-10 14:33:55 +0100245 template <class S> inline Handle<S> As() {
246 return Handle<S>::Cast(*this);
247 }
248
Steve Blocka7e24c12009-10-30 11:49:00 +0000249 private:
250 T* val_;
251};
252
253
254/**
255 * A light-weight stack-allocated object handle. All operations
256 * that return objects from within v8 return them in local handles. They
257 * are created within HandleScopes, and all local handles allocated within a
258 * handle scope are destroyed when the handle scope is destroyed. Hence it
259 * is not necessary to explicitly deallocate local handles.
260 */
Steve Block8defd9f2010-07-08 12:39:36 +0100261template <class T> class Local : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000262 public:
263 inline Local();
264 template <class S> inline Local(Local<S> that)
265 : Handle<T>(reinterpret_cast<T*>(*that)) {
266 /**
267 * This check fails when trying to convert between incompatible
268 * handles. For example, converting from a Handle<String> to a
269 * Handle<Number>.
270 */
271 TYPE_CHECK(T, S);
272 }
273 template <class S> inline Local(S* that) : Handle<T>(that) { }
274 template <class S> static inline Local<T> Cast(Local<S> that) {
275#ifdef V8_ENABLE_CHECKS
276 // If we're going to perform the type check then we have to check
277 // that the handle isn't empty before doing the checked cast.
278 if (that.IsEmpty()) return Local<T>();
279#endif
280 return Local<T>(T::Cast(*that));
281 }
282
Steve Block6ded16b2010-05-10 14:33:55 +0100283 template <class S> inline Local<S> As() {
284 return Local<S>::Cast(*this);
285 }
286
Steve Blocka7e24c12009-10-30 11:49:00 +0000287 /** Create a local handle for the content of another handle.
288 * The referee is kept alive by the local handle even when
289 * the original handle is destroyed/disposed.
290 */
291 inline static Local<T> New(Handle<T> that);
292};
293
294
295/**
296 * An object reference that is independent of any handle scope. Where
297 * a Local handle only lives as long as the HandleScope in which it was
298 * allocated, a Persistent handle remains valid until it is explicitly
299 * disposed.
300 *
301 * A persistent handle contains a reference to a storage cell within
302 * the v8 engine which holds an object value and which is updated by
303 * the garbage collector whenever the object is moved. A new storage
304 * cell can be created using Persistent::New and existing handles can
305 * be disposed using Persistent::Dispose. Since persistent handles
306 * are passed by value you may have many persistent handle objects
307 * that point to the same storage cell. For instance, if you pass a
308 * persistent handle as an argument to a function you will not get two
309 * different storage cells but rather two references to the same
310 * storage cell.
311 */
Steve Block8defd9f2010-07-08 12:39:36 +0100312template <class T> class Persistent : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000313 public:
314
315 /**
316 * Creates an empty persistent handle that doesn't point to any
317 * storage cell.
318 */
319 inline Persistent();
320
321 /**
322 * Creates a persistent handle for the same storage cell as the
323 * specified handle. This constructor allows you to pass persistent
324 * handles as arguments by value and to assign between persistent
325 * handles. However, attempting to assign between incompatible
326 * persistent handles, for instance from a Persistent<String> to a
327 * Persistent<Number> will cause a compiletime error. Assigning
328 * between compatible persistent handles, for instance assigning a
329 * Persistent<String> to a variable declared as Persistent<Value>,
330 * is allowed as String is a subclass of Value.
331 */
332 template <class S> inline Persistent(Persistent<S> that)
333 : Handle<T>(reinterpret_cast<T*>(*that)) {
334 /**
335 * This check fails when trying to convert between incompatible
336 * handles. For example, converting from a Handle<String> to a
337 * Handle<Number>.
338 */
339 TYPE_CHECK(T, S);
340 }
341
342 template <class S> inline Persistent(S* that) : Handle<T>(that) { }
343
344 /**
345 * "Casts" a plain handle which is known to be a persistent handle
346 * to a persistent handle.
347 */
348 template <class S> explicit inline Persistent(Handle<S> that)
349 : Handle<T>(*that) { }
350
351 template <class S> static inline Persistent<T> Cast(Persistent<S> that) {
352#ifdef V8_ENABLE_CHECKS
353 // If we're going to perform the type check then we have to check
354 // that the handle isn't empty before doing the checked cast.
355 if (that.IsEmpty()) return Persistent<T>();
356#endif
357 return Persistent<T>(T::Cast(*that));
358 }
359
Steve Block6ded16b2010-05-10 14:33:55 +0100360 template <class S> inline Persistent<S> As() {
361 return Persistent<S>::Cast(*this);
362 }
363
Steve Blocka7e24c12009-10-30 11:49:00 +0000364 /**
365 * Creates a new persistent handle for an existing local or
366 * persistent handle.
367 */
368 inline static Persistent<T> New(Handle<T> that);
369
370 /**
371 * Releases the storage cell referenced by this persistent handle.
372 * Does not remove the reference to the cell from any handles.
373 * This handle's reference, and any any other references to the storage
374 * cell remain and IsEmpty will still return false.
375 */
376 inline void Dispose();
377
378 /**
379 * Make the reference to this object weak. When only weak handles
380 * refer to the object, the garbage collector will perform a
381 * callback to the given V8::WeakReferenceCallback function, passing
382 * it the object reference and the given parameters.
383 */
384 inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
385
386 /** Clears the weak reference to this object.*/
387 inline void ClearWeak();
388
389 /**
390 *Checks if the handle holds the only reference to an object.
391 */
392 inline bool IsNearDeath() const;
393
394 /**
395 * Returns true if the handle's reference is weak.
396 */
397 inline bool IsWeak() const;
398
399 private:
400 friend class ImplementationUtilities;
401 friend class ObjectTemplate;
402};
403
404
405 /**
406 * A stack-allocated class that governs a number of local handles.
407 * After a handle scope has been created, all local handles will be
408 * allocated within that handle scope until either the handle scope is
409 * deleted or another handle scope is created. If there is already a
410 * handle scope and a new one is created, all allocations will take
411 * place in the new handle scope until it is deleted. After that,
412 * new handles will again be allocated in the original handle scope.
413 *
414 * After the handle scope of a local handle has been deleted the
415 * garbage collector will no longer track the object stored in the
416 * handle and may deallocate it. The behavior of accessing a handle
417 * for which the handle scope has been deleted is undefined.
418 */
419class V8EXPORT HandleScope {
420 public:
421 HandleScope();
422
423 ~HandleScope();
424
425 /**
426 * Closes the handle scope and returns the value as a handle in the
427 * previous scope, which is the new current scope after the call.
428 */
429 template <class T> Local<T> Close(Handle<T> value);
430
431 /**
432 * Counts the number of allocated handles.
433 */
434 static int NumberOfHandles();
435
436 /**
437 * Creates a new handle with the given value.
438 */
439 static internal::Object** CreateHandle(internal::Object* value);
440
441 private:
442 // Make it impossible to create heap-allocated or illegal handle
443 // scopes by disallowing certain operations.
444 HandleScope(const HandleScope&);
445 void operator=(const HandleScope&);
446 void* operator new(size_t size);
447 void operator delete(void*, size_t);
448
Steve Blockd0582a62009-12-15 09:54:21 +0000449 // This Data class is accessible internally as HandleScopeData through a
450 // typedef in the ImplementationUtilities class.
Steve Blocka7e24c12009-10-30 11:49:00 +0000451 class V8EXPORT Data {
452 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000453 internal::Object** next;
454 internal::Object** limit;
John Reck59135872010-11-02 12:39:01 -0700455 int level;
456
Steve Blocka7e24c12009-10-30 11:49:00 +0000457 inline void Initialize() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000458 next = limit = NULL;
John Reck59135872010-11-02 12:39:01 -0700459 level = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000460 }
461 };
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800462
John Reck59135872010-11-02 12:39:01 -0700463 void Leave();
Steve Blocka7e24c12009-10-30 11:49:00 +0000464
John Reck59135872010-11-02 12:39:01 -0700465 internal::Object** prev_next_;
466 internal::Object** prev_limit_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000467
468 // Allow for the active closing of HandleScopes which allows to pass a handle
469 // from the HandleScope being closed to the next top most HandleScope.
470 bool is_closed_;
471 internal::Object** RawClose(internal::Object** value);
472
473 friend class ImplementationUtilities;
474};
475
476
477// --- S p e c i a l o b j e c t s ---
478
479
480/**
481 * The superclass of values and API object templates.
482 */
483class V8EXPORT Data {
484 private:
485 Data();
486};
487
488
489/**
490 * Pre-compilation data that can be associated with a script. This
491 * data can be calculated for a script in advance of actually
492 * compiling it, and can be stored between compilations. When script
493 * data is given to the compile method compilation will be faster.
494 */
495class V8EXPORT ScriptData { // NOLINT
496 public:
497 virtual ~ScriptData() { }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100498
Leon Clarkef7060e22010-06-03 12:02:55 +0100499 /**
500 * Pre-compiles the specified script (context-independent).
501 *
502 * \param input Pointer to UTF-8 script source code.
503 * \param length Length of UTF-8 script source code.
504 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000505 static ScriptData* PreCompile(const char* input, int length);
Steve Blocka7e24c12009-10-30 11:49:00 +0000506
Leon Clarkef7060e22010-06-03 12:02:55 +0100507 /**
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100508 * Pre-compiles the specified script (context-independent).
509 *
510 * NOTE: Pre-compilation using this method cannot happen on another thread
511 * without using Lockers.
512 *
513 * \param source Script source code.
514 */
515 static ScriptData* PreCompile(Handle<String> source);
516
517 /**
Leon Clarkef7060e22010-06-03 12:02:55 +0100518 * Load previous pre-compilation data.
519 *
520 * \param data Pointer to data returned by a call to Data() of a previous
521 * ScriptData. Ownership is not transferred.
522 * \param length Length of data.
523 */
524 static ScriptData* New(const char* data, int length);
525
526 /**
527 * Returns the length of Data().
528 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000529 virtual int Length() = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +0100530
531 /**
532 * Returns a serialized representation of this ScriptData that can later be
533 * passed to New(). NOTE: Serialized data is platform-dependent.
534 */
535 virtual const char* Data() = 0;
536
537 /**
538 * Returns true if the source code could not be parsed.
539 */
Leon Clarkee46be812010-01-19 14:06:41 +0000540 virtual bool HasError() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000541};
542
543
544/**
545 * The origin, within a file, of a script.
546 */
Steve Block8defd9f2010-07-08 12:39:36 +0100547class ScriptOrigin {
Steve Blocka7e24c12009-10-30 11:49:00 +0000548 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100549 inline ScriptOrigin(
550 Handle<Value> resource_name,
551 Handle<Integer> resource_line_offset = Handle<Integer>(),
552 Handle<Integer> resource_column_offset = Handle<Integer>())
Steve Blocka7e24c12009-10-30 11:49:00 +0000553 : resource_name_(resource_name),
554 resource_line_offset_(resource_line_offset),
555 resource_column_offset_(resource_column_offset) { }
556 inline Handle<Value> ResourceName() const;
557 inline Handle<Integer> ResourceLineOffset() const;
558 inline Handle<Integer> ResourceColumnOffset() const;
559 private:
560 Handle<Value> resource_name_;
561 Handle<Integer> resource_line_offset_;
562 Handle<Integer> resource_column_offset_;
563};
564
565
566/**
567 * A compiled JavaScript script.
568 */
569class V8EXPORT Script {
570 public:
571
Steve Blocka7e24c12009-10-30 11:49:00 +0000572 /**
Andrei Popescu402d9372010-02-26 13:31:12 +0000573 * Compiles the specified script (context-independent).
Steve Blocka7e24c12009-10-30 11:49:00 +0000574 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000575 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100576 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000577 * when New() returns
578 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
579 * using pre_data speeds compilation if it's done multiple times.
580 * Owned by caller, no references are kept when New() returns.
581 * \param script_data Arbitrary data associated with script. Using
Steve Block6ded16b2010-05-10 14:33:55 +0100582 * this has same effect as calling SetData(), but allows data to be
Andrei Popescu402d9372010-02-26 13:31:12 +0000583 * available to compile event handlers.
584 * \return Compiled script object (context independent; when run it
585 * will use the currently entered context).
Steve Blocka7e24c12009-10-30 11:49:00 +0000586 */
Andrei Popescu402d9372010-02-26 13:31:12 +0000587 static Local<Script> New(Handle<String> source,
588 ScriptOrigin* origin = NULL,
589 ScriptData* pre_data = NULL,
590 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000591
592 /**
593 * Compiles the specified script using the specified file name
594 * object (typically a string) as the script's origin.
595 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000596 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100597 * \param file_name file name object (typically a string) to be used
Andrei Popescu402d9372010-02-26 13:31:12 +0000598 * as the script's origin.
599 * \return Compiled script object (context independent; when run it
600 * will use the currently entered context).
601 */
602 static Local<Script> New(Handle<String> source,
603 Handle<Value> file_name);
604
605 /**
606 * Compiles the specified script (bound to current context).
607 *
608 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100609 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000610 * when Compile() returns
611 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
612 * using pre_data speeds compilation if it's done multiple times.
613 * Owned by caller, no references are kept when Compile() returns.
614 * \param script_data Arbitrary data associated with script. Using
615 * this has same effect as calling SetData(), but makes data available
616 * earlier (i.e. to compile event handlers).
617 * \return Compiled script object, bound to the context that was active
618 * when this function was called. When run it will always use this
619 * context.
Steve Blocka7e24c12009-10-30 11:49:00 +0000620 */
621 static Local<Script> Compile(Handle<String> source,
Andrei Popescu402d9372010-02-26 13:31:12 +0000622 ScriptOrigin* origin = NULL,
623 ScriptData* pre_data = NULL,
624 Handle<String> script_data = Handle<String>());
625
626 /**
627 * Compiles the specified script using the specified file name
628 * object (typically a string) as the script's origin.
629 *
630 * \param source Script source code.
631 * \param file_name File name to use as script's origin
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.
638 */
639 static Local<Script> Compile(Handle<String> source,
640 Handle<Value> file_name,
641 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000642
643 /**
644 * Runs the script returning the resulting value. If the script is
645 * context independent (created using ::New) it will be run in the
646 * currently entered context. If it is context specific (created
647 * using ::Compile) it will be run in the context in which it was
648 * compiled.
649 */
650 Local<Value> Run();
651
652 /**
653 * Returns the script id value.
654 */
655 Local<Value> Id();
656
657 /**
658 * Associate an additional data object with the script. This is mainly used
659 * with the debugger as this data object is only available through the
660 * debugger API.
661 */
Steve Blockd0582a62009-12-15 09:54:21 +0000662 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000663};
664
665
666/**
667 * An error message.
668 */
669class V8EXPORT Message {
670 public:
671 Local<String> Get() const;
672 Local<String> GetSourceLine() const;
673
674 /**
675 * Returns the resource name for the script from where the function causing
676 * the error originates.
677 */
678 Handle<Value> GetScriptResourceName() const;
679
680 /**
681 * Returns the resource data for the script from where the function causing
682 * the error originates.
683 */
684 Handle<Value> GetScriptData() const;
685
686 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100687 * Exception stack trace. By default stack traces are not captured for
688 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
689 * to change this option.
690 */
691 Handle<StackTrace> GetStackTrace() const;
692
693 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000694 * Returns the number, 1-based, of the line where the error occurred.
695 */
696 int GetLineNumber() const;
697
698 /**
699 * Returns the index within the script of the first character where
700 * the error occurred.
701 */
702 int GetStartPosition() const;
703
704 /**
705 * Returns the index within the script of the last character where
706 * the error occurred.
707 */
708 int GetEndPosition() const;
709
710 /**
711 * Returns the index within the line of the first character where
712 * the error occurred.
713 */
714 int GetStartColumn() const;
715
716 /**
717 * Returns the index within the line of the last character where
718 * the error occurred.
719 */
720 int GetEndColumn() const;
721
722 // TODO(1245381): Print to a string instead of on a FILE.
723 static void PrintCurrentStackTrace(FILE* out);
Kristian Monsen25f61362010-05-21 11:50:48 +0100724
725 static const int kNoLineNumberInfo = 0;
726 static const int kNoColumnInfo = 0;
727};
728
729
730/**
731 * Representation of a JavaScript stack trace. The information collected is a
732 * snapshot of the execution stack and the information remains valid after
733 * execution continues.
734 */
735class V8EXPORT StackTrace {
736 public:
737 /**
738 * Flags that determine what information is placed captured for each
739 * StackFrame when grabbing the current stack trace.
740 */
741 enum StackTraceOptions {
742 kLineNumber = 1,
743 kColumnOffset = 1 << 1 | kLineNumber,
744 kScriptName = 1 << 2,
745 kFunctionName = 1 << 3,
746 kIsEval = 1 << 4,
747 kIsConstructor = 1 << 5,
Ben Murdochf87a2032010-10-22 12:50:53 +0100748 kScriptNameOrSourceURL = 1 << 6,
Kristian Monsen25f61362010-05-21 11:50:48 +0100749 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
Ben Murdochf87a2032010-10-22 12:50:53 +0100750 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
Kristian Monsen25f61362010-05-21 11:50:48 +0100751 };
752
753 /**
754 * Returns a StackFrame at a particular index.
755 */
756 Local<StackFrame> GetFrame(uint32_t index) const;
757
758 /**
759 * Returns the number of StackFrames.
760 */
761 int GetFrameCount() const;
762
763 /**
764 * Returns StackTrace as a v8::Array that contains StackFrame objects.
765 */
766 Local<Array> AsArray();
767
768 /**
769 * Grab a snapshot of the the current JavaScript execution stack.
770 *
771 * \param frame_limit The maximum number of stack frames we want to capture.
772 * \param options Enumerates the set of things we will capture for each
773 * StackFrame.
774 */
775 static Local<StackTrace> CurrentStackTrace(
776 int frame_limit,
777 StackTraceOptions options = kOverview);
778};
779
780
781/**
782 * A single JavaScript stack frame.
783 */
784class V8EXPORT StackFrame {
785 public:
786 /**
787 * Returns the number, 1-based, of the line for the associate function call.
788 * This method will return Message::kNoLineNumberInfo if it is unable to
789 * retrieve the line number, or if kLineNumber was not passed as an option
790 * when capturing the StackTrace.
791 */
792 int GetLineNumber() const;
793
794 /**
795 * Returns the 1-based column offset on the line for the associated function
796 * call.
797 * This method will return Message::kNoColumnInfo if it is unable to retrieve
798 * the column number, or if kColumnOffset was not passed as an option when
799 * capturing the StackTrace.
800 */
801 int GetColumn() const;
802
803 /**
804 * Returns the name of the resource that contains the script for the
805 * function for this StackFrame.
806 */
807 Local<String> GetScriptName() const;
808
809 /**
Ben Murdochf87a2032010-10-22 12:50:53 +0100810 * Returns the name of the resource that contains the script for the
811 * function for this StackFrame or sourceURL value if the script name
812 * is undefined and its source ends with //@ sourceURL=... string.
813 */
814 Local<String> GetScriptNameOrSourceURL() const;
815
816 /**
Kristian Monsen25f61362010-05-21 11:50:48 +0100817 * Returns the name of the function associated with this stack frame.
818 */
819 Local<String> GetFunctionName() const;
820
821 /**
822 * Returns whether or not the associated function is compiled via a call to
823 * eval().
824 */
825 bool IsEval() const;
826
827 /**
828 * Returns whther or not the associated function is called as a
829 * constructor via "new".
830 */
831 bool IsConstructor() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000832};
833
834
835// --- V a l u e ---
836
837
838/**
839 * The superclass of all JavaScript values and objects.
840 */
Steve Block8defd9f2010-07-08 12:39:36 +0100841class Value : public Data {
Steve Blocka7e24c12009-10-30 11:49:00 +0000842 public:
843
844 /**
845 * Returns true if this value is the undefined value. See ECMA-262
846 * 4.3.10.
847 */
Steve Block8defd9f2010-07-08 12:39:36 +0100848 V8EXPORT bool IsUndefined() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000849
850 /**
851 * Returns true if this value is the null value. See ECMA-262
852 * 4.3.11.
853 */
Steve Block8defd9f2010-07-08 12:39:36 +0100854 V8EXPORT bool IsNull() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000855
856 /**
857 * Returns true if this value is true.
858 */
Steve Block8defd9f2010-07-08 12:39:36 +0100859 V8EXPORT bool IsTrue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000860
861 /**
862 * Returns true if this value is false.
863 */
Steve Block8defd9f2010-07-08 12:39:36 +0100864 V8EXPORT bool IsFalse() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000865
866 /**
867 * Returns true if this value is an instance of the String type.
868 * See ECMA-262 8.4.
869 */
870 inline bool IsString() const;
871
872 /**
873 * Returns true if this value is a function.
874 */
Steve Block8defd9f2010-07-08 12:39:36 +0100875 V8EXPORT bool IsFunction() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000876
877 /**
878 * Returns true if this value is an array.
879 */
Steve Block8defd9f2010-07-08 12:39:36 +0100880 V8EXPORT bool IsArray() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000881
882 /**
883 * Returns true if this value is an object.
884 */
Steve Block8defd9f2010-07-08 12:39:36 +0100885 V8EXPORT bool IsObject() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000886
887 /**
888 * Returns true if this value is boolean.
889 */
Steve Block8defd9f2010-07-08 12:39:36 +0100890 V8EXPORT bool IsBoolean() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000891
892 /**
893 * Returns true if this value is a number.
894 */
Steve Block8defd9f2010-07-08 12:39:36 +0100895 V8EXPORT bool IsNumber() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000896
897 /**
898 * Returns true if this value is external.
899 */
Steve Block8defd9f2010-07-08 12:39:36 +0100900 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000901
902 /**
903 * Returns true if this value is a 32-bit signed integer.
904 */
Steve Block8defd9f2010-07-08 12:39:36 +0100905 V8EXPORT bool IsInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000906
907 /**
Steve Block6ded16b2010-05-10 14:33:55 +0100908 * Returns true if this value is a 32-bit unsigned integer.
909 */
Steve Block8defd9f2010-07-08 12:39:36 +0100910 V8EXPORT bool IsUint32() const;
Steve Block6ded16b2010-05-10 14:33:55 +0100911
912 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000913 * Returns true if this value is a Date.
914 */
Steve Block8defd9f2010-07-08 12:39:36 +0100915 V8EXPORT bool IsDate() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000916
Iain Merrick75681382010-08-19 15:07:18 +0100917 /**
918 * Returns true if this value is a RegExp.
919 */
920 V8EXPORT bool IsRegExp() const;
921
Steve Block8defd9f2010-07-08 12:39:36 +0100922 V8EXPORT Local<Boolean> ToBoolean() const;
923 V8EXPORT Local<Number> ToNumber() const;
924 V8EXPORT Local<String> ToString() const;
925 V8EXPORT Local<String> ToDetailString() const;
926 V8EXPORT Local<Object> ToObject() const;
927 V8EXPORT Local<Integer> ToInteger() const;
928 V8EXPORT Local<Uint32> ToUint32() const;
929 V8EXPORT Local<Int32> ToInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000930
931 /**
932 * Attempts to convert a string to an array index.
933 * Returns an empty handle if the conversion fails.
934 */
Steve Block8defd9f2010-07-08 12:39:36 +0100935 V8EXPORT Local<Uint32> ToArrayIndex() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000936
Steve Block8defd9f2010-07-08 12:39:36 +0100937 V8EXPORT bool BooleanValue() const;
938 V8EXPORT double NumberValue() const;
939 V8EXPORT int64_t IntegerValue() const;
940 V8EXPORT uint32_t Uint32Value() const;
941 V8EXPORT int32_t Int32Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000942
943 /** JS == */
Steve Block8defd9f2010-07-08 12:39:36 +0100944 V8EXPORT bool Equals(Handle<Value> that) const;
945 V8EXPORT bool StrictEquals(Handle<Value> that) const;
Steve Block3ce2e202009-11-05 08:53:23 +0000946
Steve Blocka7e24c12009-10-30 11:49:00 +0000947 private:
948 inline bool QuickIsString() const;
Steve Block8defd9f2010-07-08 12:39:36 +0100949 V8EXPORT bool FullIsString() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000950};
951
952
953/**
954 * The superclass of primitive values. See ECMA-262 4.3.2.
955 */
Steve Block8defd9f2010-07-08 12:39:36 +0100956class Primitive : public Value { };
Steve Blocka7e24c12009-10-30 11:49:00 +0000957
958
959/**
960 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
961 * or false value.
962 */
Steve Block8defd9f2010-07-08 12:39:36 +0100963class Boolean : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000964 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100965 V8EXPORT bool Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000966 static inline Handle<Boolean> New(bool value);
967};
968
969
970/**
971 * A JavaScript string value (ECMA-262, 4.3.17).
972 */
Steve Block8defd9f2010-07-08 12:39:36 +0100973class String : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000974 public:
975
976 /**
977 * Returns the number of characters in this string.
978 */
Steve Block8defd9f2010-07-08 12:39:36 +0100979 V8EXPORT int Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000980
981 /**
982 * Returns the number of bytes in the UTF-8 encoded
983 * representation of this string.
984 */
Steve Block8defd9f2010-07-08 12:39:36 +0100985 V8EXPORT int Utf8Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000986
987 /**
988 * Write the contents of the string to an external buffer.
989 * If no arguments are given, expects the buffer to be large
990 * enough to hold the entire string and NULL terminator. Copies
991 * the contents of the string and the NULL terminator into the
992 * buffer.
993 *
Ben Murdochb0fe1622011-05-05 13:52:32 +0100994 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
995 * before the end of the buffer.
996 *
Steve Blocka7e24c12009-10-30 11:49:00 +0000997 * Copies up to length characters into the output buffer.
998 * Only null-terminates if there is enough space in the buffer.
999 *
1000 * \param buffer The buffer into which the string will be copied.
1001 * \param start The starting position within the string at which
1002 * copying begins.
Ben Murdochb0fe1622011-05-05 13:52:32 +01001003 * \param length The number of characters to copy from the string. For
1004 * WriteUtf8 the number of bytes in the buffer.
Steve Block6ded16b2010-05-10 14:33:55 +01001005 * \param nchars_ref The number of characters written, can be NULL.
1006 * \param hints Various hints that might affect performance of this or
1007 * subsequent operations.
Ben Murdochb0fe1622011-05-05 13:52:32 +01001008 * \return The number of characters copied to the buffer excluding the null
1009 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1010 * including the null terminator.
Steve Blocka7e24c12009-10-30 11:49:00 +00001011 */
Steve Block6ded16b2010-05-10 14:33:55 +01001012 enum WriteHints {
1013 NO_HINTS = 0,
1014 HINT_MANY_WRITES_EXPECTED = 1
1015 };
1016
Steve Block8defd9f2010-07-08 12:39:36 +01001017 V8EXPORT int Write(uint16_t* buffer,
1018 int start = 0,
1019 int length = -1,
1020 WriteHints hints = NO_HINTS) const; // UTF-16
1021 V8EXPORT int WriteAscii(char* buffer,
1022 int start = 0,
1023 int length = -1,
1024 WriteHints hints = NO_HINTS) const; // ASCII
1025 V8EXPORT int WriteUtf8(char* buffer,
1026 int length = -1,
1027 int* nchars_ref = NULL,
1028 WriteHints hints = NO_HINTS) const; // UTF-8
Steve Blocka7e24c12009-10-30 11:49:00 +00001029
1030 /**
1031 * A zero length string.
1032 */
Steve Block8defd9f2010-07-08 12:39:36 +01001033 V8EXPORT static v8::Local<v8::String> Empty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001034
1035 /**
1036 * Returns true if the string is external
1037 */
Steve Block8defd9f2010-07-08 12:39:36 +01001038 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001039
1040 /**
1041 * Returns true if the string is both external and ascii
1042 */
Steve Block8defd9f2010-07-08 12:39:36 +01001043 V8EXPORT bool IsExternalAscii() const;
Leon Clarkee46be812010-01-19 14:06:41 +00001044
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001045 class V8EXPORT ExternalStringResourceBase { // NOLINT
Leon Clarkee46be812010-01-19 14:06:41 +00001046 public:
1047 virtual ~ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001048
Leon Clarkee46be812010-01-19 14:06:41 +00001049 protected:
1050 ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001051
1052 /**
1053 * Internally V8 will call this Dispose method when the external string
1054 * resource is no longer needed. The default implementation will use the
1055 * delete operator. This method can be overridden in subclasses to
1056 * control how allocated external string resources are disposed.
1057 */
1058 virtual void Dispose() { delete this; }
1059
Leon Clarkee46be812010-01-19 14:06:41 +00001060 private:
1061 // Disallow copying and assigning.
1062 ExternalStringResourceBase(const ExternalStringResourceBase&);
1063 void operator=(const ExternalStringResourceBase&);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001064
1065 friend class v8::internal::Heap;
Leon Clarkee46be812010-01-19 14:06:41 +00001066 };
1067
Steve Blocka7e24c12009-10-30 11:49:00 +00001068 /**
1069 * An ExternalStringResource is a wrapper around a two-byte string
1070 * buffer that resides outside V8's heap. Implement an
1071 * ExternalStringResource to manage the life cycle of the underlying
1072 * buffer. Note that the string data must be immutable.
1073 */
Leon Clarkee46be812010-01-19 14:06:41 +00001074 class V8EXPORT ExternalStringResource
1075 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001076 public:
1077 /**
1078 * Override the destructor to manage the life cycle of the underlying
1079 * buffer.
1080 */
1081 virtual ~ExternalStringResource() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001082
1083 /**
1084 * The string data from the underlying buffer.
1085 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001086 virtual const uint16_t* data() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001087
1088 /**
1089 * The length of the string. That is, the number of two-byte characters.
1090 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001091 virtual size_t length() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001092
Steve Blocka7e24c12009-10-30 11:49:00 +00001093 protected:
1094 ExternalStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001095 };
1096
1097 /**
1098 * An ExternalAsciiStringResource is a wrapper around an ascii
1099 * string buffer that resides outside V8's heap. Implement an
1100 * ExternalAsciiStringResource to manage the life cycle of the
1101 * underlying buffer. Note that the string data must be immutable
1102 * and that the data must be strict 7-bit ASCII, not Latin1 or
1103 * UTF-8, which would require special treatment internally in the
1104 * engine and, in the case of UTF-8, do not allow efficient indexing.
1105 * Use String::New or convert to 16 bit data for non-ASCII.
1106 */
1107
Leon Clarkee46be812010-01-19 14:06:41 +00001108 class V8EXPORT ExternalAsciiStringResource
1109 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001110 public:
1111 /**
1112 * Override the destructor to manage the life cycle of the underlying
1113 * buffer.
1114 */
1115 virtual ~ExternalAsciiStringResource() {}
1116 /** The string data from the underlying buffer.*/
1117 virtual const char* data() const = 0;
1118 /** The number of ascii characters in the string.*/
1119 virtual size_t length() const = 0;
1120 protected:
1121 ExternalAsciiStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001122 };
1123
1124 /**
1125 * Get the ExternalStringResource for an external string. Returns
1126 * NULL if IsExternal() doesn't return true.
1127 */
1128 inline ExternalStringResource* GetExternalStringResource() const;
1129
1130 /**
1131 * Get the ExternalAsciiStringResource for an external ascii string.
1132 * Returns NULL if IsExternalAscii() doesn't return true.
1133 */
Steve Block8defd9f2010-07-08 12:39:36 +01001134 V8EXPORT ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001135
1136 static inline String* Cast(v8::Value* obj);
1137
1138 /**
1139 * Allocates a new string from either utf-8 encoded or ascii data.
1140 * The second parameter 'length' gives the buffer length.
1141 * If the data is utf-8 encoded, the caller must
1142 * be careful to supply the length parameter.
1143 * If it is not given, the function calls
1144 * 'strlen' to determine the buffer length, it might be
1145 * wrong if 'data' contains a null character.
1146 */
Steve Block8defd9f2010-07-08 12:39:36 +01001147 V8EXPORT static Local<String> New(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001148
1149 /** Allocates a new string from utf16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001150 V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001151
1152 /** Creates a symbol. Returns one if it exists already.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001153 V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001154
1155 /**
Steve Block3ce2e202009-11-05 08:53:23 +00001156 * Creates a new string by concatenating the left and the right strings
1157 * passed in as parameters.
1158 */
Steve Block8defd9f2010-07-08 12:39:36 +01001159 V8EXPORT static Local<String> Concat(Handle<String> left,
1160 Handle<String>right);
Steve Block3ce2e202009-11-05 08:53:23 +00001161
1162 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001163 * Creates a new external string using the data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001164 * resource. When the external string is no longer live on V8's heap the
1165 * resource will be disposed by calling its Dispose method. The caller of
1166 * this function should not otherwise delete or modify the resource. Neither
1167 * should the underlying buffer be deallocated or modified except through the
1168 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001169 */
Steve Block8defd9f2010-07-08 12:39:36 +01001170 V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001171
1172 /**
1173 * Associate an external string resource with this string by transforming it
1174 * in place so that existing references to this string in the JavaScript heap
1175 * will use the external string resource. The external string resource's
1176 * character contents needs to be equivalent to this string.
1177 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001178 * The string is not modified if the operation fails. See NewExternal for
1179 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001180 */
Steve Block8defd9f2010-07-08 12:39:36 +01001181 V8EXPORT bool MakeExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001182
1183 /**
1184 * Creates a new external string using the ascii data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001185 * resource. When the external string is no longer live on V8's heap the
1186 * resource will be disposed by calling its Dispose method. The caller of
1187 * this function should not otherwise delete or modify the resource. Neither
1188 * should the underlying buffer be deallocated or modified except through the
1189 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001190 */
Steve Block8defd9f2010-07-08 12:39:36 +01001191 V8EXPORT static Local<String> NewExternal(
1192 ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001193
1194 /**
1195 * Associate an external string resource with this string by transforming it
1196 * in place so that existing references to this string in the JavaScript heap
1197 * will use the external string resource. The external string resource's
1198 * character contents needs to be equivalent to this string.
1199 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001200 * The string is not modified if the operation fails. See NewExternal for
1201 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001202 */
Steve Block8defd9f2010-07-08 12:39:36 +01001203 V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001204
1205 /**
1206 * Returns true if this string can be made external.
1207 */
Steve Block8defd9f2010-07-08 12:39:36 +01001208 V8EXPORT bool CanMakeExternal();
Steve Blocka7e24c12009-10-30 11:49:00 +00001209
1210 /** Creates an undetectable string from the supplied ascii or utf-8 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001211 V8EXPORT static Local<String> NewUndetectable(const char* data,
1212 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001213
1214 /** Creates an undetectable string from the supplied utf-16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001215 V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1216 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001217
1218 /**
1219 * Converts an object to a utf8-encoded character array. Useful if
1220 * you want to print the object. If conversion to a string fails
1221 * (eg. due to an exception in the toString() method of the object)
1222 * then the length() method returns 0 and the * operator returns
1223 * NULL.
1224 */
1225 class V8EXPORT Utf8Value {
1226 public:
1227 explicit Utf8Value(Handle<v8::Value> obj);
1228 ~Utf8Value();
1229 char* operator*() { return str_; }
1230 const char* operator*() const { return str_; }
1231 int length() const { return length_; }
1232 private:
1233 char* str_;
1234 int length_;
1235
1236 // Disallow copying and assigning.
1237 Utf8Value(const Utf8Value&);
1238 void operator=(const Utf8Value&);
1239 };
1240
1241 /**
1242 * Converts an object to an ascii string.
1243 * Useful if you want to print the object.
1244 * If conversion to a string fails (eg. due to an exception in the toString()
1245 * method of the object) then the length() method returns 0 and the * operator
1246 * returns NULL.
1247 */
1248 class V8EXPORT AsciiValue {
1249 public:
1250 explicit AsciiValue(Handle<v8::Value> obj);
1251 ~AsciiValue();
1252 char* operator*() { return str_; }
1253 const char* operator*() const { return str_; }
1254 int length() const { return length_; }
1255 private:
1256 char* str_;
1257 int length_;
1258
1259 // Disallow copying and assigning.
1260 AsciiValue(const AsciiValue&);
1261 void operator=(const AsciiValue&);
1262 };
1263
1264 /**
1265 * Converts an object to a two-byte string.
1266 * If conversion to a string fails (eg. due to an exception in the toString()
1267 * method of the object) then the length() method returns 0 and the * operator
1268 * returns NULL.
1269 */
1270 class V8EXPORT Value {
1271 public:
1272 explicit Value(Handle<v8::Value> obj);
1273 ~Value();
1274 uint16_t* operator*() { return str_; }
1275 const uint16_t* operator*() const { return str_; }
1276 int length() const { return length_; }
1277 private:
1278 uint16_t* str_;
1279 int length_;
1280
1281 // Disallow copying and assigning.
1282 Value(const Value&);
1283 void operator=(const Value&);
1284 };
Steve Block3ce2e202009-11-05 08:53:23 +00001285
Steve Blocka7e24c12009-10-30 11:49:00 +00001286 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001287 V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1288 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001289};
1290
1291
1292/**
1293 * A JavaScript number value (ECMA-262, 4.3.20)
1294 */
Steve Block8defd9f2010-07-08 12:39:36 +01001295class Number : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +00001296 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001297 V8EXPORT double Value() const;
1298 V8EXPORT static Local<Number> New(double value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001299 static inline Number* Cast(v8::Value* obj);
1300 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001301 V8EXPORT Number();
Steve Blocka7e24c12009-10-30 11:49:00 +00001302 static void CheckCast(v8::Value* obj);
1303};
1304
1305
1306/**
1307 * A JavaScript value representing a signed integer.
1308 */
Steve Block8defd9f2010-07-08 12:39:36 +01001309class Integer : public Number {
Steve Blocka7e24c12009-10-30 11:49:00 +00001310 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001311 V8EXPORT static Local<Integer> New(int32_t value);
1312 V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1313 V8EXPORT int64_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001314 static inline Integer* Cast(v8::Value* obj);
1315 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001316 V8EXPORT Integer();
1317 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001318};
1319
1320
1321/**
1322 * A JavaScript value representing a 32-bit signed integer.
1323 */
Steve Block8defd9f2010-07-08 12:39:36 +01001324class Int32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001325 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001326 V8EXPORT int32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001327 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001328 V8EXPORT Int32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001329};
1330
1331
1332/**
1333 * A JavaScript value representing a 32-bit unsigned integer.
1334 */
Steve Block8defd9f2010-07-08 12:39:36 +01001335class Uint32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001336 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001337 V8EXPORT uint32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001338 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001339 V8EXPORT Uint32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001340};
1341
1342
1343/**
1344 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1345 */
Steve Block8defd9f2010-07-08 12:39:36 +01001346class Date : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001347 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001348 V8EXPORT static Local<Value> New(double time);
Steve Blocka7e24c12009-10-30 11:49:00 +00001349
1350 /**
1351 * A specialization of Value::NumberValue that is more efficient
1352 * because we know the structure of this object.
1353 */
Steve Block8defd9f2010-07-08 12:39:36 +01001354 V8EXPORT double NumberValue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001355
1356 static inline Date* Cast(v8::Value* obj);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001357
1358 /**
1359 * Notification that the embedder has changed the time zone,
1360 * daylight savings time, or other date / time configuration
1361 * parameters. V8 keeps a cache of various values used for
1362 * date / time computation. This notification will reset
1363 * those cached values for the current context so that date /
1364 * time configuration changes would be reflected in the Date
1365 * object.
1366 *
1367 * This API should not be called more than needed as it will
1368 * negatively impact the performance of date operations.
1369 */
1370 V8EXPORT static void DateTimeConfigurationChangeNotification();
1371
Steve Blocka7e24c12009-10-30 11:49:00 +00001372 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001373 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001374};
1375
1376
Ben Murdochf87a2032010-10-22 12:50:53 +01001377/**
1378 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1379 */
1380class RegExp : public Value {
1381 public:
1382 /**
1383 * Regular expression flag bits. They can be or'ed to enable a set
1384 * of flags.
1385 */
1386 enum Flags {
1387 kNone = 0,
1388 kGlobal = 1,
1389 kIgnoreCase = 2,
1390 kMultiline = 4
1391 };
1392
1393 /**
1394 * Creates a regular expression from the given pattern string and
1395 * the flags bit field. May throw a JavaScript exception as
1396 * described in ECMA-262, 15.10.4.1.
1397 *
1398 * For example,
1399 * RegExp::New(v8::String::New("foo"),
1400 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
1401 * is equivalent to evaluating "/foo/gm".
1402 */
1403 V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1404 Flags flags);
1405
1406 /**
1407 * Returns the value of the source property: a string representing
1408 * the regular expression.
1409 */
1410 V8EXPORT Local<String> GetSource() const;
1411
1412 /**
1413 * Returns the flags bit field.
1414 */
1415 V8EXPORT Flags GetFlags() const;
1416
1417 static inline RegExp* Cast(v8::Value* obj);
1418
1419 private:
1420 V8EXPORT static void CheckCast(v8::Value* obj);
1421};
1422
1423
Steve Blocka7e24c12009-10-30 11:49:00 +00001424enum PropertyAttribute {
1425 None = 0,
1426 ReadOnly = 1 << 0,
1427 DontEnum = 1 << 1,
1428 DontDelete = 1 << 2
1429};
1430
Steve Block3ce2e202009-11-05 08:53:23 +00001431enum ExternalArrayType {
1432 kExternalByteArray = 1,
1433 kExternalUnsignedByteArray,
1434 kExternalShortArray,
1435 kExternalUnsignedShortArray,
1436 kExternalIntArray,
1437 kExternalUnsignedIntArray,
1438 kExternalFloatArray
1439};
1440
Steve Blocka7e24c12009-10-30 11:49:00 +00001441/**
Leon Clarkef7060e22010-06-03 12:02:55 +01001442 * Accessor[Getter|Setter] are used as callback functions when
1443 * setting|getting a particular property. See Object and ObjectTemplate's
1444 * method SetAccessor.
1445 */
1446typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1447 const AccessorInfo& info);
1448
1449
1450typedef void (*AccessorSetter)(Local<String> property,
1451 Local<Value> value,
1452 const AccessorInfo& info);
1453
1454
1455/**
1456 * Access control specifications.
1457 *
1458 * Some accessors should be accessible across contexts. These
1459 * accessors have an explicit access control parameter which specifies
1460 * the kind of cross-context access that should be allowed.
1461 *
1462 * Additionally, for security, accessors can prohibit overwriting by
1463 * accessors defined in JavaScript. For objects that have such
1464 * accessors either locally or in their prototype chain it is not
1465 * possible to overwrite the accessor by using __defineGetter__ or
1466 * __defineSetter__ from JavaScript code.
1467 */
1468enum AccessControl {
1469 DEFAULT = 0,
1470 ALL_CAN_READ = 1,
1471 ALL_CAN_WRITE = 1 << 1,
1472 PROHIBITS_OVERWRITING = 1 << 2
1473};
1474
1475
1476/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001477 * A JavaScript object (ECMA-262, 4.3.3)
1478 */
Steve Block8defd9f2010-07-08 12:39:36 +01001479class Object : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001480 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001481 V8EXPORT bool Set(Handle<Value> key,
1482 Handle<Value> value,
1483 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001484
Steve Block8defd9f2010-07-08 12:39:36 +01001485 V8EXPORT bool Set(uint32_t index,
1486 Handle<Value> value);
Steve Block6ded16b2010-05-10 14:33:55 +01001487
Steve Blocka7e24c12009-10-30 11:49:00 +00001488 // Sets a local property on this object bypassing interceptors and
1489 // overriding accessors or read-only properties.
1490 //
1491 // Note that if the object has an interceptor the property will be set
1492 // locally, but since the interceptor takes precedence the local property
1493 // will only be returned if the interceptor doesn't return a value.
1494 //
1495 // Note also that this only works for named properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001496 V8EXPORT bool ForceSet(Handle<Value> key,
1497 Handle<Value> value,
1498 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001499
Steve Block8defd9f2010-07-08 12:39:36 +01001500 V8EXPORT Local<Value> Get(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001501
Steve Block8defd9f2010-07-08 12:39:36 +01001502 V8EXPORT Local<Value> Get(uint32_t index);
Steve Block6ded16b2010-05-10 14:33:55 +01001503
Steve Blocka7e24c12009-10-30 11:49:00 +00001504 // TODO(1245389): Replace the type-specific versions of these
1505 // functions with generic ones that accept a Handle<Value> key.
Steve Block8defd9f2010-07-08 12:39:36 +01001506 V8EXPORT bool Has(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001507
Steve Block8defd9f2010-07-08 12:39:36 +01001508 V8EXPORT bool Delete(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001509
1510 // Delete a property on this object bypassing interceptors and
1511 // ignoring dont-delete attributes.
Steve Block8defd9f2010-07-08 12:39:36 +01001512 V8EXPORT bool ForceDelete(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001513
Steve Block8defd9f2010-07-08 12:39:36 +01001514 V8EXPORT bool Has(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001515
Steve Block8defd9f2010-07-08 12:39:36 +01001516 V8EXPORT bool Delete(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001517
Steve Block8defd9f2010-07-08 12:39:36 +01001518 V8EXPORT bool SetAccessor(Handle<String> name,
1519 AccessorGetter getter,
1520 AccessorSetter setter = 0,
1521 Handle<Value> data = Handle<Value>(),
1522 AccessControl settings = DEFAULT,
1523 PropertyAttribute attribute = None);
Leon Clarkef7060e22010-06-03 12:02:55 +01001524
Steve Blocka7e24c12009-10-30 11:49:00 +00001525 /**
1526 * Returns an array containing the names of the enumerable properties
1527 * of this object, including properties from prototype objects. The
1528 * array returned by this method contains the same values as would
1529 * be enumerated by a for-in statement over this object.
1530 */
Steve Block8defd9f2010-07-08 12:39:36 +01001531 V8EXPORT Local<Array> GetPropertyNames();
Steve Blocka7e24c12009-10-30 11:49:00 +00001532
1533 /**
1534 * Get the prototype object. This does not skip objects marked to
1535 * be skipped by __proto__ and it does not consult the security
1536 * handler.
1537 */
Steve Block8defd9f2010-07-08 12:39:36 +01001538 V8EXPORT Local<Value> GetPrototype();
Steve Blocka7e24c12009-10-30 11:49:00 +00001539
1540 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00001541 * Set the prototype object. This does not skip objects marked to
1542 * be skipped by __proto__ and it does not consult the security
1543 * handler.
1544 */
Steve Block8defd9f2010-07-08 12:39:36 +01001545 V8EXPORT bool SetPrototype(Handle<Value> prototype);
Andrei Popescu402d9372010-02-26 13:31:12 +00001546
1547 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001548 * Finds an instance of the given function template in the prototype
1549 * chain.
1550 */
Steve Block8defd9f2010-07-08 12:39:36 +01001551 V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1552 Handle<FunctionTemplate> tmpl);
Steve Blocka7e24c12009-10-30 11:49:00 +00001553
1554 /**
1555 * Call builtin Object.prototype.toString on this object.
1556 * This is different from Value::ToString() that may call
1557 * user-defined toString function. This one does not.
1558 */
Steve Block8defd9f2010-07-08 12:39:36 +01001559 V8EXPORT Local<String> ObjectProtoToString();
Steve Blocka7e24c12009-10-30 11:49:00 +00001560
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08001561 /**
1562 * Returns the name of the function invoked as a constructor for this object.
1563 */
1564 V8EXPORT Local<String> GetConstructorName();
1565
Steve Blocka7e24c12009-10-30 11:49:00 +00001566 /** Gets the number of internal fields for this Object. */
Steve Block8defd9f2010-07-08 12:39:36 +01001567 V8EXPORT int InternalFieldCount();
Steve Blocka7e24c12009-10-30 11:49:00 +00001568 /** Gets the value in an internal field. */
1569 inline Local<Value> GetInternalField(int index);
1570 /** Sets the value in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001571 V8EXPORT void SetInternalField(int index, Handle<Value> value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001572
1573 /** Gets a native pointer from an internal field. */
1574 inline void* GetPointerFromInternalField(int index);
Steve Block3ce2e202009-11-05 08:53:23 +00001575
Steve Blocka7e24c12009-10-30 11:49:00 +00001576 /** Sets a native pointer in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001577 V8EXPORT void SetPointerInInternalField(int index, void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001578
1579 // Testers for local properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001580 V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1581 V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1582 V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001583
1584 /**
1585 * If result.IsEmpty() no real property was located in the prototype chain.
1586 * This means interceptors in the prototype chain are not called.
1587 */
Steve Block8defd9f2010-07-08 12:39:36 +01001588 V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1589 Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001590
1591 /**
1592 * If result.IsEmpty() no real property was located on the object or
1593 * in the prototype chain.
1594 * This means interceptors in the prototype chain are not called.
1595 */
Steve Block8defd9f2010-07-08 12:39:36 +01001596 V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001597
1598 /** Tests for a named lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001599 V8EXPORT bool HasNamedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001600
1601 /** Tests for an index lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001602 V8EXPORT bool HasIndexedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001603
1604 /**
1605 * Turns on access check on the object if the object is an instance of
1606 * a template that has access check callbacks. If an object has no
1607 * access check info, the object cannot be accessed by anyone.
1608 */
Steve Block8defd9f2010-07-08 12:39:36 +01001609 V8EXPORT void TurnOnAccessCheck();
Steve Blocka7e24c12009-10-30 11:49:00 +00001610
1611 /**
1612 * Returns the identity hash for this object. The current implemenation uses
1613 * a hidden property on the object to store the identity hash.
1614 *
1615 * The return value will never be 0. Also, it is not guaranteed to be
1616 * unique.
1617 */
Steve Block8defd9f2010-07-08 12:39:36 +01001618 V8EXPORT int GetIdentityHash();
Steve Blocka7e24c12009-10-30 11:49:00 +00001619
1620 /**
1621 * Access hidden properties on JavaScript objects. These properties are
1622 * hidden from the executing JavaScript and only accessible through the V8
1623 * C++ API. Hidden properties introduced by V8 internally (for example the
1624 * identity hash) are prefixed with "v8::".
1625 */
Steve Block8defd9f2010-07-08 12:39:36 +01001626 V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1627 V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1628 V8EXPORT bool DeleteHiddenValue(Handle<String> key);
Steve Block3ce2e202009-11-05 08:53:23 +00001629
Steve Blocka7e24c12009-10-30 11:49:00 +00001630 /**
1631 * Returns true if this is an instance of an api function (one
1632 * created from a function created from a function template) and has
1633 * been modified since it was created. Note that this method is
1634 * conservative and may return true for objects that haven't actually
1635 * been modified.
1636 */
Steve Block8defd9f2010-07-08 12:39:36 +01001637 V8EXPORT bool IsDirty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001638
1639 /**
1640 * Clone this object with a fast but shallow copy. Values will point
1641 * to the same values as the original object.
1642 */
Steve Block8defd9f2010-07-08 12:39:36 +01001643 V8EXPORT Local<Object> Clone();
Steve Blocka7e24c12009-10-30 11:49:00 +00001644
1645 /**
1646 * Set the backing store of the indexed properties to be managed by the
1647 * embedding layer. Access to the indexed properties will follow the rules
1648 * spelled out in CanvasPixelArray.
1649 * Note: The embedding program still owns the data and needs to ensure that
1650 * the backing store is preserved while V8 has a reference.
1651 */
Steve Block8defd9f2010-07-08 12:39:36 +01001652 V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
Steve Block9fac8402011-05-12 15:51:54 +01001653 V8EXPORT bool HasIndexedPropertiesInPixelData();
1654 V8EXPORT uint8_t* GetIndexedPropertiesPixelData();
1655 V8EXPORT int GetIndexedPropertiesPixelDataLength();
Steve Blocka7e24c12009-10-30 11:49:00 +00001656
Steve Block3ce2e202009-11-05 08:53:23 +00001657 /**
1658 * Set the backing store of the indexed properties to be managed by the
1659 * embedding layer. Access to the indexed properties will follow the rules
1660 * spelled out for the CanvasArray subtypes in the WebGL specification.
1661 * Note: The embedding program still owns the data and needs to ensure that
1662 * the backing store is preserved while V8 has a reference.
1663 */
Steve Block8defd9f2010-07-08 12:39:36 +01001664 V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1665 void* data,
1666 ExternalArrayType array_type,
1667 int number_of_elements);
Steve Block9fac8402011-05-12 15:51:54 +01001668 V8EXPORT bool HasIndexedPropertiesInExternalArrayData();
1669 V8EXPORT void* GetIndexedPropertiesExternalArrayData();
1670 V8EXPORT ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1671 V8EXPORT int GetIndexedPropertiesExternalArrayDataLength();
Steve Block3ce2e202009-11-05 08:53:23 +00001672
Steve Block8defd9f2010-07-08 12:39:36 +01001673 V8EXPORT static Local<Object> New();
Steve Blocka7e24c12009-10-30 11:49:00 +00001674 static inline Object* Cast(Value* obj);
1675 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001676 V8EXPORT Object();
1677 V8EXPORT static void CheckCast(Value* obj);
1678 V8EXPORT Local<Value> CheckedGetInternalField(int index);
1679 V8EXPORT void* SlowGetPointerFromInternalField(int index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001680
1681 /**
1682 * If quick access to the internal field is possible this method
Steve Block3ce2e202009-11-05 08:53:23 +00001683 * returns the value. Otherwise an empty handle is returned.
Steve Blocka7e24c12009-10-30 11:49:00 +00001684 */
1685 inline Local<Value> UncheckedGetInternalField(int index);
1686};
1687
1688
1689/**
1690 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1691 */
Steve Block8defd9f2010-07-08 12:39:36 +01001692class Array : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001693 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001694 V8EXPORT uint32_t Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001695
1696 /**
1697 * Clones an element at index |index|. Returns an empty
1698 * handle if cloning fails (for any reason).
1699 */
Steve Block8defd9f2010-07-08 12:39:36 +01001700 V8EXPORT Local<Object> CloneElementAt(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001701
Steve Block8defd9f2010-07-08 12:39:36 +01001702 V8EXPORT static Local<Array> New(int length = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001703 static inline Array* Cast(Value* obj);
1704 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001705 V8EXPORT Array();
Steve Blocka7e24c12009-10-30 11:49:00 +00001706 static void CheckCast(Value* obj);
1707};
1708
1709
1710/**
1711 * A JavaScript function object (ECMA-262, 15.3).
1712 */
Steve Block8defd9f2010-07-08 12:39:36 +01001713class Function : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001714 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001715 V8EXPORT Local<Object> NewInstance() const;
1716 V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1717 V8EXPORT Local<Value> Call(Handle<Object> recv,
1718 int argc,
1719 Handle<Value> argv[]);
1720 V8EXPORT void SetName(Handle<String> name);
1721 V8EXPORT Handle<Value> GetName() const;
Andrei Popescu402d9372010-02-26 13:31:12 +00001722
1723 /**
1724 * Returns zero based line number of function body and
1725 * kLineOffsetNotFound if no information available.
1726 */
Steve Block8defd9f2010-07-08 12:39:36 +01001727 V8EXPORT int GetScriptLineNumber() const;
1728 V8EXPORT ScriptOrigin GetScriptOrigin() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001729 static inline Function* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001730 V8EXPORT static const int kLineOffsetNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00001731 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001732 V8EXPORT Function();
1733 V8EXPORT static void CheckCast(Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001734};
1735
1736
1737/**
1738 * A JavaScript value that wraps a C++ void*. This type of value is
1739 * mainly used to associate C++ data structures with JavaScript
1740 * objects.
1741 *
1742 * The Wrap function V8 will return the most optimal Value object wrapping the
1743 * C++ void*. The type of the value is not guaranteed to be an External object
1744 * and no assumptions about its type should be made. To access the wrapped
1745 * value Unwrap should be used, all other operations on that object will lead
1746 * to unpredictable results.
1747 */
Steve Block8defd9f2010-07-08 12:39:36 +01001748class External : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001749 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001750 V8EXPORT static Local<Value> Wrap(void* data);
Steve Blocka7e24c12009-10-30 11:49:00 +00001751 static inline void* Unwrap(Handle<Value> obj);
1752
Steve Block8defd9f2010-07-08 12:39:36 +01001753 V8EXPORT static Local<External> New(void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001754 static inline External* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001755 V8EXPORT void* Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001756 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001757 V8EXPORT External();
1758 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001759 static inline void* QuickUnwrap(Handle<v8::Value> obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001760 V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001761};
1762
1763
1764// --- T e m p l a t e s ---
1765
1766
1767/**
1768 * The superclass of object and function templates.
1769 */
1770class V8EXPORT Template : public Data {
1771 public:
1772 /** Adds a property to each instance created by this template.*/
1773 void Set(Handle<String> name, Handle<Data> value,
1774 PropertyAttribute attributes = None);
1775 inline void Set(const char* name, Handle<Data> value);
1776 private:
1777 Template();
1778
1779 friend class ObjectTemplate;
1780 friend class FunctionTemplate;
1781};
1782
1783
1784/**
1785 * The argument information given to function call callbacks. This
1786 * class provides access to information about the context of the call,
1787 * including the receiver, the number and values of arguments, and
1788 * the holder of the function.
1789 */
Steve Block8defd9f2010-07-08 12:39:36 +01001790class Arguments {
Steve Blocka7e24c12009-10-30 11:49:00 +00001791 public:
1792 inline int Length() const;
1793 inline Local<Value> operator[](int i) const;
1794 inline Local<Function> Callee() const;
1795 inline Local<Object> This() const;
1796 inline Local<Object> Holder() const;
1797 inline bool IsConstructCall() const;
1798 inline Local<Value> Data() const;
1799 private:
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001800 static const int kDataIndex = 0;
1801 static const int kCalleeIndex = -1;
1802 static const int kHolderIndex = -2;
1803
Steve Blocka7e24c12009-10-30 11:49:00 +00001804 friend class ImplementationUtilities;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001805 inline Arguments(internal::Object** implicit_args,
1806 internal::Object** values,
1807 int length,
1808 bool is_construct_call);
1809 internal::Object** implicit_args_;
1810 internal::Object** values_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001811 int length_;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001812 bool is_construct_call_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001813};
1814
1815
1816/**
1817 * The information passed to an accessor callback about the context
1818 * of the property access.
1819 */
1820class V8EXPORT AccessorInfo {
1821 public:
1822 inline AccessorInfo(internal::Object** args)
1823 : args_(args) { }
1824 inline Local<Value> Data() const;
1825 inline Local<Object> This() const;
1826 inline Local<Object> Holder() const;
1827 private:
1828 internal::Object** args_;
1829};
1830
1831
1832typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
1833
Steve Blocka7e24c12009-10-30 11:49:00 +00001834/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001835 * NamedProperty[Getter|Setter] are used as interceptors on object.
1836 * See ObjectTemplate::SetNamedPropertyHandler.
1837 */
1838typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
1839 const AccessorInfo& info);
1840
1841
1842/**
1843 * Returns the value if the setter intercepts the request.
1844 * Otherwise, returns an empty handle.
1845 */
1846typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
1847 Local<Value> value,
1848 const AccessorInfo& info);
1849
Steve Blocka7e24c12009-10-30 11:49:00 +00001850/**
1851 * Returns a non-empty handle if the interceptor intercepts the request.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001852 * The result is an integer encoding property attributes (like v8::None,
1853 * v8::DontEnum, etc.)
Steve Blocka7e24c12009-10-30 11:49:00 +00001854 */
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001855typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
1856 const AccessorInfo& info);
Steve Blocka7e24c12009-10-30 11:49:00 +00001857
1858
1859/**
1860 * Returns a non-empty handle if the deleter intercepts the request.
1861 * The return value is true if the property could be deleted and false
1862 * otherwise.
1863 */
1864typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
1865 const AccessorInfo& info);
1866
1867/**
1868 * Returns an array containing the names of the properties the named
1869 * property getter intercepts.
1870 */
1871typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
1872
1873
1874/**
1875 * Returns the value of the property if the getter intercepts the
1876 * request. Otherwise, returns an empty handle.
1877 */
1878typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
1879 const AccessorInfo& info);
1880
1881
1882/**
1883 * Returns the value if the setter intercepts the request.
1884 * Otherwise, returns an empty handle.
1885 */
1886typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
1887 Local<Value> value,
1888 const AccessorInfo& info);
1889
1890
1891/**
1892 * Returns a non-empty handle if the interceptor intercepts the request.
Iain Merrick75681382010-08-19 15:07:18 +01001893 * The result is an integer encoding property attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00001894 */
Iain Merrick75681382010-08-19 15:07:18 +01001895typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
Steve Blocka7e24c12009-10-30 11:49:00 +00001896 const AccessorInfo& info);
1897
1898/**
1899 * Returns a non-empty handle if the deleter intercepts the request.
1900 * The return value is true if the property could be deleted and false
1901 * otherwise.
1902 */
1903typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
1904 const AccessorInfo& info);
1905
1906/**
1907 * Returns an array containing the indices of the properties the
1908 * indexed property getter intercepts.
1909 */
1910typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
1911
1912
1913/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001914 * Access type specification.
1915 */
1916enum AccessType {
1917 ACCESS_GET,
1918 ACCESS_SET,
1919 ACCESS_HAS,
1920 ACCESS_DELETE,
1921 ACCESS_KEYS
1922};
1923
1924
1925/**
1926 * Returns true if cross-context access should be allowed to the named
1927 * property with the given key on the host object.
1928 */
1929typedef bool (*NamedSecurityCallback)(Local<Object> host,
1930 Local<Value> key,
1931 AccessType type,
1932 Local<Value> data);
1933
1934
1935/**
1936 * Returns true if cross-context access should be allowed to the indexed
1937 * property with the given index on the host object.
1938 */
1939typedef bool (*IndexedSecurityCallback)(Local<Object> host,
1940 uint32_t index,
1941 AccessType type,
1942 Local<Value> data);
1943
1944
1945/**
1946 * A FunctionTemplate is used to create functions at runtime. There
1947 * can only be one function created from a FunctionTemplate in a
1948 * context. The lifetime of the created function is equal to the
1949 * lifetime of the context. So in case the embedder needs to create
1950 * temporary functions that can be collected using Scripts is
1951 * preferred.
1952 *
1953 * A FunctionTemplate can have properties, these properties are added to the
1954 * function object when it is created.
1955 *
1956 * A FunctionTemplate has a corresponding instance template which is
1957 * used to create object instances when the function is used as a
1958 * constructor. Properties added to the instance template are added to
1959 * each object instance.
1960 *
1961 * A FunctionTemplate can have a prototype template. The prototype template
1962 * is used to create the prototype object of the function.
1963 *
1964 * The following example shows how to use a FunctionTemplate:
1965 *
1966 * \code
1967 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
1968 * t->Set("func_property", v8::Number::New(1));
1969 *
1970 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
1971 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
1972 * proto_t->Set("proto_const", v8::Number::New(2));
1973 *
1974 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
1975 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
1976 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
1977 * instance_t->Set("instance_property", Number::New(3));
1978 *
1979 * v8::Local<v8::Function> function = t->GetFunction();
1980 * v8::Local<v8::Object> instance = function->NewInstance();
1981 * \endcode
1982 *
1983 * Let's use "function" as the JS variable name of the function object
1984 * and "instance" for the instance object created above. The function
1985 * and the instance will have the following properties:
1986 *
1987 * \code
1988 * func_property in function == true;
1989 * function.func_property == 1;
1990 *
1991 * function.prototype.proto_method() invokes 'InvokeCallback'
1992 * function.prototype.proto_const == 2;
1993 *
1994 * instance instanceof function == true;
1995 * instance.instance_accessor calls 'InstanceAccessorCallback'
1996 * instance.instance_property == 3;
1997 * \endcode
1998 *
1999 * A FunctionTemplate can inherit from another one by calling the
2000 * FunctionTemplate::Inherit method. The following graph illustrates
2001 * the semantics of inheritance:
2002 *
2003 * \code
2004 * FunctionTemplate Parent -> Parent() . prototype -> { }
2005 * ^ ^
2006 * | Inherit(Parent) | .__proto__
2007 * | |
2008 * FunctionTemplate Child -> Child() . prototype -> { }
2009 * \endcode
2010 *
2011 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
2012 * object of the Child() function has __proto__ pointing to the
2013 * Parent() function's prototype object. An instance of the Child
2014 * function has all properties on Parent's instance templates.
2015 *
2016 * Let Parent be the FunctionTemplate initialized in the previous
2017 * section and create a Child FunctionTemplate by:
2018 *
2019 * \code
2020 * Local<FunctionTemplate> parent = t;
2021 * Local<FunctionTemplate> child = FunctionTemplate::New();
2022 * child->Inherit(parent);
2023 *
2024 * Local<Function> child_function = child->GetFunction();
2025 * Local<Object> child_instance = child_function->NewInstance();
2026 * \endcode
2027 *
2028 * The Child function and Child instance will have the following
2029 * properties:
2030 *
2031 * \code
2032 * child_func.prototype.__proto__ == function.prototype;
2033 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
2034 * child_instance.instance_property == 3;
2035 * \endcode
2036 */
2037class V8EXPORT FunctionTemplate : public Template {
2038 public:
2039 /** Creates a function template.*/
2040 static Local<FunctionTemplate> New(
2041 InvocationCallback callback = 0,
2042 Handle<Value> data = Handle<Value>(),
2043 Handle<Signature> signature = Handle<Signature>());
2044 /** Returns the unique function instance in the current execution context.*/
2045 Local<Function> GetFunction();
2046
2047 /**
2048 * Set the call-handler callback for a FunctionTemplate. This
2049 * callback is called whenever the function created from this
2050 * FunctionTemplate is called.
2051 */
2052 void SetCallHandler(InvocationCallback callback,
2053 Handle<Value> data = Handle<Value>());
2054
2055 /** Get the InstanceTemplate. */
2056 Local<ObjectTemplate> InstanceTemplate();
2057
2058 /** Causes the function template to inherit from a parent function template.*/
2059 void Inherit(Handle<FunctionTemplate> parent);
2060
2061 /**
2062 * A PrototypeTemplate is the template used to create the prototype object
2063 * of the function created by this template.
2064 */
2065 Local<ObjectTemplate> PrototypeTemplate();
2066
2067
2068 /**
2069 * Set the class name of the FunctionTemplate. This is used for
2070 * printing objects created with the function created from the
2071 * FunctionTemplate as its constructor.
2072 */
2073 void SetClassName(Handle<String> name);
2074
2075 /**
2076 * Determines whether the __proto__ accessor ignores instances of
2077 * the function template. If instances of the function template are
2078 * ignored, __proto__ skips all instances and instead returns the
2079 * next object in the prototype chain.
2080 *
2081 * Call with a value of true to make the __proto__ accessor ignore
2082 * instances of the function template. Call with a value of false
2083 * to make the __proto__ accessor not ignore instances of the
2084 * function template. By default, instances of a function template
2085 * are not ignored.
2086 */
2087 void SetHiddenPrototype(bool value);
2088
2089 /**
2090 * Returns true if the given object is an instance of this function
2091 * template.
2092 */
2093 bool HasInstance(Handle<Value> object);
2094
2095 private:
2096 FunctionTemplate();
2097 void AddInstancePropertyAccessor(Handle<String> name,
2098 AccessorGetter getter,
2099 AccessorSetter setter,
2100 Handle<Value> data,
2101 AccessControl settings,
2102 PropertyAttribute attributes);
2103 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2104 NamedPropertySetter setter,
2105 NamedPropertyQuery query,
2106 NamedPropertyDeleter remover,
2107 NamedPropertyEnumerator enumerator,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002108 Handle<Value> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00002109 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2110 IndexedPropertySetter setter,
2111 IndexedPropertyQuery query,
2112 IndexedPropertyDeleter remover,
2113 IndexedPropertyEnumerator enumerator,
2114 Handle<Value> data);
2115 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2116 Handle<Value> data);
2117
2118 friend class Context;
2119 friend class ObjectTemplate;
2120};
2121
2122
2123/**
2124 * An ObjectTemplate is used to create objects at runtime.
2125 *
2126 * Properties added to an ObjectTemplate are added to each object
2127 * created from the ObjectTemplate.
2128 */
2129class V8EXPORT ObjectTemplate : public Template {
2130 public:
2131 /** Creates an ObjectTemplate. */
2132 static Local<ObjectTemplate> New();
2133
2134 /** Creates a new instance of this template.*/
2135 Local<Object> NewInstance();
2136
2137 /**
2138 * Sets an accessor on the object template.
2139 *
2140 * Whenever the property with the given name is accessed on objects
2141 * created from this ObjectTemplate the getter and setter callbacks
2142 * are called instead of getting and setting the property directly
2143 * on the JavaScript object.
2144 *
2145 * \param name The name of the property for which an accessor is added.
2146 * \param getter The callback to invoke when getting the property.
2147 * \param setter The callback to invoke when setting the property.
2148 * \param data A piece of data that will be passed to the getter and setter
2149 * callbacks whenever they are invoked.
2150 * \param settings Access control settings for the accessor. This is a bit
2151 * field consisting of one of more of
2152 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2153 * The default is to not allow cross-context access.
2154 * ALL_CAN_READ means that all cross-context reads are allowed.
2155 * ALL_CAN_WRITE means that all cross-context writes are allowed.
2156 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2157 * cross-context access.
2158 * \param attribute The attributes of the property for which an accessor
2159 * is added.
2160 */
2161 void SetAccessor(Handle<String> name,
2162 AccessorGetter getter,
2163 AccessorSetter setter = 0,
2164 Handle<Value> data = Handle<Value>(),
2165 AccessControl settings = DEFAULT,
2166 PropertyAttribute attribute = None);
2167
2168 /**
2169 * Sets a named property handler on the object template.
2170 *
2171 * Whenever a named property is accessed on objects created from
2172 * this object template, the provided callback is invoked instead of
2173 * accessing the property directly on the JavaScript object.
2174 *
2175 * \param getter The callback to invoke when getting a property.
2176 * \param setter The callback to invoke when setting a property.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002177 * \param query The callback to invoke to check if a property is present,
2178 * and if present, get its attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00002179 * \param deleter The callback to invoke when deleting a property.
2180 * \param enumerator The callback to invoke to enumerate all the named
2181 * properties of an object.
2182 * \param data A piece of data that will be passed to the callbacks
2183 * whenever they are invoked.
2184 */
2185 void SetNamedPropertyHandler(NamedPropertyGetter getter,
2186 NamedPropertySetter setter = 0,
2187 NamedPropertyQuery query = 0,
2188 NamedPropertyDeleter deleter = 0,
2189 NamedPropertyEnumerator enumerator = 0,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002190 Handle<Value> data = Handle<Value>());
Steve Blocka7e24c12009-10-30 11:49:00 +00002191
2192 /**
2193 * Sets an indexed property handler on the object template.
2194 *
2195 * Whenever an indexed property is accessed on objects created from
2196 * this object template, the provided callback is invoked instead of
2197 * accessing the property directly on the JavaScript object.
2198 *
2199 * \param getter The callback to invoke when getting a property.
2200 * \param setter The callback to invoke when setting a property.
2201 * \param query The callback to invoke to check is an object has a property.
2202 * \param deleter The callback to invoke when deleting a property.
2203 * \param enumerator The callback to invoke to enumerate all the indexed
2204 * properties of an object.
2205 * \param data A piece of data that will be passed to the callbacks
2206 * whenever they are invoked.
2207 */
2208 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2209 IndexedPropertySetter setter = 0,
2210 IndexedPropertyQuery query = 0,
2211 IndexedPropertyDeleter deleter = 0,
2212 IndexedPropertyEnumerator enumerator = 0,
2213 Handle<Value> data = Handle<Value>());
Iain Merrick75681382010-08-19 15:07:18 +01002214
Steve Blocka7e24c12009-10-30 11:49:00 +00002215 /**
2216 * Sets the callback to be used when calling instances created from
2217 * this template as a function. If no callback is set, instances
2218 * behave like normal JavaScript objects that cannot be called as a
2219 * function.
2220 */
2221 void SetCallAsFunctionHandler(InvocationCallback callback,
2222 Handle<Value> data = Handle<Value>());
2223
2224 /**
2225 * Mark object instances of the template as undetectable.
2226 *
2227 * In many ways, undetectable objects behave as though they are not
2228 * there. They behave like 'undefined' in conditionals and when
2229 * printed. However, properties can be accessed and called as on
2230 * normal objects.
2231 */
2232 void MarkAsUndetectable();
2233
2234 /**
2235 * Sets access check callbacks on the object template.
2236 *
2237 * When accessing properties on instances of this object template,
2238 * the access check callback will be called to determine whether or
2239 * not to allow cross-context access to the properties.
2240 * The last parameter specifies whether access checks are turned
2241 * on by default on instances. If access checks are off by default,
2242 * they can be turned on on individual instances by calling
2243 * Object::TurnOnAccessCheck().
2244 */
2245 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2246 IndexedSecurityCallback indexed_handler,
2247 Handle<Value> data = Handle<Value>(),
2248 bool turned_on_by_default = true);
2249
2250 /**
2251 * Gets the number of internal fields for objects generated from
2252 * this template.
2253 */
2254 int InternalFieldCount();
2255
2256 /**
2257 * Sets the number of internal fields for objects generated from
2258 * this template.
2259 */
2260 void SetInternalFieldCount(int value);
2261
2262 private:
2263 ObjectTemplate();
2264 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2265 friend class FunctionTemplate;
2266};
2267
2268
2269/**
2270 * A Signature specifies which receivers and arguments a function can
2271 * legally be called with.
2272 */
2273class V8EXPORT Signature : public Data {
2274 public:
2275 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2276 Handle<FunctionTemplate>(),
2277 int argc = 0,
2278 Handle<FunctionTemplate> argv[] = 0);
2279 private:
2280 Signature();
2281};
2282
2283
2284/**
2285 * A utility for determining the type of objects based on the template
2286 * they were constructed from.
2287 */
2288class V8EXPORT TypeSwitch : public Data {
2289 public:
2290 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2291 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2292 int match(Handle<Value> value);
2293 private:
2294 TypeSwitch();
2295};
2296
2297
2298// --- E x t e n s i o n s ---
2299
2300
2301/**
2302 * Ignore
2303 */
2304class V8EXPORT Extension { // NOLINT
2305 public:
2306 Extension(const char* name,
2307 const char* source = 0,
2308 int dep_count = 0,
2309 const char** deps = 0);
2310 virtual ~Extension() { }
2311 virtual v8::Handle<v8::FunctionTemplate>
2312 GetNativeFunction(v8::Handle<v8::String> name) {
2313 return v8::Handle<v8::FunctionTemplate>();
2314 }
2315
2316 const char* name() { return name_; }
2317 const char* source() { return source_; }
2318 int dependency_count() { return dep_count_; }
2319 const char** dependencies() { return deps_; }
2320 void set_auto_enable(bool value) { auto_enable_ = value; }
2321 bool auto_enable() { return auto_enable_; }
2322
2323 private:
2324 const char* name_;
2325 const char* source_;
2326 int dep_count_;
2327 const char** deps_;
2328 bool auto_enable_;
2329
2330 // Disallow copying and assigning.
2331 Extension(const Extension&);
2332 void operator=(const Extension&);
2333};
2334
2335
2336void V8EXPORT RegisterExtension(Extension* extension);
2337
2338
2339/**
2340 * Ignore
2341 */
2342class V8EXPORT DeclareExtension {
2343 public:
2344 inline DeclareExtension(Extension* extension) {
2345 RegisterExtension(extension);
2346 }
2347};
2348
2349
2350// --- S t a t i c s ---
2351
2352
2353Handle<Primitive> V8EXPORT Undefined();
2354Handle<Primitive> V8EXPORT Null();
2355Handle<Boolean> V8EXPORT True();
2356Handle<Boolean> V8EXPORT False();
2357
2358
2359/**
2360 * A set of constraints that specifies the limits of the runtime's memory use.
2361 * You must set the heap size before initializing the VM - the size cannot be
2362 * adjusted after the VM is initialized.
2363 *
2364 * If you are using threads then you should hold the V8::Locker lock while
2365 * setting the stack limit and you must set a non-default stack limit separately
2366 * for each thread.
2367 */
2368class V8EXPORT ResourceConstraints {
2369 public:
2370 ResourceConstraints();
2371 int max_young_space_size() const { return max_young_space_size_; }
2372 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2373 int max_old_space_size() const { return max_old_space_size_; }
2374 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
Russell Brenner90bac252010-11-18 13:33:46 -08002375 int max_executable_size() { return max_executable_size_; }
2376 void set_max_executable_size(int value) { max_executable_size_ = value; }
Steve Blocka7e24c12009-10-30 11:49:00 +00002377 uint32_t* stack_limit() const { return stack_limit_; }
2378 // Sets an address beyond which the VM's stack may not grow.
2379 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2380 private:
2381 int max_young_space_size_;
2382 int max_old_space_size_;
Russell Brenner90bac252010-11-18 13:33:46 -08002383 int max_executable_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002384 uint32_t* stack_limit_;
2385};
2386
2387
Kristian Monsen25f61362010-05-21 11:50:48 +01002388bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
Steve Blocka7e24c12009-10-30 11:49:00 +00002389
2390
2391// --- E x c e p t i o n s ---
2392
2393
2394typedef void (*FatalErrorCallback)(const char* location, const char* message);
2395
2396
2397typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2398
2399
2400/**
2401 * Schedules an exception to be thrown when returning to JavaScript. When an
2402 * exception has been scheduled it is illegal to invoke any JavaScript
2403 * operation; the caller must return immediately and only after the exception
2404 * has been handled does it become legal to invoke JavaScript operations.
2405 */
2406Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2407
2408/**
2409 * Create new error objects by calling the corresponding error object
2410 * constructor with the message.
2411 */
2412class V8EXPORT Exception {
2413 public:
2414 static Local<Value> RangeError(Handle<String> message);
2415 static Local<Value> ReferenceError(Handle<String> message);
2416 static Local<Value> SyntaxError(Handle<String> message);
2417 static Local<Value> TypeError(Handle<String> message);
2418 static Local<Value> Error(Handle<String> message);
2419};
2420
2421
2422// --- C o u n t e r s C a l l b a c k s ---
2423
2424typedef int* (*CounterLookupCallback)(const char* name);
2425
2426typedef void* (*CreateHistogramCallback)(const char* name,
2427 int min,
2428 int max,
2429 size_t buckets);
2430
2431typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2432
Iain Merrick9ac36c92010-09-13 15:29:50 +01002433// --- M e m o r y A l l o c a t i o n C a l l b a c k ---
2434 enum ObjectSpace {
2435 kObjectSpaceNewSpace = 1 << 0,
2436 kObjectSpaceOldPointerSpace = 1 << 1,
2437 kObjectSpaceOldDataSpace = 1 << 2,
2438 kObjectSpaceCodeSpace = 1 << 3,
2439 kObjectSpaceMapSpace = 1 << 4,
2440 kObjectSpaceLoSpace = 1 << 5,
2441
2442 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2443 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2444 kObjectSpaceLoSpace
2445 };
2446
2447 enum AllocationAction {
2448 kAllocationActionAllocate = 1 << 0,
2449 kAllocationActionFree = 1 << 1,
2450 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2451 };
2452
2453typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2454 AllocationAction action,
2455 int size);
2456
Steve Blocka7e24c12009-10-30 11:49:00 +00002457// --- F a i l e d A c c e s s C h e c k C a l l b a c k ---
2458typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2459 AccessType type,
2460 Local<Value> data);
2461
2462// --- G a r b a g e C o l l e c t i o n C a l l b a c k s
2463
2464/**
Steve Block6ded16b2010-05-10 14:33:55 +01002465 * Applications can register callback functions which will be called
2466 * before and after a garbage collection. Allocations are not
2467 * allowed in the callback functions, you therefore cannot manipulate
Steve Blocka7e24c12009-10-30 11:49:00 +00002468 * objects (set or delete properties for example) since it is possible
2469 * such operations will result in the allocation of objects.
2470 */
Steve Block6ded16b2010-05-10 14:33:55 +01002471enum GCType {
2472 kGCTypeScavenge = 1 << 0,
2473 kGCTypeMarkSweepCompact = 1 << 1,
2474 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2475};
2476
2477enum GCCallbackFlags {
2478 kNoGCCallbackFlags = 0,
2479 kGCCallbackFlagCompacted = 1 << 0
2480};
2481
2482typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2483typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2484
Steve Blocka7e24c12009-10-30 11:49:00 +00002485typedef void (*GCCallback)();
2486
2487
Steve Blocka7e24c12009-10-30 11:49:00 +00002488/**
2489 * Profiler modules.
2490 *
2491 * In V8, profiler consists of several modules: CPU profiler, and different
2492 * kinds of heap profiling. Each can be turned on / off independently.
2493 * When PROFILER_MODULE_HEAP_SNAPSHOT flag is passed to ResumeProfilerEx,
2494 * modules are enabled only temporarily for making a snapshot of the heap.
2495 */
2496enum ProfilerModules {
2497 PROFILER_MODULE_NONE = 0,
2498 PROFILER_MODULE_CPU = 1,
2499 PROFILER_MODULE_HEAP_STATS = 1 << 1,
2500 PROFILER_MODULE_JS_CONSTRUCTORS = 1 << 2,
2501 PROFILER_MODULE_HEAP_SNAPSHOT = 1 << 16
2502};
2503
2504
2505/**
Steve Block3ce2e202009-11-05 08:53:23 +00002506 * Collection of V8 heap information.
2507 *
2508 * Instances of this class can be passed to v8::V8::HeapStatistics to
2509 * get heap statistics from V8.
2510 */
2511class V8EXPORT HeapStatistics {
2512 public:
2513 HeapStatistics();
2514 size_t total_heap_size() { return total_heap_size_; }
Russell Brenner90bac252010-11-18 13:33:46 -08002515 size_t total_heap_size_executable() { return total_heap_size_executable_; }
Steve Block3ce2e202009-11-05 08:53:23 +00002516 size_t used_heap_size() { return used_heap_size_; }
Ben Murdochb8e0da22011-05-16 14:20:40 +01002517 size_t heap_size_limit() { return heap_size_limit_; }
Steve Block3ce2e202009-11-05 08:53:23 +00002518
2519 private:
2520 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
Russell Brenner90bac252010-11-18 13:33:46 -08002521 void set_total_heap_size_executable(size_t size) {
2522 total_heap_size_executable_ = size;
2523 }
Steve Block3ce2e202009-11-05 08:53:23 +00002524 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
Ben Murdochb8e0da22011-05-16 14:20:40 +01002525 void set_heap_size_limit(size_t size) { heap_size_limit_ = size; }
Steve Block3ce2e202009-11-05 08:53:23 +00002526
2527 size_t total_heap_size_;
Russell Brenner90bac252010-11-18 13:33:46 -08002528 size_t total_heap_size_executable_;
Steve Block3ce2e202009-11-05 08:53:23 +00002529 size_t used_heap_size_;
Ben Murdochb8e0da22011-05-16 14:20:40 +01002530 size_t heap_size_limit_;
Steve Block3ce2e202009-11-05 08:53:23 +00002531
2532 friend class V8;
2533};
2534
2535
2536/**
Steve Blocka7e24c12009-10-30 11:49:00 +00002537 * Container class for static utility functions.
2538 */
2539class V8EXPORT V8 {
2540 public:
2541 /** Set the callback to invoke in case of fatal errors. */
2542 static void SetFatalErrorHandler(FatalErrorCallback that);
2543
2544 /**
2545 * Ignore out-of-memory exceptions.
2546 *
2547 * V8 running out of memory is treated as a fatal error by default.
2548 * This means that the fatal error handler is called and that V8 is
2549 * terminated.
2550 *
2551 * IgnoreOutOfMemoryException can be used to not treat a
2552 * out-of-memory situation as a fatal error. This way, the contexts
2553 * that did not cause the out of memory problem might be able to
2554 * continue execution.
2555 */
2556 static void IgnoreOutOfMemoryException();
2557
2558 /**
2559 * Check if V8 is dead and therefore unusable. This is the case after
2560 * fatal errors such as out-of-memory situations.
2561 */
2562 static bool IsDead();
2563
2564 /**
2565 * Adds a message listener.
2566 *
2567 * The same message listener can be added more than once and it that
2568 * case it will be called more than once for each message.
2569 */
2570 static bool AddMessageListener(MessageCallback that,
2571 Handle<Value> data = Handle<Value>());
2572
2573 /**
2574 * Remove all message listeners from the specified callback function.
2575 */
2576 static void RemoveMessageListeners(MessageCallback that);
2577
2578 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002579 * Tells V8 to capture current stack trace when uncaught exception occurs
2580 * and report it to the message listeners. The option is off by default.
2581 */
2582 static void SetCaptureStackTraceForUncaughtExceptions(
2583 bool capture,
2584 int frame_limit = 10,
2585 StackTrace::StackTraceOptions options = StackTrace::kOverview);
2586
2587 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002588 * Sets V8 flags from a string.
2589 */
2590 static void SetFlagsFromString(const char* str, int length);
2591
2592 /**
2593 * Sets V8 flags from the command line.
2594 */
2595 static void SetFlagsFromCommandLine(int* argc,
2596 char** argv,
2597 bool remove_flags);
2598
2599 /** Get the version string. */
2600 static const char* GetVersion();
2601
2602 /**
2603 * Enables the host application to provide a mechanism for recording
2604 * statistics counters.
2605 */
2606 static void SetCounterFunction(CounterLookupCallback);
2607
2608 /**
2609 * Enables the host application to provide a mechanism for recording
2610 * histograms. The CreateHistogram function returns a
2611 * histogram which will later be passed to the AddHistogramSample
2612 * function.
2613 */
2614 static void SetCreateHistogramFunction(CreateHistogramCallback);
2615 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
2616
2617 /**
2618 * Enables the computation of a sliding window of states. The sliding
2619 * window information is recorded in statistics counters.
2620 */
2621 static void EnableSlidingStateWindow();
2622
2623 /** Callback function for reporting failed access checks.*/
2624 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
2625
2626 /**
2627 * Enables the host application to receive a notification before a
Steve Block6ded16b2010-05-10 14:33:55 +01002628 * garbage collection. Allocations are not allowed in the
2629 * callback function, you therefore cannot manipulate objects (set
2630 * or delete properties for example) since it is possible such
2631 * operations will result in the allocation of objects. It is possible
2632 * to specify the GCType filter for your callback. But it is not possible to
2633 * register the same callback function two times with different
2634 * GCType filters.
2635 */
2636 static void AddGCPrologueCallback(
2637 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
2638
2639 /**
2640 * This function removes callback which was installed by
2641 * AddGCPrologueCallback function.
2642 */
2643 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
2644
2645 /**
2646 * The function is deprecated. Please use AddGCPrologueCallback instead.
2647 * Enables the host application to receive a notification before a
2648 * garbage collection. Allocations are not allowed in the
Steve Blocka7e24c12009-10-30 11:49:00 +00002649 * callback function, you therefore cannot manipulate objects (set
2650 * or delete properties for example) since it is possible such
2651 * operations will result in the allocation of objects.
2652 */
2653 static void SetGlobalGCPrologueCallback(GCCallback);
2654
2655 /**
2656 * Enables the host application to receive a notification after a
Steve Block6ded16b2010-05-10 14:33:55 +01002657 * garbage collection. Allocations are not allowed in the
2658 * callback function, you therefore cannot manipulate objects (set
2659 * or delete properties for example) since it is possible such
2660 * operations will result in the allocation of objects. It is possible
2661 * to specify the GCType filter for your callback. But it is not possible to
2662 * register the same callback function two times with different
2663 * GCType filters.
2664 */
2665 static void AddGCEpilogueCallback(
2666 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
2667
2668 /**
2669 * This function removes callback which was installed by
2670 * AddGCEpilogueCallback function.
2671 */
2672 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
2673
2674 /**
2675 * The function is deprecated. Please use AddGCEpilogueCallback instead.
2676 * Enables the host application to receive a notification after a
Steve Blocka7e24c12009-10-30 11:49:00 +00002677 * major garbage collection. Allocations are not allowed in the
2678 * callback function, you therefore cannot manipulate objects (set
2679 * or delete properties for example) since it is possible such
2680 * operations will result in the allocation of objects.
2681 */
2682 static void SetGlobalGCEpilogueCallback(GCCallback);
2683
2684 /**
Iain Merrick9ac36c92010-09-13 15:29:50 +01002685 * Enables the host application to provide a mechanism to be notified
2686 * and perform custom logging when V8 Allocates Executable Memory.
2687 */
2688 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
2689 ObjectSpace space,
2690 AllocationAction action);
2691
2692 /**
2693 * This function removes callback which was installed by
2694 * AddMemoryAllocationCallback function.
2695 */
2696 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
2697
2698 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002699 * Allows the host application to group objects together. If one
2700 * object in the group is alive, all objects in the group are alive.
2701 * After each garbage collection, object groups are removed. It is
2702 * intended to be used in the before-garbage-collection callback
2703 * function, for instance to simulate DOM tree connections among JS
2704 * wrapper objects.
2705 */
2706 static void AddObjectGroup(Persistent<Value>* objects, size_t length);
2707
2708 /**
2709 * Initializes from snapshot if possible. Otherwise, attempts to
2710 * initialize from scratch. This function is called implicitly if
2711 * you use the API without calling it first.
2712 */
2713 static bool Initialize();
2714
2715 /**
2716 * Adjusts the amount of registered external memory. Used to give
2717 * V8 an indication of the amount of externally allocated memory
2718 * that is kept alive by JavaScript objects. V8 uses this to decide
2719 * when to perform global garbage collections. Registering
2720 * externally allocated memory will trigger global garbage
2721 * collections more often than otherwise in an attempt to garbage
2722 * collect the JavaScript objects keeping the externally allocated
2723 * memory alive.
2724 *
2725 * \param change_in_bytes the change in externally allocated memory
2726 * that is kept alive by JavaScript objects.
2727 * \returns the adjusted value.
2728 */
2729 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
2730
2731 /**
2732 * Suspends recording of tick samples in the profiler.
2733 * When the V8 profiling mode is enabled (usually via command line
2734 * switches) this function suspends recording of tick samples.
2735 * Profiling ticks are discarded until ResumeProfiler() is called.
2736 *
2737 * See also the --prof and --prof_auto command line switches to
2738 * enable V8 profiling.
2739 */
2740 static void PauseProfiler();
2741
2742 /**
2743 * Resumes recording of tick samples in the profiler.
2744 * See also PauseProfiler().
2745 */
2746 static void ResumeProfiler();
2747
2748 /**
2749 * Return whether profiler is currently paused.
2750 */
2751 static bool IsProfilerPaused();
2752
2753 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002754 * Resumes specified profiler modules. Can be called several times to
2755 * mark the opening of a profiler events block with the given tag.
2756 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002757 * "ResumeProfiler" is equivalent to "ResumeProfilerEx(PROFILER_MODULE_CPU)".
2758 * See ProfilerModules enum.
2759 *
2760 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002761 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002762 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002763 static void ResumeProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002764
2765 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002766 * Pauses specified profiler modules. Each call to "PauseProfilerEx" closes
2767 * a block of profiler events opened by a call to "ResumeProfilerEx" with the
2768 * same tag value. There is no need for blocks to be properly nested.
2769 * The profiler is paused when the last opened block is closed.
2770 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002771 * "PauseProfiler" is equivalent to "PauseProfilerEx(PROFILER_MODULE_CPU)".
2772 * See ProfilerModules enum.
2773 *
2774 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002775 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002776 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002777 static void PauseProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002778
2779 /**
2780 * Returns active (resumed) profiler modules.
2781 * See ProfilerModules enum.
2782 *
2783 * \returns active profiler modules.
2784 */
2785 static int GetActiveProfilerModules();
2786
2787 /**
2788 * If logging is performed into a memory buffer (via --logfile=*), allows to
2789 * retrieve previously written messages. This can be used for retrieving
2790 * profiler log data in the application. This function is thread-safe.
2791 *
2792 * Caller provides a destination buffer that must exist during GetLogLines
2793 * call. Only whole log lines are copied into the buffer.
2794 *
2795 * \param from_pos specified a point in a buffer to read from, 0 is the
2796 * beginning of a buffer. It is assumed that caller updates its current
2797 * position using returned size value from the previous call.
2798 * \param dest_buf destination buffer for log data.
2799 * \param max_size size of the destination buffer.
2800 * \returns actual size of log data copied into buffer.
2801 */
2802 static int GetLogLines(int from_pos, char* dest_buf, int max_size);
2803
2804 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002805 * The minimum allowed size for a log lines buffer. If the size of
2806 * the buffer given will not be enough to hold a line of the maximum
2807 * length, an attempt to find a log line end in GetLogLines will
2808 * fail, and an empty result will be returned.
2809 */
2810 static const int kMinimumSizeForLogLinesBuffer = 2048;
2811
2812 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002813 * Retrieve the V8 thread id of the calling thread.
2814 *
2815 * The thread id for a thread should only be retrieved after the V8
2816 * lock has been acquired with a Locker object with that thread.
2817 */
2818 static int GetCurrentThreadId();
2819
2820 /**
2821 * Forcefully terminate execution of a JavaScript thread. This can
2822 * be used to terminate long-running scripts.
2823 *
2824 * TerminateExecution should only be called when then V8 lock has
2825 * been acquired with a Locker object. Therefore, in order to be
2826 * able to terminate long-running threads, preemption must be
2827 * enabled to allow the user of TerminateExecution to acquire the
2828 * lock.
2829 *
2830 * The termination is achieved by throwing an exception that is
2831 * uncatchable by JavaScript exception handlers. Termination
2832 * exceptions act as if they were caught by a C++ TryCatch exception
2833 * handlers. If forceful termination is used, any C++ TryCatch
2834 * exception handler that catches an exception should check if that
2835 * exception is a termination exception and immediately return if
2836 * that is the case. Returning immediately in that case will
2837 * continue the propagation of the termination exception if needed.
2838 *
2839 * The thread id passed to TerminateExecution must have been
2840 * obtained by calling GetCurrentThreadId on the thread in question.
2841 *
2842 * \param thread_id The thread id of the thread to terminate.
2843 */
2844 static void TerminateExecution(int thread_id);
2845
2846 /**
2847 * Forcefully terminate the current thread of JavaScript execution.
2848 *
2849 * This method can be used by any thread even if that thread has not
2850 * acquired the V8 lock with a Locker object.
2851 */
2852 static void TerminateExecution();
2853
2854 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002855 * Is V8 terminating JavaScript execution.
2856 *
2857 * Returns true if JavaScript execution is currently terminating
2858 * because of a call to TerminateExecution. In that case there are
2859 * still JavaScript frames on the stack and the termination
2860 * exception is still active.
2861 */
2862 static bool IsExecutionTerminating();
2863
2864 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002865 * Releases any resources used by v8 and stops any utility threads
2866 * that may be running. Note that disposing v8 is permanent, it
2867 * cannot be reinitialized.
2868 *
2869 * It should generally not be necessary to dispose v8 before exiting
2870 * a process, this should happen automatically. It is only necessary
2871 * to use if the process needs the resources taken up by v8.
2872 */
2873 static bool Dispose();
2874
Steve Block3ce2e202009-11-05 08:53:23 +00002875 /**
2876 * Get statistics about the heap memory usage.
2877 */
2878 static void GetHeapStatistics(HeapStatistics* heap_statistics);
Steve Blocka7e24c12009-10-30 11:49:00 +00002879
2880 /**
2881 * Optional notification that the embedder is idle.
2882 * V8 uses the notification to reduce memory footprint.
2883 * This call can be used repeatedly if the embedder remains idle.
Steve Blocka7e24c12009-10-30 11:49:00 +00002884 * Returns true if the embedder should stop calling IdleNotification
2885 * until real work has been done. This indicates that V8 has done
2886 * as much cleanup as it will be able to do.
2887 */
Steve Block3ce2e202009-11-05 08:53:23 +00002888 static bool IdleNotification();
Steve Blocka7e24c12009-10-30 11:49:00 +00002889
2890 /**
2891 * Optional notification that the system is running low on memory.
2892 * V8 uses these notifications to attempt to free memory.
2893 */
2894 static void LowMemoryNotification();
2895
Steve Block6ded16b2010-05-10 14:33:55 +01002896 /**
2897 * Optional notification that a context has been disposed. V8 uses
2898 * these notifications to guide the GC heuristic. Returns the number
2899 * of context disposals - including this one - since the last time
2900 * V8 had a chance to clean up.
2901 */
2902 static int ContextDisposedNotification();
2903
Steve Blocka7e24c12009-10-30 11:49:00 +00002904 private:
2905 V8();
2906
2907 static internal::Object** GlobalizeReference(internal::Object** handle);
2908 static void DisposeGlobal(internal::Object** global_handle);
2909 static void MakeWeak(internal::Object** global_handle,
2910 void* data,
2911 WeakReferenceCallback);
2912 static void ClearWeak(internal::Object** global_handle);
2913 static bool IsGlobalNearDeath(internal::Object** global_handle);
2914 static bool IsGlobalWeak(internal::Object** global_handle);
2915
2916 template <class T> friend class Handle;
2917 template <class T> friend class Local;
2918 template <class T> friend class Persistent;
2919 friend class Context;
2920};
2921
2922
2923/**
2924 * An external exception handler.
2925 */
2926class V8EXPORT TryCatch {
2927 public:
2928
2929 /**
2930 * Creates a new try/catch block and registers it with v8.
2931 */
2932 TryCatch();
2933
2934 /**
2935 * Unregisters and deletes this try/catch block.
2936 */
2937 ~TryCatch();
2938
2939 /**
2940 * Returns true if an exception has been caught by this try/catch block.
2941 */
2942 bool HasCaught() const;
2943
2944 /**
2945 * For certain types of exceptions, it makes no sense to continue
2946 * execution.
2947 *
2948 * Currently, the only type of exception that can be caught by a
2949 * TryCatch handler and for which it does not make sense to continue
2950 * is termination exception. Such exceptions are thrown when the
2951 * TerminateExecution methods are called to terminate a long-running
2952 * script.
2953 *
2954 * If CanContinue returns false, the correct action is to perform
2955 * any C++ cleanup needed and then return.
2956 */
2957 bool CanContinue() const;
2958
2959 /**
Steve Blockd0582a62009-12-15 09:54:21 +00002960 * Throws the exception caught by this TryCatch in a way that avoids
2961 * it being caught again by this same TryCatch. As with ThrowException
2962 * it is illegal to execute any JavaScript operations after calling
2963 * ReThrow; the caller must return immediately to where the exception
2964 * is caught.
2965 */
2966 Handle<Value> ReThrow();
2967
2968 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002969 * Returns the exception caught by this try/catch block. If no exception has
2970 * been caught an empty handle is returned.
2971 *
2972 * The returned handle is valid until this TryCatch block has been destroyed.
2973 */
2974 Local<Value> Exception() const;
2975
2976 /**
2977 * Returns the .stack property of the thrown object. If no .stack
2978 * property is present an empty handle is returned.
2979 */
2980 Local<Value> StackTrace() const;
2981
2982 /**
2983 * Returns the message associated with this exception. If there is
2984 * no message associated an empty handle is returned.
2985 *
2986 * The returned handle is valid until this TryCatch block has been
2987 * destroyed.
2988 */
2989 Local<v8::Message> Message() const;
2990
2991 /**
2992 * Clears any exceptions that may have been caught by this try/catch block.
2993 * After this method has been called, HasCaught() will return false.
2994 *
2995 * It is not necessary to clear a try/catch block before using it again; if
2996 * another exception is thrown the previously caught exception will just be
2997 * overwritten. However, it is often a good idea since it makes it easier
2998 * to determine which operation threw a given exception.
2999 */
3000 void Reset();
3001
3002 /**
3003 * Set verbosity of the external exception handler.
3004 *
3005 * By default, exceptions that are caught by an external exception
3006 * handler are not reported. Call SetVerbose with true on an
3007 * external exception handler to have exceptions caught by the
3008 * handler reported as if they were not caught.
3009 */
3010 void SetVerbose(bool value);
3011
3012 /**
3013 * Set whether or not this TryCatch should capture a Message object
3014 * which holds source information about where the exception
3015 * occurred. True by default.
3016 */
3017 void SetCaptureMessage(bool value);
3018
Steve Blockd0582a62009-12-15 09:54:21 +00003019 private:
3020 void* next_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003021 void* exception_;
3022 void* message_;
Steve Blockd0582a62009-12-15 09:54:21 +00003023 bool is_verbose_ : 1;
3024 bool can_continue_ : 1;
3025 bool capture_message_ : 1;
3026 bool rethrow_ : 1;
3027
3028 friend class v8::internal::Top;
Steve Blocka7e24c12009-10-30 11:49:00 +00003029};
3030
3031
3032// --- C o n t e x t ---
3033
3034
3035/**
3036 * Ignore
3037 */
3038class V8EXPORT ExtensionConfiguration {
3039 public:
3040 ExtensionConfiguration(int name_count, const char* names[])
3041 : name_count_(name_count), names_(names) { }
3042 private:
3043 friend class ImplementationUtilities;
3044 int name_count_;
3045 const char** names_;
3046};
3047
3048
3049/**
3050 * A sandboxed execution context with its own set of built-in objects
3051 * and functions.
3052 */
3053class V8EXPORT Context {
3054 public:
Steve Block1e0659c2011-05-24 12:43:12 +01003055 /**
3056 * Returns the global proxy object or global object itself for
3057 * detached contexts.
3058 *
3059 * Global proxy object is a thin wrapper whose prototype points to
3060 * actual context's global object with the properties like Object, etc.
3061 * This is done that way for security reasons (for more details see
3062 * https://wiki.mozilla.org/Gecko:SplitWindow).
3063 *
3064 * Please note that changes to global proxy object prototype most probably
3065 * would break VM---v8 expects only global object as a prototype of
3066 * global proxy object.
3067 *
3068 * If DetachGlobal() has been invoked, Global() would return actual global
3069 * object until global is reattached with ReattachGlobal().
3070 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003071 Local<Object> Global();
3072
3073 /**
3074 * Detaches the global object from its context before
3075 * the global object can be reused to create a new context.
3076 */
3077 void DetachGlobal();
3078
Andrei Popescu74b3c142010-03-29 12:03:09 +01003079 /**
3080 * Reattaches a global object to a context. This can be used to
3081 * restore the connection between a global object and a context
3082 * after DetachGlobal has been called.
3083 *
3084 * \param global_object The global object to reattach to the
3085 * context. For this to work, the global object must be the global
3086 * object that was associated with this context before a call to
3087 * DetachGlobal.
3088 */
3089 void ReattachGlobal(Handle<Object> global_object);
3090
Leon Clarkef7060e22010-06-03 12:02:55 +01003091 /** Creates a new context.
3092 *
3093 * Returns a persistent handle to the newly allocated context. This
3094 * persistent handle has to be disposed when the context is no
3095 * longer used so the context can be garbage collected.
Steve Block9fac8402011-05-12 15:51:54 +01003096 *
3097 * \param extensions An optional extension configuration containing
3098 * the extensions to be installed in the newly created context.
3099 *
3100 * \param global_template An optional object template from which the
3101 * global object for the newly created context will be created.
3102 *
3103 * \param global_object An optional global object to be reused for
3104 * the newly created context. This global object must have been
3105 * created by a previous call to Context::New with the same global
3106 * template. The state of the global object will be completely reset
3107 * and only object identify will remain.
Leon Clarkef7060e22010-06-03 12:02:55 +01003108 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003109 static Persistent<Context> New(
Andrei Popescu31002712010-02-23 13:46:05 +00003110 ExtensionConfiguration* extensions = NULL,
Steve Blocka7e24c12009-10-30 11:49:00 +00003111 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3112 Handle<Value> global_object = Handle<Value>());
3113
3114 /** Returns the last entered context. */
3115 static Local<Context> GetEntered();
3116
3117 /** Returns the context that is on the top of the stack. */
3118 static Local<Context> GetCurrent();
3119
3120 /**
3121 * Returns the context of the calling JavaScript code. That is the
3122 * context of the top-most JavaScript frame. If there are no
3123 * JavaScript frames an empty handle is returned.
3124 */
3125 static Local<Context> GetCalling();
3126
3127 /**
3128 * Sets the security token for the context. To access an object in
3129 * another context, the security tokens must match.
3130 */
3131 void SetSecurityToken(Handle<Value> token);
3132
3133 /** Restores the security token to the default value. */
3134 void UseDefaultSecurityToken();
3135
3136 /** Returns the security token of this context.*/
3137 Handle<Value> GetSecurityToken();
3138
3139 /**
3140 * Enter this context. After entering a context, all code compiled
3141 * and run is compiled and run in this context. If another context
3142 * is already entered, this old context is saved so it can be
3143 * restored when the new context is exited.
3144 */
3145 void Enter();
3146
3147 /**
3148 * Exit this context. Exiting the current context restores the
3149 * context that was in place when entering the current context.
3150 */
3151 void Exit();
3152
3153 /** Returns true if the context has experienced an out of memory situation. */
3154 bool HasOutOfMemoryException();
3155
3156 /** Returns true if V8 has a current context. */
3157 static bool InContext();
3158
3159 /**
3160 * Associate an additional data object with the context. This is mainly used
3161 * with the debugger to provide additional information on the context through
3162 * the debugger API.
3163 */
Steve Blockd0582a62009-12-15 09:54:21 +00003164 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00003165 Local<Value> GetData();
3166
3167 /**
3168 * Stack-allocated class which sets the execution context for all
3169 * operations executed within a local scope.
3170 */
Steve Block8defd9f2010-07-08 12:39:36 +01003171 class Scope {
Steve Blocka7e24c12009-10-30 11:49:00 +00003172 public:
3173 inline Scope(Handle<Context> context) : context_(context) {
3174 context_->Enter();
3175 }
3176 inline ~Scope() { context_->Exit(); }
3177 private:
3178 Handle<Context> context_;
3179 };
3180
3181 private:
3182 friend class Value;
3183 friend class Script;
3184 friend class Object;
3185 friend class Function;
3186};
3187
3188
3189/**
3190 * Multiple threads in V8 are allowed, but only one thread at a time
3191 * is allowed to use V8. The definition of 'using V8' includes
3192 * accessing handles or holding onto object pointers obtained from V8
3193 * handles. It is up to the user of V8 to ensure (perhaps with
3194 * locking) that this constraint is not violated.
3195 *
3196 * If you wish to start using V8 in a thread you can do this by constructing
3197 * a v8::Locker object. After the code using V8 has completed for the
3198 * current thread you can call the destructor. This can be combined
3199 * with C++ scope-based construction as follows:
3200 *
3201 * \code
3202 * ...
3203 * {
3204 * v8::Locker locker;
3205 * ...
3206 * // Code using V8 goes here.
3207 * ...
3208 * } // Destructor called here
3209 * \endcode
3210 *
3211 * If you wish to stop using V8 in a thread A you can do this by either
3212 * by destroying the v8::Locker object as above or by constructing a
3213 * v8::Unlocker object:
3214 *
3215 * \code
3216 * {
3217 * v8::Unlocker unlocker;
3218 * ...
3219 * // Code not using V8 goes here while V8 can run in another thread.
3220 * ...
3221 * } // Destructor called here.
3222 * \endcode
3223 *
3224 * The Unlocker object is intended for use in a long-running callback
3225 * from V8, where you want to release the V8 lock for other threads to
3226 * use.
3227 *
3228 * The v8::Locker is a recursive lock. That is, you can lock more than
3229 * once in a given thread. This can be useful if you have code that can
3230 * be called either from code that holds the lock or from code that does
3231 * not. The Unlocker is not recursive so you can not have several
3232 * Unlockers on the stack at once, and you can not use an Unlocker in a
3233 * thread that is not inside a Locker's scope.
3234 *
3235 * An unlocker will unlock several lockers if it has to and reinstate
3236 * the correct depth of locking on its destruction. eg.:
3237 *
3238 * \code
3239 * // V8 not locked.
3240 * {
3241 * v8::Locker locker;
3242 * // V8 locked.
3243 * {
3244 * v8::Locker another_locker;
3245 * // V8 still locked (2 levels).
3246 * {
3247 * v8::Unlocker unlocker;
3248 * // V8 not locked.
3249 * }
3250 * // V8 locked again (2 levels).
3251 * }
3252 * // V8 still locked (1 level).
3253 * }
3254 * // V8 Now no longer locked.
3255 * \endcode
3256 */
3257class V8EXPORT Unlocker {
3258 public:
3259 Unlocker();
3260 ~Unlocker();
3261};
3262
3263
3264class V8EXPORT Locker {
3265 public:
3266 Locker();
3267 ~Locker();
3268
3269 /**
3270 * Start preemption.
3271 *
3272 * When preemption is started, a timer is fired every n milli seconds
3273 * that will switch between multiple threads that are in contention
3274 * for the V8 lock.
3275 */
3276 static void StartPreemption(int every_n_ms);
3277
3278 /**
3279 * Stop preemption.
3280 */
3281 static void StopPreemption();
3282
3283 /**
3284 * Returns whether or not the locker is locked by the current thread.
3285 */
3286 static bool IsLocked();
3287
3288 /**
3289 * Returns whether v8::Locker is being used by this V8 instance.
3290 */
3291 static bool IsActive() { return active_; }
3292
3293 private:
3294 bool has_lock_;
3295 bool top_level_;
3296
3297 static bool active_;
3298
3299 // Disallow copying and assigning.
3300 Locker(const Locker&);
3301 void operator=(const Locker&);
3302};
3303
3304
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003305/**
3306 * An interface for exporting data from V8, using "push" model.
3307 */
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003308class V8EXPORT OutputStream { // NOLINT
3309 public:
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003310 enum OutputEncoding {
3311 kAscii = 0 // 7-bit ASCII.
3312 };
3313 enum WriteResult {
3314 kContinue = 0,
3315 kAbort = 1
3316 };
3317 virtual ~OutputStream() {}
3318 /** Notify about the end of stream. */
3319 virtual void EndOfStream() = 0;
3320 /** Get preferred output chunk size. Called only once. */
3321 virtual int GetChunkSize() { return 1024; }
3322 /** Get preferred output encoding. Called only once. */
3323 virtual OutputEncoding GetOutputEncoding() { return kAscii; }
3324 /**
3325 * Writes the next chunk of snapshot data into the stream. Writing
3326 * can be stopped by returning kAbort as function result. EndOfStream
3327 * will not be called in case writing was aborted.
3328 */
3329 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3330};
3331
3332
Ben Murdochb0fe1622011-05-05 13:52:32 +01003333/**
3334 * An interface for reporting progress and controlling long-running
3335 * activities.
3336 */
3337class V8EXPORT ActivityControl { // NOLINT
3338 public:
3339 enum ControlOption {
3340 kContinue = 0,
3341 kAbort = 1
3342 };
3343 virtual ~ActivityControl() {}
3344 /**
3345 * Notify about current progress. The activity can be stopped by
3346 * returning kAbort as the callback result.
3347 */
3348 virtual ControlOption ReportProgressValue(int done, int total) = 0;
3349};
3350
Steve Blocka7e24c12009-10-30 11:49:00 +00003351
3352// --- I m p l e m e n t a t i o n ---
3353
3354
3355namespace internal {
3356
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003357static const int kApiPointerSize = sizeof(void*); // NOLINT
3358static const int kApiIntSize = sizeof(int); // NOLINT
Steve Blocka7e24c12009-10-30 11:49:00 +00003359
3360// Tag information for HeapObject.
3361const int kHeapObjectTag = 1;
3362const int kHeapObjectTagSize = 2;
3363const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3364
Steve Blocka7e24c12009-10-30 11:49:00 +00003365// Tag information for Smi.
3366const int kSmiTag = 0;
3367const int kSmiTagSize = 1;
3368const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3369
Ben Murdochb8e0da22011-05-16 14:20:40 +01003370template <size_t ptr_size> struct SmiTagging;
Steve Block3ce2e202009-11-05 08:53:23 +00003371
3372// Smi constants for 32-bit systems.
Ben Murdochb8e0da22011-05-16 14:20:40 +01003373template <> struct SmiTagging<4> {
Steve Block3ce2e202009-11-05 08:53:23 +00003374 static const int kSmiShiftSize = 0;
3375 static const int kSmiValueSize = 31;
3376 static inline int SmiToInt(internal::Object* value) {
3377 int shift_bits = kSmiTagSize + kSmiShiftSize;
3378 // Throw away top 32 bits and shift down (requires >> to be sign extending).
3379 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3380 }
Ben Murdochb8e0da22011-05-16 14:20:40 +01003381
3382 // For 32-bit systems any 2 bytes aligned pointer can be encoded as smi
3383 // with a plain reinterpret_cast.
Steve Block1e0659c2011-05-24 12:43:12 +01003384 static const uintptr_t kEncodablePointerMask = 0x1;
Ben Murdochb8e0da22011-05-16 14:20:40 +01003385 static const int kPointerToSmiShift = 0;
Steve Block3ce2e202009-11-05 08:53:23 +00003386};
3387
3388// Smi constants for 64-bit systems.
Ben Murdochb8e0da22011-05-16 14:20:40 +01003389template <> struct SmiTagging<8> {
Steve Block3ce2e202009-11-05 08:53:23 +00003390 static const int kSmiShiftSize = 31;
3391 static const int kSmiValueSize = 32;
3392 static inline int SmiToInt(internal::Object* value) {
3393 int shift_bits = kSmiTagSize + kSmiShiftSize;
3394 // Shift down and throw away top 32 bits.
3395 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3396 }
Ben Murdochb8e0da22011-05-16 14:20:40 +01003397
3398 // To maximize the range of pointers that can be encoded
3399 // in the available 32 bits, we require them to be 8 bytes aligned.
3400 // This gives 2 ^ (32 + 3) = 32G address space covered.
3401 // It might be not enough to cover stack allocated objects on some platforms.
3402 static const int kPointerAlignment = 3;
3403
Steve Block1e0659c2011-05-24 12:43:12 +01003404 static const uintptr_t kEncodablePointerMask =
3405 ~(uintptr_t(0xffffffff) << kPointerAlignment);
Ben Murdochb8e0da22011-05-16 14:20:40 +01003406
3407 static const int kPointerToSmiShift =
3408 kSmiTagSize + kSmiShiftSize - kPointerAlignment;
Steve Block3ce2e202009-11-05 08:53:23 +00003409};
3410
Ben Murdochb8e0da22011-05-16 14:20:40 +01003411typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
3412const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
3413const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
Steve Block1e0659c2011-05-24 12:43:12 +01003414const uintptr_t kEncodablePointerMask =
Ben Murdochb8e0da22011-05-16 14:20:40 +01003415 PlatformSmiTagging::kEncodablePointerMask;
3416const int kPointerToSmiShift = PlatformSmiTagging::kPointerToSmiShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00003417
Steve Blockd0582a62009-12-15 09:54:21 +00003418template <size_t ptr_size> struct InternalConstants;
3419
3420// Internal constants for 32-bit systems.
3421template <> struct InternalConstants<4> {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003422 static const int kStringResourceOffset = 3 * kApiPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003423};
3424
3425// Internal constants for 64-bit systems.
3426template <> struct InternalConstants<8> {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003427 static const int kStringResourceOffset = 3 * kApiPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003428};
3429
Steve Blocka7e24c12009-10-30 11:49:00 +00003430/**
3431 * This class exports constants and functionality from within v8 that
3432 * is necessary to implement inline functions in the v8 api. Don't
3433 * depend on functions and constants defined here.
3434 */
3435class Internals {
3436 public:
3437
3438 // These values match non-compiler-dependent values defined within
3439 // the implementation of v8.
3440 static const int kHeapObjectMapOffset = 0;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003441 static const int kMapInstanceTypeOffset = kApiPointerSize + kApiIntSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003442 static const int kStringResourceOffset =
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003443 InternalConstants<kApiPointerSize>::kStringResourceOffset;
Steve Blockd0582a62009-12-15 09:54:21 +00003444
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003445 static const int kProxyProxyOffset = kApiPointerSize;
3446 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003447 static const int kFullStringRepresentationMask = 0x07;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003448 static const int kExternalTwoByteRepresentationTag = 0x02;
Steve Blocka7e24c12009-10-30 11:49:00 +00003449
Steve Block1e0659c2011-05-24 12:43:12 +01003450 static const int kJSObjectType = 0xa0;
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003451 static const int kFirstNonstringType = 0x80;
3452 static const int kProxyType = 0x85;
Steve Blocka7e24c12009-10-30 11:49:00 +00003453
3454 static inline bool HasHeapObjectTag(internal::Object* value) {
3455 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3456 kHeapObjectTag);
3457 }
3458
3459 static inline bool HasSmiTag(internal::Object* value) {
3460 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3461 }
3462
3463 static inline int SmiValue(internal::Object* value) {
Ben Murdochb8e0da22011-05-16 14:20:40 +01003464 return PlatformSmiTagging::SmiToInt(value);
Steve Block3ce2e202009-11-05 08:53:23 +00003465 }
3466
3467 static inline int GetInstanceType(internal::Object* obj) {
3468 typedef internal::Object O;
3469 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3470 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3471 }
3472
Ben Murdochb8e0da22011-05-16 14:20:40 +01003473 static inline void* GetExternalPointerFromSmi(internal::Object* value) {
Steve Block1e0659c2011-05-24 12:43:12 +01003474 const uintptr_t address = reinterpret_cast<uintptr_t>(value);
Ben Murdochb8e0da22011-05-16 14:20:40 +01003475 return reinterpret_cast<void*>(address >> kPointerToSmiShift);
3476 }
3477
Steve Block3ce2e202009-11-05 08:53:23 +00003478 static inline void* GetExternalPointer(internal::Object* obj) {
3479 if (HasSmiTag(obj)) {
Ben Murdochb8e0da22011-05-16 14:20:40 +01003480 return GetExternalPointerFromSmi(obj);
Steve Block3ce2e202009-11-05 08:53:23 +00003481 } else if (GetInstanceType(obj) == kProxyType) {
3482 return ReadField<void*>(obj, kProxyProxyOffset);
3483 } else {
3484 return NULL;
3485 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003486 }
3487
3488 static inline bool IsExternalTwoByteString(int instance_type) {
3489 int representation = (instance_type & kFullStringRepresentationMask);
3490 return representation == kExternalTwoByteRepresentationTag;
3491 }
3492
3493 template <typename T>
3494 static inline T ReadField(Object* ptr, int offset) {
3495 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3496 return *reinterpret_cast<T*>(addr);
3497 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003498};
3499
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003500} // namespace internal
Steve Blocka7e24c12009-10-30 11:49:00 +00003501
3502
3503template <class T>
3504Handle<T>::Handle() : val_(0) { }
3505
3506
3507template <class T>
3508Local<T>::Local() : Handle<T>() { }
3509
3510
3511template <class T>
3512Local<T> Local<T>::New(Handle<T> that) {
3513 if (that.IsEmpty()) return Local<T>();
3514 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3515 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3516}
3517
3518
3519template <class T>
3520Persistent<T> Persistent<T>::New(Handle<T> that) {
3521 if (that.IsEmpty()) return Persistent<T>();
3522 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3523 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3524}
3525
3526
3527template <class T>
3528bool Persistent<T>::IsNearDeath() const {
3529 if (this->IsEmpty()) return false;
3530 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3531}
3532
3533
3534template <class T>
3535bool Persistent<T>::IsWeak() const {
3536 if (this->IsEmpty()) return false;
3537 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3538}
3539
3540
3541template <class T>
3542void Persistent<T>::Dispose() {
3543 if (this->IsEmpty()) return;
3544 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3545}
3546
3547
3548template <class T>
3549Persistent<T>::Persistent() : Handle<T>() { }
3550
3551template <class T>
3552void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3553 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3554 parameters,
3555 callback);
3556}
3557
3558template <class T>
3559void Persistent<T>::ClearWeak() {
3560 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
3561}
3562
Steve Block8defd9f2010-07-08 12:39:36 +01003563
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003564Arguments::Arguments(internal::Object** implicit_args,
3565 internal::Object** values, int length,
3566 bool is_construct_call)
3567 : implicit_args_(implicit_args),
3568 values_(values),
3569 length_(length),
3570 is_construct_call_(is_construct_call) { }
Steve Block8defd9f2010-07-08 12:39:36 +01003571
3572
Steve Blocka7e24c12009-10-30 11:49:00 +00003573Local<Value> Arguments::operator[](int i) const {
3574 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
3575 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
3576}
3577
3578
3579Local<Function> Arguments::Callee() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003580 return Local<Function>(reinterpret_cast<Function*>(
3581 &implicit_args_[kCalleeIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003582}
3583
3584
3585Local<Object> Arguments::This() const {
3586 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
3587}
3588
3589
3590Local<Object> Arguments::Holder() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003591 return Local<Object>(reinterpret_cast<Object*>(
3592 &implicit_args_[kHolderIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003593}
3594
3595
3596Local<Value> Arguments::Data() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003597 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003598}
3599
3600
3601bool Arguments::IsConstructCall() const {
3602 return is_construct_call_;
3603}
3604
3605
3606int Arguments::Length() const {
3607 return length_;
3608}
3609
3610
3611template <class T>
3612Local<T> HandleScope::Close(Handle<T> value) {
3613 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
3614 internal::Object** after = RawClose(before);
3615 return Local<T>(reinterpret_cast<T*>(after));
3616}
3617
3618Handle<Value> ScriptOrigin::ResourceName() const {
3619 return resource_name_;
3620}
3621
3622
3623Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
3624 return resource_line_offset_;
3625}
3626
3627
3628Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
3629 return resource_column_offset_;
3630}
3631
3632
3633Handle<Boolean> Boolean::New(bool value) {
3634 return value ? True() : False();
3635}
3636
3637
3638void Template::Set(const char* name, v8::Handle<Data> value) {
3639 Set(v8::String::New(name), value);
3640}
3641
3642
3643Local<Value> Object::GetInternalField(int index) {
3644#ifndef V8_ENABLE_CHECKS
3645 Local<Value> quick_result = UncheckedGetInternalField(index);
3646 if (!quick_result.IsEmpty()) return quick_result;
3647#endif
3648 return CheckedGetInternalField(index);
3649}
3650
3651
3652Local<Value> Object::UncheckedGetInternalField(int index) {
3653 typedef internal::Object O;
3654 typedef internal::Internals I;
3655 O* obj = *reinterpret_cast<O**>(this);
Steve Block3ce2e202009-11-05 08:53:23 +00003656 if (I::GetInstanceType(obj) == I::kJSObjectType) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003657 // If the object is a plain JSObject, which is the common case,
3658 // we know where to find the internal fields and can return the
3659 // value directly.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003660 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003661 O* value = I::ReadField<O*>(obj, offset);
3662 O** result = HandleScope::CreateHandle(value);
3663 return Local<Value>(reinterpret_cast<Value*>(result));
3664 } else {
3665 return Local<Value>();
3666 }
3667}
3668
3669
3670void* External::Unwrap(Handle<v8::Value> obj) {
3671#ifdef V8_ENABLE_CHECKS
3672 return FullUnwrap(obj);
3673#else
3674 return QuickUnwrap(obj);
3675#endif
3676}
3677
3678
3679void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
3680 typedef internal::Object O;
Steve Blocka7e24c12009-10-30 11:49:00 +00003681 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
Steve Block3ce2e202009-11-05 08:53:23 +00003682 return internal::Internals::GetExternalPointer(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00003683}
3684
3685
3686void* Object::GetPointerFromInternalField(int index) {
Steve Block3ce2e202009-11-05 08:53:23 +00003687 typedef internal::Object O;
3688 typedef internal::Internals I;
3689
3690 O* obj = *reinterpret_cast<O**>(this);
3691
3692 if (I::GetInstanceType(obj) == I::kJSObjectType) {
3693 // If the object is a plain JSObject, which is the common case,
3694 // we know where to find the internal fields and can return the
3695 // value directly.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003696 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
Steve Block3ce2e202009-11-05 08:53:23 +00003697 O* value = I::ReadField<O*>(obj, offset);
3698 return I::GetExternalPointer(value);
3699 }
3700
3701 return SlowGetPointerFromInternalField(index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003702}
3703
3704
3705String* String::Cast(v8::Value* value) {
3706#ifdef V8_ENABLE_CHECKS
3707 CheckCast(value);
3708#endif
3709 return static_cast<String*>(value);
3710}
3711
3712
3713String::ExternalStringResource* String::GetExternalStringResource() const {
3714 typedef internal::Object O;
3715 typedef internal::Internals I;
3716 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
Steve Blocka7e24c12009-10-30 11:49:00 +00003717 String::ExternalStringResource* result;
Steve Block3ce2e202009-11-05 08:53:23 +00003718 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003719 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
3720 result = reinterpret_cast<String::ExternalStringResource*>(value);
3721 } else {
3722 result = NULL;
3723 }
3724#ifdef V8_ENABLE_CHECKS
3725 VerifyExternalStringResource(result);
3726#endif
3727 return result;
3728}
3729
3730
3731bool Value::IsString() const {
3732#ifdef V8_ENABLE_CHECKS
3733 return FullIsString();
3734#else
3735 return QuickIsString();
3736#endif
3737}
3738
3739bool Value::QuickIsString() const {
3740 typedef internal::Object O;
3741 typedef internal::Internals I;
3742 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
3743 if (!I::HasHeapObjectTag(obj)) return false;
Steve Block3ce2e202009-11-05 08:53:23 +00003744 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
Steve Blocka7e24c12009-10-30 11:49:00 +00003745}
3746
3747
3748Number* Number::Cast(v8::Value* value) {
3749#ifdef V8_ENABLE_CHECKS
3750 CheckCast(value);
3751#endif
3752 return static_cast<Number*>(value);
3753}
3754
3755
3756Integer* Integer::Cast(v8::Value* value) {
3757#ifdef V8_ENABLE_CHECKS
3758 CheckCast(value);
3759#endif
3760 return static_cast<Integer*>(value);
3761}
3762
3763
3764Date* Date::Cast(v8::Value* value) {
3765#ifdef V8_ENABLE_CHECKS
3766 CheckCast(value);
3767#endif
3768 return static_cast<Date*>(value);
3769}
3770
3771
Ben Murdochf87a2032010-10-22 12:50:53 +01003772RegExp* RegExp::Cast(v8::Value* value) {
3773#ifdef V8_ENABLE_CHECKS
3774 CheckCast(value);
3775#endif
3776 return static_cast<RegExp*>(value);
3777}
3778
3779
Steve Blocka7e24c12009-10-30 11:49:00 +00003780Object* Object::Cast(v8::Value* value) {
3781#ifdef V8_ENABLE_CHECKS
3782 CheckCast(value);
3783#endif
3784 return static_cast<Object*>(value);
3785}
3786
3787
3788Array* Array::Cast(v8::Value* value) {
3789#ifdef V8_ENABLE_CHECKS
3790 CheckCast(value);
3791#endif
3792 return static_cast<Array*>(value);
3793}
3794
3795
3796Function* Function::Cast(v8::Value* value) {
3797#ifdef V8_ENABLE_CHECKS
3798 CheckCast(value);
3799#endif
3800 return static_cast<Function*>(value);
3801}
3802
3803
3804External* External::Cast(v8::Value* value) {
3805#ifdef V8_ENABLE_CHECKS
3806 CheckCast(value);
3807#endif
3808 return static_cast<External*>(value);
3809}
3810
3811
3812Local<Value> AccessorInfo::Data() const {
Steve Block6ded16b2010-05-10 14:33:55 +01003813 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003814}
3815
3816
3817Local<Object> AccessorInfo::This() const {
3818 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
3819}
3820
3821
3822Local<Object> AccessorInfo::Holder() const {
3823 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
3824}
3825
3826
3827/**
3828 * \example shell.cc
3829 * A simple shell that takes a list of expressions on the
3830 * command-line and executes them.
3831 */
3832
3833
3834/**
3835 * \example process.cc
3836 */
3837
3838
3839} // namespace v8
3840
3841
3842#undef V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00003843#undef TYPE_CHECK
3844
3845
3846#endif // V8_H_