blob: c07ba1f0cfbe70e9c543b203cde7e122934e75e8 [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
41#include <stdio.h>
42
43#ifdef _WIN32
44// When compiling on MinGW stdint.h is available.
45#ifdef __MINGW32__
46#include <stdint.h>
47#else // __MINGW32__
48typedef signed char int8_t;
49typedef unsigned char uint8_t;
50typedef short int16_t; // NOLINT
51typedef unsigned short uint16_t; // NOLINT
52typedef int int32_t;
53typedef unsigned int uint32_t;
54typedef __int64 int64_t;
55typedef unsigned __int64 uint64_t;
56// intptr_t and friends are defined in crtdefs.h through stdio.h.
57#endif // __MINGW32__
58
59// Setup for Windows DLL export/import. When building the V8 DLL the
60// BUILDING_V8_SHARED needs to be defined. When building a program which uses
61// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
62// static library or building a program which uses the V8 static library neither
63// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
64// The reason for having both V8EXPORT and V8EXPORT_INLINE is that classes which
65// have their code inside this header file need to have __declspec(dllexport)
66// when building the DLL but cannot have __declspec(dllimport) when building
67// a program which uses the DLL.
68#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
69#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
70 build configuration to ensure that at most one of these is set
71#endif
72
73#ifdef BUILDING_V8_SHARED
74#define V8EXPORT __declspec(dllexport)
75#define V8EXPORT_INLINE __declspec(dllexport)
76#elif USING_V8_SHARED
77#define V8EXPORT __declspec(dllimport)
78#define V8EXPORT_INLINE
79#else
80#define V8EXPORT
81#define V8EXPORT_INLINE
82#endif // BUILDING_V8_SHARED
83
84#else // _WIN32
85
86#include <stdint.h>
87
88// Setup for Linux shared library export. There is no need to distinguish
89// between building or using the V8 shared library, but we should not
90// export symbols when we are building a static library.
91#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
92#define V8EXPORT __attribute__ ((visibility("default")))
93#define V8EXPORT_INLINE __attribute__ ((visibility("default")))
94#else // defined(__GNUC__) && (__GNUC__ >= 4)
95#define V8EXPORT
96#define V8EXPORT_INLINE
97#endif // defined(__GNUC__) && (__GNUC__ >= 4)
98
99#endif // _WIN32
100
101/**
102 * The v8 JavaScript engine.
103 */
104namespace v8 {
105
106class Context;
107class String;
108class Value;
109class Utils;
110class Number;
111class Object;
112class Array;
113class Int32;
114class Uint32;
115class External;
116class Primitive;
117class Boolean;
118class Integer;
119class Function;
120class Date;
121class ImplementationUtilities;
122class Signature;
123template <class T> class Handle;
124template <class T> class Local;
125template <class T> class Persistent;
126class FunctionTemplate;
127class ObjectTemplate;
128class Data;
129
130namespace internal {
131
Steve Blocka7e24c12009-10-30 11:49:00 +0000132class Arguments;
Steve Blockd0582a62009-12-15 09:54:21 +0000133class Object;
134class Top;
Steve Blocka7e24c12009-10-30 11:49:00 +0000135
136}
137
138
139// --- W e a k H a n d l e s
140
141
142/**
143 * A weak reference callback function.
144 *
145 * \param object the weak global object to be reclaimed by the garbage collector
146 * \param parameter the value passed in when making the weak global object
147 */
148typedef void (*WeakReferenceCallback)(Persistent<Value> object,
149 void* parameter);
150
151
152// --- H a n d l e s ---
153
154#define TYPE_CHECK(T, S) \
155 while (false) { \
156 *(static_cast<T**>(0)) = static_cast<S*>(0); \
157 }
158
159/**
160 * An object reference managed by the v8 garbage collector.
161 *
162 * All objects returned from v8 have to be tracked by the garbage
163 * collector so that it knows that the objects are still alive. Also,
164 * because the garbage collector may move objects, it is unsafe to
165 * point directly to an object. Instead, all objects are stored in
166 * handles which are known by the garbage collector and updated
167 * whenever an object moves. Handles should always be passed by value
168 * (except in cases like out-parameters) and they should never be
169 * allocated on the heap.
170 *
171 * There are two types of handles: local and persistent handles.
172 * Local handles are light-weight and transient and typically used in
173 * local operations. They are managed by HandleScopes. Persistent
174 * handles can be used when storing objects across several independent
175 * operations and have to be explicitly deallocated when they're no
176 * longer used.
177 *
178 * It is safe to extract the object stored in the handle by
179 * dereferencing the handle (for instance, to extract the Object* from
180 * an Handle<Object>); the value will still be governed by a handle
181 * behind the scenes and the same rules apply to these values as to
182 * their handles.
183 */
184template <class T> class V8EXPORT_INLINE Handle {
185 public:
186
187 /**
188 * Creates an empty handle.
189 */
190 inline Handle();
191
192 /**
193 * Creates a new handle for the specified value.
194 */
195 explicit Handle(T* val) : val_(val) { }
196
197 /**
198 * Creates a handle for the contents of the specified handle. This
199 * constructor allows you to pass handles as arguments by value and
200 * to assign between handles. However, if you try to assign between
201 * incompatible handles, for instance from a Handle<String> to a
202 * Handle<Number> it will cause a compiletime error. Assigning
203 * between compatible handles, for instance assigning a
204 * Handle<String> to a variable declared as Handle<Value>, is legal
205 * because String is a subclass of Value.
206 */
207 template <class S> inline Handle(Handle<S> that)
208 : val_(reinterpret_cast<T*>(*that)) {
209 /**
210 * This check fails when trying to convert between incompatible
211 * handles. For example, converting from a Handle<String> to a
212 * Handle<Number>.
213 */
214 TYPE_CHECK(T, S);
215 }
216
217 /**
218 * Returns true if the handle is empty.
219 */
220 bool IsEmpty() const { return val_ == 0; }
221
222 T* operator->() const { return val_; }
223
224 T* operator*() const { return val_; }
225
226 /**
227 * Sets the handle to be empty. IsEmpty() will then return true.
228 */
229 void Clear() { this->val_ = 0; }
230
231 /**
232 * Checks whether two handles are the same.
233 * Returns true if both are empty, or if the objects
234 * to which they refer are identical.
235 * The handles' references are not checked.
236 */
237 template <class S> bool operator==(Handle<S> that) const {
238 internal::Object** a = reinterpret_cast<internal::Object**>(**this);
239 internal::Object** b = reinterpret_cast<internal::Object**>(*that);
240 if (a == 0) return b == 0;
241 if (b == 0) return false;
242 return *a == *b;
243 }
244
245 /**
246 * Checks whether two handles are different.
247 * Returns true if only one of the handles is empty, or if
248 * the objects to which they refer are different.
249 * The handles' references are not checked.
250 */
251 template <class S> bool operator!=(Handle<S> that) const {
252 return !operator==(that);
253 }
254
255 template <class S> static inline Handle<T> Cast(Handle<S> that) {
256#ifdef V8_ENABLE_CHECKS
257 // If we're going to perform the type check then we have to check
258 // that the handle isn't empty before doing the checked cast.
259 if (that.IsEmpty()) return Handle<T>();
260#endif
261 return Handle<T>(T::Cast(*that));
262 }
263
Steve Block6ded16b2010-05-10 14:33:55 +0100264 template <class S> inline Handle<S> As() {
265 return Handle<S>::Cast(*this);
266 }
267
Steve Blocka7e24c12009-10-30 11:49:00 +0000268 private:
269 T* val_;
270};
271
272
273/**
274 * A light-weight stack-allocated object handle. All operations
275 * that return objects from within v8 return them in local handles. They
276 * are created within HandleScopes, and all local handles allocated within a
277 * handle scope are destroyed when the handle scope is destroyed. Hence it
278 * is not necessary to explicitly deallocate local handles.
279 */
280template <class T> class V8EXPORT_INLINE Local : public Handle<T> {
281 public:
282 inline Local();
283 template <class S> inline Local(Local<S> that)
284 : Handle<T>(reinterpret_cast<T*>(*that)) {
285 /**
286 * This check fails when trying to convert between incompatible
287 * handles. For example, converting from a Handle<String> to a
288 * Handle<Number>.
289 */
290 TYPE_CHECK(T, S);
291 }
292 template <class S> inline Local(S* that) : Handle<T>(that) { }
293 template <class S> static inline Local<T> Cast(Local<S> that) {
294#ifdef V8_ENABLE_CHECKS
295 // If we're going to perform the type check then we have to check
296 // that the handle isn't empty before doing the checked cast.
297 if (that.IsEmpty()) return Local<T>();
298#endif
299 return Local<T>(T::Cast(*that));
300 }
301
Steve Block6ded16b2010-05-10 14:33:55 +0100302 template <class S> inline Local<S> As() {
303 return Local<S>::Cast(*this);
304 }
305
Steve Blocka7e24c12009-10-30 11:49:00 +0000306 /** Create a local handle for the content of another handle.
307 * The referee is kept alive by the local handle even when
308 * the original handle is destroyed/disposed.
309 */
310 inline static Local<T> New(Handle<T> that);
311};
312
313
314/**
315 * An object reference that is independent of any handle scope. Where
316 * a Local handle only lives as long as the HandleScope in which it was
317 * allocated, a Persistent handle remains valid until it is explicitly
318 * disposed.
319 *
320 * A persistent handle contains a reference to a storage cell within
321 * the v8 engine which holds an object value and which is updated by
322 * the garbage collector whenever the object is moved. A new storage
323 * cell can be created using Persistent::New and existing handles can
324 * be disposed using Persistent::Dispose. Since persistent handles
325 * are passed by value you may have many persistent handle objects
326 * that point to the same storage cell. For instance, if you pass a
327 * persistent handle as an argument to a function you will not get two
328 * different storage cells but rather two references to the same
329 * storage cell.
330 */
331template <class T> class V8EXPORT_INLINE Persistent : public Handle<T> {
332 public:
333
334 /**
335 * Creates an empty persistent handle that doesn't point to any
336 * storage cell.
337 */
338 inline Persistent();
339
340 /**
341 * Creates a persistent handle for the same storage cell as the
342 * specified handle. This constructor allows you to pass persistent
343 * handles as arguments by value and to assign between persistent
344 * handles. However, attempting to assign between incompatible
345 * persistent handles, for instance from a Persistent<String> to a
346 * Persistent<Number> will cause a compiletime error. Assigning
347 * between compatible persistent handles, for instance assigning a
348 * Persistent<String> to a variable declared as Persistent<Value>,
349 * is allowed as String is a subclass of Value.
350 */
351 template <class S> inline Persistent(Persistent<S> that)
352 : Handle<T>(reinterpret_cast<T*>(*that)) {
353 /**
354 * This check fails when trying to convert between incompatible
355 * handles. For example, converting from a Handle<String> to a
356 * Handle<Number>.
357 */
358 TYPE_CHECK(T, S);
359 }
360
361 template <class S> inline Persistent(S* that) : Handle<T>(that) { }
362
363 /**
364 * "Casts" a plain handle which is known to be a persistent handle
365 * to a persistent handle.
366 */
367 template <class S> explicit inline Persistent(Handle<S> that)
368 : Handle<T>(*that) { }
369
370 template <class S> static inline Persistent<T> Cast(Persistent<S> that) {
371#ifdef V8_ENABLE_CHECKS
372 // If we're going to perform the type check then we have to check
373 // that the handle isn't empty before doing the checked cast.
374 if (that.IsEmpty()) return Persistent<T>();
375#endif
376 return Persistent<T>(T::Cast(*that));
377 }
378
Steve Block6ded16b2010-05-10 14:33:55 +0100379 template <class S> inline Persistent<S> As() {
380 return Persistent<S>::Cast(*this);
381 }
382
Steve Blocka7e24c12009-10-30 11:49:00 +0000383 /**
384 * Creates a new persistent handle for an existing local or
385 * persistent handle.
386 */
387 inline static Persistent<T> New(Handle<T> that);
388
389 /**
390 * Releases the storage cell referenced by this persistent handle.
391 * Does not remove the reference to the cell from any handles.
392 * This handle's reference, and any any other references to the storage
393 * cell remain and IsEmpty will still return false.
394 */
395 inline void Dispose();
396
397 /**
398 * Make the reference to this object weak. When only weak handles
399 * refer to the object, the garbage collector will perform a
400 * callback to the given V8::WeakReferenceCallback function, passing
401 * it the object reference and the given parameters.
402 */
403 inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
404
405 /** Clears the weak reference to this object.*/
406 inline void ClearWeak();
407
408 /**
409 *Checks if the handle holds the only reference to an object.
410 */
411 inline bool IsNearDeath() const;
412
413 /**
414 * Returns true if the handle's reference is weak.
415 */
416 inline bool IsWeak() const;
417
418 private:
419 friend class ImplementationUtilities;
420 friend class ObjectTemplate;
421};
422
423
424 /**
425 * A stack-allocated class that governs a number of local handles.
426 * After a handle scope has been created, all local handles will be
427 * allocated within that handle scope until either the handle scope is
428 * deleted or another handle scope is created. If there is already a
429 * handle scope and a new one is created, all allocations will take
430 * place in the new handle scope until it is deleted. After that,
431 * new handles will again be allocated in the original handle scope.
432 *
433 * After the handle scope of a local handle has been deleted the
434 * garbage collector will no longer track the object stored in the
435 * handle and may deallocate it. The behavior of accessing a handle
436 * for which the handle scope has been deleted is undefined.
437 */
438class V8EXPORT HandleScope {
439 public:
440 HandleScope();
441
442 ~HandleScope();
443
444 /**
445 * Closes the handle scope and returns the value as a handle in the
446 * previous scope, which is the new current scope after the call.
447 */
448 template <class T> Local<T> Close(Handle<T> value);
449
450 /**
451 * Counts the number of allocated handles.
452 */
453 static int NumberOfHandles();
454
455 /**
456 * Creates a new handle with the given value.
457 */
458 static internal::Object** CreateHandle(internal::Object* value);
459
460 private:
461 // Make it impossible to create heap-allocated or illegal handle
462 // scopes by disallowing certain operations.
463 HandleScope(const HandleScope&);
464 void operator=(const HandleScope&);
465 void* operator new(size_t size);
466 void operator delete(void*, size_t);
467
Steve Blockd0582a62009-12-15 09:54:21 +0000468 // This Data class is accessible internally as HandleScopeData through a
469 // typedef in the ImplementationUtilities class.
Steve Blocka7e24c12009-10-30 11:49:00 +0000470 class V8EXPORT Data {
471 public:
472 int extensions;
473 internal::Object** next;
474 internal::Object** limit;
475 inline void Initialize() {
476 extensions = -1;
477 next = limit = NULL;
478 }
479 };
480
481 Data previous_;
482
483 // Allow for the active closing of HandleScopes which allows to pass a handle
484 // from the HandleScope being closed to the next top most HandleScope.
485 bool is_closed_;
486 internal::Object** RawClose(internal::Object** value);
487
488 friend class ImplementationUtilities;
489};
490
491
492// --- S p e c i a l o b j e c t s ---
493
494
495/**
496 * The superclass of values and API object templates.
497 */
498class V8EXPORT Data {
499 private:
500 Data();
501};
502
503
504/**
505 * Pre-compilation data that can be associated with a script. This
506 * data can be calculated for a script in advance of actually
507 * compiling it, and can be stored between compilations. When script
508 * data is given to the compile method compilation will be faster.
509 */
510class V8EXPORT ScriptData { // NOLINT
511 public:
512 virtual ~ScriptData() { }
513 static ScriptData* PreCompile(const char* input, int length);
514 static ScriptData* New(unsigned* data, int length);
515
516 virtual int Length() = 0;
517 virtual unsigned* Data() = 0;
Leon Clarkee46be812010-01-19 14:06:41 +0000518 virtual bool HasError() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000519};
520
521
522/**
523 * The origin, within a file, of a script.
524 */
525class V8EXPORT ScriptOrigin {
526 public:
527 ScriptOrigin(Handle<Value> resource_name,
528 Handle<Integer> resource_line_offset = Handle<Integer>(),
529 Handle<Integer> resource_column_offset = Handle<Integer>())
530 : resource_name_(resource_name),
531 resource_line_offset_(resource_line_offset),
532 resource_column_offset_(resource_column_offset) { }
533 inline Handle<Value> ResourceName() const;
534 inline Handle<Integer> ResourceLineOffset() const;
535 inline Handle<Integer> ResourceColumnOffset() const;
536 private:
537 Handle<Value> resource_name_;
538 Handle<Integer> resource_line_offset_;
539 Handle<Integer> resource_column_offset_;
540};
541
542
543/**
544 * A compiled JavaScript script.
545 */
546class V8EXPORT Script {
547 public:
548
Steve Blocka7e24c12009-10-30 11:49:00 +0000549 /**
Andrei Popescu402d9372010-02-26 13:31:12 +0000550 * Compiles the specified script (context-independent).
Steve Blocka7e24c12009-10-30 11:49:00 +0000551 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000552 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100553 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000554 * when New() returns
555 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
556 * using pre_data speeds compilation if it's done multiple times.
557 * Owned by caller, no references are kept when New() returns.
558 * \param script_data Arbitrary data associated with script. Using
Steve Block6ded16b2010-05-10 14:33:55 +0100559 * this has same effect as calling SetData(), but allows data to be
Andrei Popescu402d9372010-02-26 13:31:12 +0000560 * available to compile event handlers.
561 * \return Compiled script object (context independent; when run it
562 * will use the currently entered context).
Steve Blocka7e24c12009-10-30 11:49:00 +0000563 */
Andrei Popescu402d9372010-02-26 13:31:12 +0000564 static Local<Script> New(Handle<String> source,
565 ScriptOrigin* origin = NULL,
566 ScriptData* pre_data = NULL,
567 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000568
569 /**
570 * Compiles the specified script using the specified file name
571 * object (typically a string) as the script's origin.
572 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000573 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100574 * \param file_name file name object (typically a string) to be used
Andrei Popescu402d9372010-02-26 13:31:12 +0000575 * as the script's origin.
576 * \return Compiled script object (context independent; when run it
577 * will use the currently entered context).
578 */
579 static Local<Script> New(Handle<String> source,
580 Handle<Value> file_name);
581
582 /**
583 * Compiles the specified script (bound to current context).
584 *
585 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100586 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000587 * when Compile() returns
588 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
589 * using pre_data speeds compilation if it's done multiple times.
590 * Owned by caller, no references are kept when Compile() returns.
591 * \param script_data Arbitrary data associated with script. Using
592 * this has same effect as calling SetData(), but makes data available
593 * earlier (i.e. to compile event handlers).
594 * \return Compiled script object, bound to the context that was active
595 * when this function was called. When run it will always use this
596 * context.
Steve Blocka7e24c12009-10-30 11:49:00 +0000597 */
598 static Local<Script> Compile(Handle<String> source,
Andrei Popescu402d9372010-02-26 13:31:12 +0000599 ScriptOrigin* origin = NULL,
600 ScriptData* pre_data = NULL,
601 Handle<String> script_data = Handle<String>());
602
603 /**
604 * Compiles the specified script using the specified file name
605 * object (typically a string) as the script's origin.
606 *
607 * \param source Script source code.
608 * \param file_name File name to use as script's origin
609 * \param script_data Arbitrary data associated with script. Using
610 * this has same effect as calling SetData(), but makes data available
611 * earlier (i.e. to compile event handlers).
612 * \return Compiled script object, bound to the context that was active
613 * when this function was called. When run it will always use this
614 * context.
615 */
616 static Local<Script> Compile(Handle<String> source,
617 Handle<Value> file_name,
618 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000619
620 /**
621 * Runs the script returning the resulting value. If the script is
622 * context independent (created using ::New) it will be run in the
623 * currently entered context. If it is context specific (created
624 * using ::Compile) it will be run in the context in which it was
625 * compiled.
626 */
627 Local<Value> Run();
628
629 /**
630 * Returns the script id value.
631 */
632 Local<Value> Id();
633
634 /**
635 * Associate an additional data object with the script. This is mainly used
636 * with the debugger as this data object is only available through the
637 * debugger API.
638 */
Steve Blockd0582a62009-12-15 09:54:21 +0000639 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000640};
641
642
643/**
644 * An error message.
645 */
646class V8EXPORT Message {
647 public:
648 Local<String> Get() const;
649 Local<String> GetSourceLine() const;
650
651 /**
652 * Returns the resource name for the script from where the function causing
653 * the error originates.
654 */
655 Handle<Value> GetScriptResourceName() const;
656
657 /**
658 * Returns the resource data for the script from where the function causing
659 * the error originates.
660 */
661 Handle<Value> GetScriptData() const;
662
663 /**
664 * Returns the number, 1-based, of the line where the error occurred.
665 */
666 int GetLineNumber() const;
667
668 /**
669 * Returns the index within the script of the first character where
670 * the error occurred.
671 */
672 int GetStartPosition() const;
673
674 /**
675 * Returns the index within the script of the last character where
676 * the error occurred.
677 */
678 int GetEndPosition() const;
679
680 /**
681 * Returns the index within the line of the first character where
682 * the error occurred.
683 */
684 int GetStartColumn() const;
685
686 /**
687 * Returns the index within the line of the last character where
688 * the error occurred.
689 */
690 int GetEndColumn() const;
691
692 // TODO(1245381): Print to a string instead of on a FILE.
693 static void PrintCurrentStackTrace(FILE* out);
694};
695
696
697// --- V a l u e ---
698
699
700/**
701 * The superclass of all JavaScript values and objects.
702 */
703class V8EXPORT Value : public Data {
704 public:
705
706 /**
707 * Returns true if this value is the undefined value. See ECMA-262
708 * 4.3.10.
709 */
710 bool IsUndefined() const;
711
712 /**
713 * Returns true if this value is the null value. See ECMA-262
714 * 4.3.11.
715 */
716 bool IsNull() const;
717
718 /**
719 * Returns true if this value is true.
720 */
721 bool IsTrue() const;
722
723 /**
724 * Returns true if this value is false.
725 */
726 bool IsFalse() const;
727
728 /**
729 * Returns true if this value is an instance of the String type.
730 * See ECMA-262 8.4.
731 */
732 inline bool IsString() const;
733
734 /**
735 * Returns true if this value is a function.
736 */
737 bool IsFunction() const;
738
739 /**
740 * Returns true if this value is an array.
741 */
742 bool IsArray() const;
743
744 /**
745 * Returns true if this value is an object.
746 */
747 bool IsObject() const;
748
749 /**
750 * Returns true if this value is boolean.
751 */
752 bool IsBoolean() const;
753
754 /**
755 * Returns true if this value is a number.
756 */
757 bool IsNumber() const;
758
759 /**
760 * Returns true if this value is external.
761 */
762 bool IsExternal() const;
763
764 /**
765 * Returns true if this value is a 32-bit signed integer.
766 */
767 bool IsInt32() const;
768
769 /**
Steve Block6ded16b2010-05-10 14:33:55 +0100770 * Returns true if this value is a 32-bit unsigned integer.
771 */
772 bool IsUint32() const;
773
774 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000775 * Returns true if this value is a Date.
776 */
777 bool IsDate() const;
778
779 Local<Boolean> ToBoolean() const;
780 Local<Number> ToNumber() const;
781 Local<String> ToString() const;
782 Local<String> ToDetailString() const;
783 Local<Object> ToObject() const;
784 Local<Integer> ToInteger() const;
785 Local<Uint32> ToUint32() const;
786 Local<Int32> ToInt32() const;
787
788 /**
789 * Attempts to convert a string to an array index.
790 * Returns an empty handle if the conversion fails.
791 */
792 Local<Uint32> ToArrayIndex() const;
793
794 bool BooleanValue() const;
795 double NumberValue() const;
796 int64_t IntegerValue() const;
797 uint32_t Uint32Value() const;
798 int32_t Int32Value() const;
799
800 /** JS == */
801 bool Equals(Handle<Value> that) const;
802 bool StrictEquals(Handle<Value> that) const;
Steve Block3ce2e202009-11-05 08:53:23 +0000803
Steve Blocka7e24c12009-10-30 11:49:00 +0000804 private:
805 inline bool QuickIsString() const;
806 bool FullIsString() const;
807};
808
809
810/**
811 * The superclass of primitive values. See ECMA-262 4.3.2.
812 */
813class V8EXPORT Primitive : public Value { };
814
815
816/**
817 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
818 * or false value.
819 */
820class V8EXPORT Boolean : public Primitive {
821 public:
822 bool Value() const;
823 static inline Handle<Boolean> New(bool value);
824};
825
826
827/**
828 * A JavaScript string value (ECMA-262, 4.3.17).
829 */
830class V8EXPORT String : public Primitive {
831 public:
832
833 /**
834 * Returns the number of characters in this string.
835 */
836 int Length() const;
837
838 /**
839 * Returns the number of bytes in the UTF-8 encoded
840 * representation of this string.
841 */
842 int Utf8Length() const;
843
844 /**
845 * Write the contents of the string to an external buffer.
846 * If no arguments are given, expects the buffer to be large
847 * enough to hold the entire string and NULL terminator. Copies
848 * the contents of the string and the NULL terminator into the
849 * buffer.
850 *
851 * Copies up to length characters into the output buffer.
852 * Only null-terminates if there is enough space in the buffer.
853 *
854 * \param buffer The buffer into which the string will be copied.
855 * \param start The starting position within the string at which
856 * copying begins.
857 * \param length The number of bytes to copy from the string.
Steve Block6ded16b2010-05-10 14:33:55 +0100858 * \param nchars_ref The number of characters written, can be NULL.
859 * \param hints Various hints that might affect performance of this or
860 * subsequent operations.
861 * \return The number of bytes copied to the buffer
Steve Blocka7e24c12009-10-30 11:49:00 +0000862 * excluding the NULL terminator.
863 */
Steve Block6ded16b2010-05-10 14:33:55 +0100864 enum WriteHints {
865 NO_HINTS = 0,
866 HINT_MANY_WRITES_EXPECTED = 1
867 };
868
869 int Write(uint16_t* buffer,
870 int start = 0,
871 int length = -1,
872 WriteHints hints = NO_HINTS) const; // UTF-16
873 int WriteAscii(char* buffer,
874 int start = 0,
875 int length = -1,
876 WriteHints hints = NO_HINTS) const; // ASCII
877 int WriteUtf8(char* buffer,
878 int length = -1,
879 int* nchars_ref = NULL,
880 WriteHints hints = NO_HINTS) const; // UTF-8
Steve Blocka7e24c12009-10-30 11:49:00 +0000881
882 /**
883 * A zero length string.
884 */
885 static v8::Local<v8::String> Empty();
886
887 /**
888 * Returns true if the string is external
889 */
890 bool IsExternal() const;
891
892 /**
893 * Returns true if the string is both external and ascii
894 */
895 bool IsExternalAscii() const;
Leon Clarkee46be812010-01-19 14:06:41 +0000896
897 class V8EXPORT ExternalStringResourceBase {
898 public:
899 virtual ~ExternalStringResourceBase() {}
900 protected:
901 ExternalStringResourceBase() {}
902 private:
903 // Disallow copying and assigning.
904 ExternalStringResourceBase(const ExternalStringResourceBase&);
905 void operator=(const ExternalStringResourceBase&);
906 };
907
Steve Blocka7e24c12009-10-30 11:49:00 +0000908 /**
909 * An ExternalStringResource is a wrapper around a two-byte string
910 * buffer that resides outside V8's heap. Implement an
911 * ExternalStringResource to manage the life cycle of the underlying
912 * buffer. Note that the string data must be immutable.
913 */
Leon Clarkee46be812010-01-19 14:06:41 +0000914 class V8EXPORT ExternalStringResource
915 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +0000916 public:
917 /**
918 * Override the destructor to manage the life cycle of the underlying
919 * buffer.
920 */
921 virtual ~ExternalStringResource() {}
922 /** The string data from the underlying buffer.*/
923 virtual const uint16_t* data() const = 0;
924 /** The length of the string. That is, the number of two-byte characters.*/
925 virtual size_t length() const = 0;
926 protected:
927 ExternalStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +0000928 };
929
930 /**
931 * An ExternalAsciiStringResource is a wrapper around an ascii
932 * string buffer that resides outside V8's heap. Implement an
933 * ExternalAsciiStringResource to manage the life cycle of the
934 * underlying buffer. Note that the string data must be immutable
935 * and that the data must be strict 7-bit ASCII, not Latin1 or
936 * UTF-8, which would require special treatment internally in the
937 * engine and, in the case of UTF-8, do not allow efficient indexing.
938 * Use String::New or convert to 16 bit data for non-ASCII.
939 */
940
Leon Clarkee46be812010-01-19 14:06:41 +0000941 class V8EXPORT ExternalAsciiStringResource
942 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +0000943 public:
944 /**
945 * Override the destructor to manage the life cycle of the underlying
946 * buffer.
947 */
948 virtual ~ExternalAsciiStringResource() {}
949 /** The string data from the underlying buffer.*/
950 virtual const char* data() const = 0;
951 /** The number of ascii characters in the string.*/
952 virtual size_t length() const = 0;
953 protected:
954 ExternalAsciiStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +0000955 };
956
957 /**
958 * Get the ExternalStringResource for an external string. Returns
959 * NULL if IsExternal() doesn't return true.
960 */
961 inline ExternalStringResource* GetExternalStringResource() const;
962
963 /**
964 * Get the ExternalAsciiStringResource for an external ascii string.
965 * Returns NULL if IsExternalAscii() doesn't return true.
966 */
967 ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
968
969 static inline String* Cast(v8::Value* obj);
970
971 /**
972 * Allocates a new string from either utf-8 encoded or ascii data.
973 * The second parameter 'length' gives the buffer length.
974 * If the data is utf-8 encoded, the caller must
975 * be careful to supply the length parameter.
976 * If it is not given, the function calls
977 * 'strlen' to determine the buffer length, it might be
978 * wrong if 'data' contains a null character.
979 */
980 static Local<String> New(const char* data, int length = -1);
981
982 /** Allocates a new string from utf16 data.*/
983 static Local<String> New(const uint16_t* data, int length = -1);
984
985 /** Creates a symbol. Returns one if it exists already.*/
986 static Local<String> NewSymbol(const char* data, int length = -1);
987
988 /**
Steve Block3ce2e202009-11-05 08:53:23 +0000989 * Creates a new string by concatenating the left and the right strings
990 * passed in as parameters.
991 */
992 static Local<String> Concat(Handle<String> left, Handle<String>right);
993
994 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000995 * Creates a new external string using the data defined in the given
996 * resource. The resource is deleted when the external string is no
997 * longer live on V8's heap. The caller of this function should not
998 * delete or modify the resource. Neither should the underlying buffer be
999 * deallocated or modified except through the destructor of the
1000 * external string resource.
1001 */
1002 static Local<String> NewExternal(ExternalStringResource* resource);
1003
1004 /**
1005 * Associate an external string resource with this string by transforming it
1006 * in place so that existing references to this string in the JavaScript heap
1007 * will use the external string resource. The external string resource's
1008 * character contents needs to be equivalent to this string.
1009 * Returns true if the string has been changed to be an external string.
1010 * The string is not modified if the operation fails.
1011 */
1012 bool MakeExternal(ExternalStringResource* resource);
1013
1014 /**
1015 * Creates a new external string using the ascii data defined in the given
1016 * resource. The resource is deleted when the external string is no
1017 * longer live on V8's heap. The caller of this function should not
1018 * delete or modify the resource. Neither should the underlying buffer be
1019 * deallocated or modified except through the destructor of the
1020 * external string resource.
1021 */
1022 static Local<String> NewExternal(ExternalAsciiStringResource* resource);
1023
1024 /**
1025 * Associate an external string resource with this string by transforming it
1026 * in place so that existing references to this string in the JavaScript heap
1027 * will use the external string resource. The external string resource's
1028 * character contents needs to be equivalent to this string.
1029 * Returns true if the string has been changed to be an external string.
1030 * The string is not modified if the operation fails.
1031 */
1032 bool MakeExternal(ExternalAsciiStringResource* resource);
1033
1034 /**
1035 * Returns true if this string can be made external.
1036 */
1037 bool CanMakeExternal();
1038
1039 /** Creates an undetectable string from the supplied ascii or utf-8 data.*/
1040 static Local<String> NewUndetectable(const char* data, int length = -1);
1041
1042 /** Creates an undetectable string from the supplied utf-16 data.*/
1043 static Local<String> NewUndetectable(const uint16_t* data, int length = -1);
1044
1045 /**
1046 * Converts an object to a utf8-encoded character array. Useful if
1047 * you want to print the object. If conversion to a string fails
1048 * (eg. due to an exception in the toString() method of the object)
1049 * then the length() method returns 0 and the * operator returns
1050 * NULL.
1051 */
1052 class V8EXPORT Utf8Value {
1053 public:
1054 explicit Utf8Value(Handle<v8::Value> obj);
1055 ~Utf8Value();
1056 char* operator*() { return str_; }
1057 const char* operator*() const { return str_; }
1058 int length() const { return length_; }
1059 private:
1060 char* str_;
1061 int length_;
1062
1063 // Disallow copying and assigning.
1064 Utf8Value(const Utf8Value&);
1065 void operator=(const Utf8Value&);
1066 };
1067
1068 /**
1069 * Converts an object to an ascii string.
1070 * Useful if you want to print the object.
1071 * If conversion to a string fails (eg. due to an exception in the toString()
1072 * method of the object) then the length() method returns 0 and the * operator
1073 * returns NULL.
1074 */
1075 class V8EXPORT AsciiValue {
1076 public:
1077 explicit AsciiValue(Handle<v8::Value> obj);
1078 ~AsciiValue();
1079 char* operator*() { return str_; }
1080 const char* operator*() const { return str_; }
1081 int length() const { return length_; }
1082 private:
1083 char* str_;
1084 int length_;
1085
1086 // Disallow copying and assigning.
1087 AsciiValue(const AsciiValue&);
1088 void operator=(const AsciiValue&);
1089 };
1090
1091 /**
1092 * Converts an object to a two-byte string.
1093 * If conversion to a string fails (eg. due to an exception in the toString()
1094 * method of the object) then the length() method returns 0 and the * operator
1095 * returns NULL.
1096 */
1097 class V8EXPORT Value {
1098 public:
1099 explicit Value(Handle<v8::Value> obj);
1100 ~Value();
1101 uint16_t* operator*() { return str_; }
1102 const uint16_t* operator*() const { return str_; }
1103 int length() const { return length_; }
1104 private:
1105 uint16_t* str_;
1106 int length_;
1107
1108 // Disallow copying and assigning.
1109 Value(const Value&);
1110 void operator=(const Value&);
1111 };
Steve Block3ce2e202009-11-05 08:53:23 +00001112
Steve Blocka7e24c12009-10-30 11:49:00 +00001113 private:
1114 void VerifyExternalStringResource(ExternalStringResource* val) const;
1115 static void CheckCast(v8::Value* obj);
1116};
1117
1118
1119/**
1120 * A JavaScript number value (ECMA-262, 4.3.20)
1121 */
1122class V8EXPORT Number : public Primitive {
1123 public:
1124 double Value() const;
1125 static Local<Number> New(double value);
1126 static inline Number* Cast(v8::Value* obj);
1127 private:
1128 Number();
1129 static void CheckCast(v8::Value* obj);
1130};
1131
1132
1133/**
1134 * A JavaScript value representing a signed integer.
1135 */
1136class V8EXPORT Integer : public Number {
1137 public:
1138 static Local<Integer> New(int32_t value);
Steve Block3ce2e202009-11-05 08:53:23 +00001139 static Local<Integer> NewFromUnsigned(uint32_t value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001140 int64_t Value() const;
1141 static inline Integer* Cast(v8::Value* obj);
1142 private:
1143 Integer();
1144 static void CheckCast(v8::Value* obj);
1145};
1146
1147
1148/**
1149 * A JavaScript value representing a 32-bit signed integer.
1150 */
1151class V8EXPORT Int32 : public Integer {
1152 public:
1153 int32_t Value() const;
1154 private:
1155 Int32();
1156};
1157
1158
1159/**
1160 * A JavaScript value representing a 32-bit unsigned integer.
1161 */
1162class V8EXPORT Uint32 : public Integer {
1163 public:
1164 uint32_t Value() const;
1165 private:
1166 Uint32();
1167};
1168
1169
1170/**
1171 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1172 */
1173class V8EXPORT Date : public Value {
1174 public:
1175 static Local<Value> New(double time);
1176
1177 /**
1178 * A specialization of Value::NumberValue that is more efficient
1179 * because we know the structure of this object.
1180 */
1181 double NumberValue() const;
1182
1183 static inline Date* Cast(v8::Value* obj);
1184 private:
1185 static void CheckCast(v8::Value* obj);
1186};
1187
1188
1189enum PropertyAttribute {
1190 None = 0,
1191 ReadOnly = 1 << 0,
1192 DontEnum = 1 << 1,
1193 DontDelete = 1 << 2
1194};
1195
Steve Block3ce2e202009-11-05 08:53:23 +00001196enum ExternalArrayType {
1197 kExternalByteArray = 1,
1198 kExternalUnsignedByteArray,
1199 kExternalShortArray,
1200 kExternalUnsignedShortArray,
1201 kExternalIntArray,
1202 kExternalUnsignedIntArray,
1203 kExternalFloatArray
1204};
1205
Steve Blocka7e24c12009-10-30 11:49:00 +00001206/**
1207 * A JavaScript object (ECMA-262, 4.3.3)
1208 */
1209class V8EXPORT Object : public Value {
1210 public:
1211 bool Set(Handle<Value> key,
1212 Handle<Value> value,
1213 PropertyAttribute attribs = None);
1214
Steve Block6ded16b2010-05-10 14:33:55 +01001215 bool Set(uint32_t index,
1216 Handle<Value> value);
1217
Steve Blocka7e24c12009-10-30 11:49:00 +00001218 // Sets a local property on this object bypassing interceptors and
1219 // overriding accessors or read-only properties.
1220 //
1221 // Note that if the object has an interceptor the property will be set
1222 // locally, but since the interceptor takes precedence the local property
1223 // will only be returned if the interceptor doesn't return a value.
1224 //
1225 // Note also that this only works for named properties.
1226 bool ForceSet(Handle<Value> key,
1227 Handle<Value> value,
1228 PropertyAttribute attribs = None);
1229
1230 Local<Value> Get(Handle<Value> key);
1231
Steve Block6ded16b2010-05-10 14:33:55 +01001232 Local<Value> Get(uint32_t index);
1233
Steve Blocka7e24c12009-10-30 11:49:00 +00001234 // TODO(1245389): Replace the type-specific versions of these
1235 // functions with generic ones that accept a Handle<Value> key.
1236 bool Has(Handle<String> key);
1237
1238 bool Delete(Handle<String> key);
1239
1240 // Delete a property on this object bypassing interceptors and
1241 // ignoring dont-delete attributes.
1242 bool ForceDelete(Handle<Value> key);
1243
1244 bool Has(uint32_t index);
1245
1246 bool Delete(uint32_t index);
1247
1248 /**
1249 * Returns an array containing the names of the enumerable properties
1250 * of this object, including properties from prototype objects. The
1251 * array returned by this method contains the same values as would
1252 * be enumerated by a for-in statement over this object.
1253 */
1254 Local<Array> GetPropertyNames();
1255
1256 /**
1257 * Get the prototype object. This does not skip objects marked to
1258 * be skipped by __proto__ and it does not consult the security
1259 * handler.
1260 */
1261 Local<Value> GetPrototype();
1262
1263 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00001264 * Set the prototype object. This does not skip objects marked to
1265 * be skipped by __proto__ and it does not consult the security
1266 * handler.
1267 */
1268 bool SetPrototype(Handle<Value> prototype);
1269
1270 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001271 * Finds an instance of the given function template in the prototype
1272 * chain.
1273 */
1274 Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
1275
1276 /**
1277 * Call builtin Object.prototype.toString on this object.
1278 * This is different from Value::ToString() that may call
1279 * user-defined toString function. This one does not.
1280 */
1281 Local<String> ObjectProtoToString();
1282
1283 /** Gets the number of internal fields for this Object. */
1284 int InternalFieldCount();
1285 /** Gets the value in an internal field. */
1286 inline Local<Value> GetInternalField(int index);
1287 /** Sets the value in an internal field. */
1288 void SetInternalField(int index, Handle<Value> value);
1289
1290 /** Gets a native pointer from an internal field. */
1291 inline void* GetPointerFromInternalField(int index);
Steve Block3ce2e202009-11-05 08:53:23 +00001292
Steve Blocka7e24c12009-10-30 11:49:00 +00001293 /** Sets a native pointer in an internal field. */
1294 void SetPointerInInternalField(int index, void* value);
1295
1296 // Testers for local properties.
1297 bool HasRealNamedProperty(Handle<String> key);
1298 bool HasRealIndexedProperty(uint32_t index);
1299 bool HasRealNamedCallbackProperty(Handle<String> key);
1300
1301 /**
1302 * If result.IsEmpty() no real property was located in the prototype chain.
1303 * This means interceptors in the prototype chain are not called.
1304 */
1305 Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
1306
1307 /**
1308 * If result.IsEmpty() no real property was located on the object or
1309 * in the prototype chain.
1310 * This means interceptors in the prototype chain are not called.
1311 */
1312 Local<Value> GetRealNamedProperty(Handle<String> key);
1313
1314 /** Tests for a named lookup interceptor.*/
1315 bool HasNamedLookupInterceptor();
1316
1317 /** Tests for an index lookup interceptor.*/
1318 bool HasIndexedLookupInterceptor();
1319
1320 /**
1321 * Turns on access check on the object if the object is an instance of
1322 * a template that has access check callbacks. If an object has no
1323 * access check info, the object cannot be accessed by anyone.
1324 */
1325 void TurnOnAccessCheck();
1326
1327 /**
1328 * Returns the identity hash for this object. The current implemenation uses
1329 * a hidden property on the object to store the identity hash.
1330 *
1331 * The return value will never be 0. Also, it is not guaranteed to be
1332 * unique.
1333 */
1334 int GetIdentityHash();
1335
1336 /**
1337 * Access hidden properties on JavaScript objects. These properties are
1338 * hidden from the executing JavaScript and only accessible through the V8
1339 * C++ API. Hidden properties introduced by V8 internally (for example the
1340 * identity hash) are prefixed with "v8::".
1341 */
1342 bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1343 Local<Value> GetHiddenValue(Handle<String> key);
1344 bool DeleteHiddenValue(Handle<String> key);
Steve Block3ce2e202009-11-05 08:53:23 +00001345
Steve Blocka7e24c12009-10-30 11:49:00 +00001346 /**
1347 * Returns true if this is an instance of an api function (one
1348 * created from a function created from a function template) and has
1349 * been modified since it was created. Note that this method is
1350 * conservative and may return true for objects that haven't actually
1351 * been modified.
1352 */
1353 bool IsDirty();
1354
1355 /**
1356 * Clone this object with a fast but shallow copy. Values will point
1357 * to the same values as the original object.
1358 */
1359 Local<Object> Clone();
1360
1361 /**
1362 * Set the backing store of the indexed properties to be managed by the
1363 * embedding layer. Access to the indexed properties will follow the rules
1364 * spelled out in CanvasPixelArray.
1365 * Note: The embedding program still owns the data and needs to ensure that
1366 * the backing store is preserved while V8 has a reference.
1367 */
1368 void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
1369
Steve Block3ce2e202009-11-05 08:53:23 +00001370 /**
1371 * Set the backing store of the indexed properties to be managed by the
1372 * embedding layer. Access to the indexed properties will follow the rules
1373 * spelled out for the CanvasArray subtypes in the WebGL specification.
1374 * Note: The embedding program still owns the data and needs to ensure that
1375 * the backing store is preserved while V8 has a reference.
1376 */
1377 void SetIndexedPropertiesToExternalArrayData(void* data,
1378 ExternalArrayType array_type,
1379 int number_of_elements);
1380
Steve Blocka7e24c12009-10-30 11:49:00 +00001381 static Local<Object> New();
1382 static inline Object* Cast(Value* obj);
1383 private:
1384 Object();
1385 static void CheckCast(Value* obj);
1386 Local<Value> CheckedGetInternalField(int index);
Steve Block3ce2e202009-11-05 08:53:23 +00001387 void* SlowGetPointerFromInternalField(int index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001388
1389 /**
1390 * If quick access to the internal field is possible this method
Steve Block3ce2e202009-11-05 08:53:23 +00001391 * returns the value. Otherwise an empty handle is returned.
Steve Blocka7e24c12009-10-30 11:49:00 +00001392 */
1393 inline Local<Value> UncheckedGetInternalField(int index);
1394};
1395
1396
1397/**
1398 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1399 */
1400class V8EXPORT Array : public Object {
1401 public:
1402 uint32_t Length() const;
1403
1404 /**
1405 * Clones an element at index |index|. Returns an empty
1406 * handle if cloning fails (for any reason).
1407 */
1408 Local<Object> CloneElementAt(uint32_t index);
1409
1410 static Local<Array> New(int length = 0);
1411 static inline Array* Cast(Value* obj);
1412 private:
1413 Array();
1414 static void CheckCast(Value* obj);
1415};
1416
1417
1418/**
1419 * A JavaScript function object (ECMA-262, 15.3).
1420 */
1421class V8EXPORT Function : public Object {
1422 public:
1423 Local<Object> NewInstance() const;
1424 Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1425 Local<Value> Call(Handle<Object> recv, int argc, Handle<Value> argv[]);
1426 void SetName(Handle<String> name);
1427 Handle<Value> GetName() const;
Andrei Popescu402d9372010-02-26 13:31:12 +00001428
1429 /**
1430 * Returns zero based line number of function body and
1431 * kLineOffsetNotFound if no information available.
1432 */
1433 int GetScriptLineNumber() const;
1434 ScriptOrigin GetScriptOrigin() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001435 static inline Function* Cast(Value* obj);
Andrei Popescu402d9372010-02-26 13:31:12 +00001436 static const int kLineOffsetNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00001437 private:
1438 Function();
1439 static void CheckCast(Value* obj);
1440};
1441
1442
1443/**
1444 * A JavaScript value that wraps a C++ void*. This type of value is
1445 * mainly used to associate C++ data structures with JavaScript
1446 * objects.
1447 *
1448 * The Wrap function V8 will return the most optimal Value object wrapping the
1449 * C++ void*. The type of the value is not guaranteed to be an External object
1450 * and no assumptions about its type should be made. To access the wrapped
1451 * value Unwrap should be used, all other operations on that object will lead
1452 * to unpredictable results.
1453 */
1454class V8EXPORT External : public Value {
1455 public:
1456 static Local<Value> Wrap(void* data);
1457 static inline void* Unwrap(Handle<Value> obj);
1458
1459 static Local<External> New(void* value);
1460 static inline External* Cast(Value* obj);
1461 void* Value() const;
1462 private:
1463 External();
1464 static void CheckCast(v8::Value* obj);
1465 static inline void* QuickUnwrap(Handle<v8::Value> obj);
1466 static void* FullUnwrap(Handle<v8::Value> obj);
1467};
1468
1469
1470// --- T e m p l a t e s ---
1471
1472
1473/**
1474 * The superclass of object and function templates.
1475 */
1476class V8EXPORT Template : public Data {
1477 public:
1478 /** Adds a property to each instance created by this template.*/
1479 void Set(Handle<String> name, Handle<Data> value,
1480 PropertyAttribute attributes = None);
1481 inline void Set(const char* name, Handle<Data> value);
1482 private:
1483 Template();
1484
1485 friend class ObjectTemplate;
1486 friend class FunctionTemplate;
1487};
1488
1489
1490/**
1491 * The argument information given to function call callbacks. This
1492 * class provides access to information about the context of the call,
1493 * including the receiver, the number and values of arguments, and
1494 * the holder of the function.
1495 */
1496class V8EXPORT Arguments {
1497 public:
1498 inline int Length() const;
1499 inline Local<Value> operator[](int i) const;
1500 inline Local<Function> Callee() const;
1501 inline Local<Object> This() const;
1502 inline Local<Object> Holder() const;
1503 inline bool IsConstructCall() const;
1504 inline Local<Value> Data() const;
1505 private:
1506 Arguments();
1507 friend class ImplementationUtilities;
1508 inline Arguments(Local<Value> data,
1509 Local<Object> holder,
1510 Local<Function> callee,
1511 bool is_construct_call,
1512 void** values, int length);
1513 Local<Value> data_;
1514 Local<Object> holder_;
1515 Local<Function> callee_;
1516 bool is_construct_call_;
1517 void** values_;
1518 int length_;
1519};
1520
1521
1522/**
1523 * The information passed to an accessor callback about the context
1524 * of the property access.
1525 */
1526class V8EXPORT AccessorInfo {
1527 public:
1528 inline AccessorInfo(internal::Object** args)
1529 : args_(args) { }
1530 inline Local<Value> Data() const;
1531 inline Local<Object> This() const;
1532 inline Local<Object> Holder() const;
1533 private:
1534 internal::Object** args_;
1535};
1536
1537
1538typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
1539
1540typedef int (*LookupCallback)(Local<Object> self, Local<String> name);
1541
1542/**
1543 * Accessor[Getter|Setter] are used as callback functions when
1544 * setting|getting a particular property. See objectTemplate::SetAccessor.
1545 */
1546typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1547 const AccessorInfo& info);
1548
1549
1550typedef void (*AccessorSetter)(Local<String> property,
1551 Local<Value> value,
1552 const AccessorInfo& info);
1553
1554
1555/**
1556 * NamedProperty[Getter|Setter] are used as interceptors on object.
1557 * See ObjectTemplate::SetNamedPropertyHandler.
1558 */
1559typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
1560 const AccessorInfo& info);
1561
1562
1563/**
1564 * Returns the value if the setter intercepts the request.
1565 * Otherwise, returns an empty handle.
1566 */
1567typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
1568 Local<Value> value,
1569 const AccessorInfo& info);
1570
1571
1572/**
1573 * Returns a non-empty handle if the interceptor intercepts the request.
1574 * The result is true if the property exists and false otherwise.
1575 */
1576typedef Handle<Boolean> (*NamedPropertyQuery)(Local<String> property,
1577 const AccessorInfo& info);
1578
1579
1580/**
1581 * Returns a non-empty handle if the deleter intercepts the request.
1582 * The return value is true if the property could be deleted and false
1583 * otherwise.
1584 */
1585typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
1586 const AccessorInfo& info);
1587
1588/**
1589 * Returns an array containing the names of the properties the named
1590 * property getter intercepts.
1591 */
1592typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
1593
1594
1595/**
1596 * Returns the value of the property if the getter intercepts the
1597 * request. Otherwise, returns an empty handle.
1598 */
1599typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
1600 const AccessorInfo& info);
1601
1602
1603/**
1604 * Returns the value if the setter intercepts the request.
1605 * Otherwise, returns an empty handle.
1606 */
1607typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
1608 Local<Value> value,
1609 const AccessorInfo& info);
1610
1611
1612/**
1613 * Returns a non-empty handle if the interceptor intercepts the request.
1614 * The result is true if the property exists and false otherwise.
1615 */
1616typedef Handle<Boolean> (*IndexedPropertyQuery)(uint32_t index,
1617 const AccessorInfo& info);
1618
1619/**
1620 * Returns a non-empty handle if the deleter intercepts the request.
1621 * The return value is true if the property could be deleted and false
1622 * otherwise.
1623 */
1624typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
1625 const AccessorInfo& info);
1626
1627/**
1628 * Returns an array containing the indices of the properties the
1629 * indexed property getter intercepts.
1630 */
1631typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
1632
1633
1634/**
1635 * Access control specifications.
1636 *
1637 * Some accessors should be accessible across contexts. These
1638 * accessors have an explicit access control parameter which specifies
1639 * the kind of cross-context access that should be allowed.
1640 *
1641 * Additionally, for security, accessors can prohibit overwriting by
1642 * accessors defined in JavaScript. For objects that have such
1643 * accessors either locally or in their prototype chain it is not
1644 * possible to overwrite the accessor by using __defineGetter__ or
1645 * __defineSetter__ from JavaScript code.
1646 */
1647enum AccessControl {
1648 DEFAULT = 0,
1649 ALL_CAN_READ = 1,
1650 ALL_CAN_WRITE = 1 << 1,
1651 PROHIBITS_OVERWRITING = 1 << 2
1652};
1653
1654
1655/**
1656 * Access type specification.
1657 */
1658enum AccessType {
1659 ACCESS_GET,
1660 ACCESS_SET,
1661 ACCESS_HAS,
1662 ACCESS_DELETE,
1663 ACCESS_KEYS
1664};
1665
1666
1667/**
1668 * Returns true if cross-context access should be allowed to the named
1669 * property with the given key on the host object.
1670 */
1671typedef bool (*NamedSecurityCallback)(Local<Object> host,
1672 Local<Value> key,
1673 AccessType type,
1674 Local<Value> data);
1675
1676
1677/**
1678 * Returns true if cross-context access should be allowed to the indexed
1679 * property with the given index on the host object.
1680 */
1681typedef bool (*IndexedSecurityCallback)(Local<Object> host,
1682 uint32_t index,
1683 AccessType type,
1684 Local<Value> data);
1685
1686
1687/**
1688 * A FunctionTemplate is used to create functions at runtime. There
1689 * can only be one function created from a FunctionTemplate in a
1690 * context. The lifetime of the created function is equal to the
1691 * lifetime of the context. So in case the embedder needs to create
1692 * temporary functions that can be collected using Scripts is
1693 * preferred.
1694 *
1695 * A FunctionTemplate can have properties, these properties are added to the
1696 * function object when it is created.
1697 *
1698 * A FunctionTemplate has a corresponding instance template which is
1699 * used to create object instances when the function is used as a
1700 * constructor. Properties added to the instance template are added to
1701 * each object instance.
1702 *
1703 * A FunctionTemplate can have a prototype template. The prototype template
1704 * is used to create the prototype object of the function.
1705 *
1706 * The following example shows how to use a FunctionTemplate:
1707 *
1708 * \code
1709 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
1710 * t->Set("func_property", v8::Number::New(1));
1711 *
1712 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
1713 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
1714 * proto_t->Set("proto_const", v8::Number::New(2));
1715 *
1716 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
1717 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
1718 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
1719 * instance_t->Set("instance_property", Number::New(3));
1720 *
1721 * v8::Local<v8::Function> function = t->GetFunction();
1722 * v8::Local<v8::Object> instance = function->NewInstance();
1723 * \endcode
1724 *
1725 * Let's use "function" as the JS variable name of the function object
1726 * and "instance" for the instance object created above. The function
1727 * and the instance will have the following properties:
1728 *
1729 * \code
1730 * func_property in function == true;
1731 * function.func_property == 1;
1732 *
1733 * function.prototype.proto_method() invokes 'InvokeCallback'
1734 * function.prototype.proto_const == 2;
1735 *
1736 * instance instanceof function == true;
1737 * instance.instance_accessor calls 'InstanceAccessorCallback'
1738 * instance.instance_property == 3;
1739 * \endcode
1740 *
1741 * A FunctionTemplate can inherit from another one by calling the
1742 * FunctionTemplate::Inherit method. The following graph illustrates
1743 * the semantics of inheritance:
1744 *
1745 * \code
1746 * FunctionTemplate Parent -> Parent() . prototype -> { }
1747 * ^ ^
1748 * | Inherit(Parent) | .__proto__
1749 * | |
1750 * FunctionTemplate Child -> Child() . prototype -> { }
1751 * \endcode
1752 *
1753 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
1754 * object of the Child() function has __proto__ pointing to the
1755 * Parent() function's prototype object. An instance of the Child
1756 * function has all properties on Parent's instance templates.
1757 *
1758 * Let Parent be the FunctionTemplate initialized in the previous
1759 * section and create a Child FunctionTemplate by:
1760 *
1761 * \code
1762 * Local<FunctionTemplate> parent = t;
1763 * Local<FunctionTemplate> child = FunctionTemplate::New();
1764 * child->Inherit(parent);
1765 *
1766 * Local<Function> child_function = child->GetFunction();
1767 * Local<Object> child_instance = child_function->NewInstance();
1768 * \endcode
1769 *
1770 * The Child function and Child instance will have the following
1771 * properties:
1772 *
1773 * \code
1774 * child_func.prototype.__proto__ == function.prototype;
1775 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
1776 * child_instance.instance_property == 3;
1777 * \endcode
1778 */
1779class V8EXPORT FunctionTemplate : public Template {
1780 public:
1781 /** Creates a function template.*/
1782 static Local<FunctionTemplate> New(
1783 InvocationCallback callback = 0,
1784 Handle<Value> data = Handle<Value>(),
1785 Handle<Signature> signature = Handle<Signature>());
1786 /** Returns the unique function instance in the current execution context.*/
1787 Local<Function> GetFunction();
1788
1789 /**
1790 * Set the call-handler callback for a FunctionTemplate. This
1791 * callback is called whenever the function created from this
1792 * FunctionTemplate is called.
1793 */
1794 void SetCallHandler(InvocationCallback callback,
1795 Handle<Value> data = Handle<Value>());
1796
1797 /** Get the InstanceTemplate. */
1798 Local<ObjectTemplate> InstanceTemplate();
1799
1800 /** Causes the function template to inherit from a parent function template.*/
1801 void Inherit(Handle<FunctionTemplate> parent);
1802
1803 /**
1804 * A PrototypeTemplate is the template used to create the prototype object
1805 * of the function created by this template.
1806 */
1807 Local<ObjectTemplate> PrototypeTemplate();
1808
1809
1810 /**
1811 * Set the class name of the FunctionTemplate. This is used for
1812 * printing objects created with the function created from the
1813 * FunctionTemplate as its constructor.
1814 */
1815 void SetClassName(Handle<String> name);
1816
1817 /**
1818 * Determines whether the __proto__ accessor ignores instances of
1819 * the function template. If instances of the function template are
1820 * ignored, __proto__ skips all instances and instead returns the
1821 * next object in the prototype chain.
1822 *
1823 * Call with a value of true to make the __proto__ accessor ignore
1824 * instances of the function template. Call with a value of false
1825 * to make the __proto__ accessor not ignore instances of the
1826 * function template. By default, instances of a function template
1827 * are not ignored.
1828 */
1829 void SetHiddenPrototype(bool value);
1830
1831 /**
1832 * Returns true if the given object is an instance of this function
1833 * template.
1834 */
1835 bool HasInstance(Handle<Value> object);
1836
1837 private:
1838 FunctionTemplate();
1839 void AddInstancePropertyAccessor(Handle<String> name,
1840 AccessorGetter getter,
1841 AccessorSetter setter,
1842 Handle<Value> data,
1843 AccessControl settings,
1844 PropertyAttribute attributes);
1845 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
1846 NamedPropertySetter setter,
1847 NamedPropertyQuery query,
1848 NamedPropertyDeleter remover,
1849 NamedPropertyEnumerator enumerator,
1850 Handle<Value> data);
1851 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
1852 IndexedPropertySetter setter,
1853 IndexedPropertyQuery query,
1854 IndexedPropertyDeleter remover,
1855 IndexedPropertyEnumerator enumerator,
1856 Handle<Value> data);
1857 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
1858 Handle<Value> data);
1859
1860 friend class Context;
1861 friend class ObjectTemplate;
1862};
1863
1864
1865/**
1866 * An ObjectTemplate is used to create objects at runtime.
1867 *
1868 * Properties added to an ObjectTemplate are added to each object
1869 * created from the ObjectTemplate.
1870 */
1871class V8EXPORT ObjectTemplate : public Template {
1872 public:
1873 /** Creates an ObjectTemplate. */
1874 static Local<ObjectTemplate> New();
1875
1876 /** Creates a new instance of this template.*/
1877 Local<Object> NewInstance();
1878
1879 /**
1880 * Sets an accessor on the object template.
1881 *
1882 * Whenever the property with the given name is accessed on objects
1883 * created from this ObjectTemplate the getter and setter callbacks
1884 * are called instead of getting and setting the property directly
1885 * on the JavaScript object.
1886 *
1887 * \param name The name of the property for which an accessor is added.
1888 * \param getter The callback to invoke when getting the property.
1889 * \param setter The callback to invoke when setting the property.
1890 * \param data A piece of data that will be passed to the getter and setter
1891 * callbacks whenever they are invoked.
1892 * \param settings Access control settings for the accessor. This is a bit
1893 * field consisting of one of more of
1894 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
1895 * The default is to not allow cross-context access.
1896 * ALL_CAN_READ means that all cross-context reads are allowed.
1897 * ALL_CAN_WRITE means that all cross-context writes are allowed.
1898 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
1899 * cross-context access.
1900 * \param attribute The attributes of the property for which an accessor
1901 * is added.
1902 */
1903 void SetAccessor(Handle<String> name,
1904 AccessorGetter getter,
1905 AccessorSetter setter = 0,
1906 Handle<Value> data = Handle<Value>(),
1907 AccessControl settings = DEFAULT,
1908 PropertyAttribute attribute = None);
1909
1910 /**
1911 * Sets a named property handler on the object template.
1912 *
1913 * Whenever a named property is accessed on objects created from
1914 * this object template, the provided callback is invoked instead of
1915 * accessing the property directly on the JavaScript object.
1916 *
1917 * \param getter The callback to invoke when getting a property.
1918 * \param setter The callback to invoke when setting a property.
1919 * \param query The callback to invoke to check is an object has a property.
1920 * \param deleter The callback to invoke when deleting a property.
1921 * \param enumerator The callback to invoke to enumerate all the named
1922 * properties of an object.
1923 * \param data A piece of data that will be passed to the callbacks
1924 * whenever they are invoked.
1925 */
1926 void SetNamedPropertyHandler(NamedPropertyGetter getter,
1927 NamedPropertySetter setter = 0,
1928 NamedPropertyQuery query = 0,
1929 NamedPropertyDeleter deleter = 0,
1930 NamedPropertyEnumerator enumerator = 0,
1931 Handle<Value> data = Handle<Value>());
1932
1933 /**
1934 * Sets an indexed property handler on the object template.
1935 *
1936 * Whenever an indexed property is accessed on objects created from
1937 * this object template, the provided callback is invoked instead of
1938 * accessing the property directly on the JavaScript object.
1939 *
1940 * \param getter The callback to invoke when getting a property.
1941 * \param setter The callback to invoke when setting a property.
1942 * \param query The callback to invoke to check is an object has a property.
1943 * \param deleter The callback to invoke when deleting a property.
1944 * \param enumerator The callback to invoke to enumerate all the indexed
1945 * properties of an object.
1946 * \param data A piece of data that will be passed to the callbacks
1947 * whenever they are invoked.
1948 */
1949 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
1950 IndexedPropertySetter setter = 0,
1951 IndexedPropertyQuery query = 0,
1952 IndexedPropertyDeleter deleter = 0,
1953 IndexedPropertyEnumerator enumerator = 0,
1954 Handle<Value> data = Handle<Value>());
1955 /**
1956 * Sets the callback to be used when calling instances created from
1957 * this template as a function. If no callback is set, instances
1958 * behave like normal JavaScript objects that cannot be called as a
1959 * function.
1960 */
1961 void SetCallAsFunctionHandler(InvocationCallback callback,
1962 Handle<Value> data = Handle<Value>());
1963
1964 /**
1965 * Mark object instances of the template as undetectable.
1966 *
1967 * In many ways, undetectable objects behave as though they are not
1968 * there. They behave like 'undefined' in conditionals and when
1969 * printed. However, properties can be accessed and called as on
1970 * normal objects.
1971 */
1972 void MarkAsUndetectable();
1973
1974 /**
1975 * Sets access check callbacks on the object template.
1976 *
1977 * When accessing properties on instances of this object template,
1978 * the access check callback will be called to determine whether or
1979 * not to allow cross-context access to the properties.
1980 * The last parameter specifies whether access checks are turned
1981 * on by default on instances. If access checks are off by default,
1982 * they can be turned on on individual instances by calling
1983 * Object::TurnOnAccessCheck().
1984 */
1985 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
1986 IndexedSecurityCallback indexed_handler,
1987 Handle<Value> data = Handle<Value>(),
1988 bool turned_on_by_default = true);
1989
1990 /**
1991 * Gets the number of internal fields for objects generated from
1992 * this template.
1993 */
1994 int InternalFieldCount();
1995
1996 /**
1997 * Sets the number of internal fields for objects generated from
1998 * this template.
1999 */
2000 void SetInternalFieldCount(int value);
2001
2002 private:
2003 ObjectTemplate();
2004 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2005 friend class FunctionTemplate;
2006};
2007
2008
2009/**
2010 * A Signature specifies which receivers and arguments a function can
2011 * legally be called with.
2012 */
2013class V8EXPORT Signature : public Data {
2014 public:
2015 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2016 Handle<FunctionTemplate>(),
2017 int argc = 0,
2018 Handle<FunctionTemplate> argv[] = 0);
2019 private:
2020 Signature();
2021};
2022
2023
2024/**
2025 * A utility for determining the type of objects based on the template
2026 * they were constructed from.
2027 */
2028class V8EXPORT TypeSwitch : public Data {
2029 public:
2030 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2031 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2032 int match(Handle<Value> value);
2033 private:
2034 TypeSwitch();
2035};
2036
2037
2038// --- E x t e n s i o n s ---
2039
2040
2041/**
2042 * Ignore
2043 */
2044class V8EXPORT Extension { // NOLINT
2045 public:
2046 Extension(const char* name,
2047 const char* source = 0,
2048 int dep_count = 0,
2049 const char** deps = 0);
2050 virtual ~Extension() { }
2051 virtual v8::Handle<v8::FunctionTemplate>
2052 GetNativeFunction(v8::Handle<v8::String> name) {
2053 return v8::Handle<v8::FunctionTemplate>();
2054 }
2055
2056 const char* name() { return name_; }
2057 const char* source() { return source_; }
2058 int dependency_count() { return dep_count_; }
2059 const char** dependencies() { return deps_; }
2060 void set_auto_enable(bool value) { auto_enable_ = value; }
2061 bool auto_enable() { return auto_enable_; }
2062
2063 private:
2064 const char* name_;
2065 const char* source_;
2066 int dep_count_;
2067 const char** deps_;
2068 bool auto_enable_;
2069
2070 // Disallow copying and assigning.
2071 Extension(const Extension&);
2072 void operator=(const Extension&);
2073};
2074
2075
2076void V8EXPORT RegisterExtension(Extension* extension);
2077
2078
2079/**
2080 * Ignore
2081 */
2082class V8EXPORT DeclareExtension {
2083 public:
2084 inline DeclareExtension(Extension* extension) {
2085 RegisterExtension(extension);
2086 }
2087};
2088
2089
2090// --- S t a t i c s ---
2091
2092
2093Handle<Primitive> V8EXPORT Undefined();
2094Handle<Primitive> V8EXPORT Null();
2095Handle<Boolean> V8EXPORT True();
2096Handle<Boolean> V8EXPORT False();
2097
2098
2099/**
2100 * A set of constraints that specifies the limits of the runtime's memory use.
2101 * You must set the heap size before initializing the VM - the size cannot be
2102 * adjusted after the VM is initialized.
2103 *
2104 * If you are using threads then you should hold the V8::Locker lock while
2105 * setting the stack limit and you must set a non-default stack limit separately
2106 * for each thread.
2107 */
2108class V8EXPORT ResourceConstraints {
2109 public:
2110 ResourceConstraints();
2111 int max_young_space_size() const { return max_young_space_size_; }
2112 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2113 int max_old_space_size() const { return max_old_space_size_; }
2114 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
2115 uint32_t* stack_limit() const { return stack_limit_; }
2116 // Sets an address beyond which the VM's stack may not grow.
2117 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2118 private:
2119 int max_young_space_size_;
2120 int max_old_space_size_;
2121 uint32_t* stack_limit_;
2122};
2123
2124
2125bool SetResourceConstraints(ResourceConstraints* constraints);
2126
2127
2128// --- E x c e p t i o n s ---
2129
2130
2131typedef void (*FatalErrorCallback)(const char* location, const char* message);
2132
2133
2134typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2135
2136
2137/**
2138 * Schedules an exception to be thrown when returning to JavaScript. When an
2139 * exception has been scheduled it is illegal to invoke any JavaScript
2140 * operation; the caller must return immediately and only after the exception
2141 * has been handled does it become legal to invoke JavaScript operations.
2142 */
2143Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2144
2145/**
2146 * Create new error objects by calling the corresponding error object
2147 * constructor with the message.
2148 */
2149class V8EXPORT Exception {
2150 public:
2151 static Local<Value> RangeError(Handle<String> message);
2152 static Local<Value> ReferenceError(Handle<String> message);
2153 static Local<Value> SyntaxError(Handle<String> message);
2154 static Local<Value> TypeError(Handle<String> message);
2155 static Local<Value> Error(Handle<String> message);
2156};
2157
2158
2159// --- C o u n t e r s C a l l b a c k s ---
2160
2161typedef int* (*CounterLookupCallback)(const char* name);
2162
2163typedef void* (*CreateHistogramCallback)(const char* name,
2164 int min,
2165 int max,
2166 size_t buckets);
2167
2168typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2169
2170// --- 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 ---
2171typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2172 AccessType type,
2173 Local<Value> data);
2174
2175// --- 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
2176
2177/**
Steve Block6ded16b2010-05-10 14:33:55 +01002178 * Applications can register callback functions which will be called
2179 * before and after a garbage collection. Allocations are not
2180 * allowed in the callback functions, you therefore cannot manipulate
Steve Blocka7e24c12009-10-30 11:49:00 +00002181 * objects (set or delete properties for example) since it is possible
2182 * such operations will result in the allocation of objects.
2183 */
Steve Block6ded16b2010-05-10 14:33:55 +01002184enum GCType {
2185 kGCTypeScavenge = 1 << 0,
2186 kGCTypeMarkSweepCompact = 1 << 1,
2187 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2188};
2189
2190enum GCCallbackFlags {
2191 kNoGCCallbackFlags = 0,
2192 kGCCallbackFlagCompacted = 1 << 0
2193};
2194
2195typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2196typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2197
Steve Blocka7e24c12009-10-30 11:49:00 +00002198typedef void (*GCCallback)();
2199
2200
2201// --- C o n t e x t G e n e r a t o r ---
2202
2203/**
2204 * Applications must provide a callback function which is called to generate
2205 * a context if a context was not deserialized from the snapshot.
2206 */
2207typedef Persistent<Context> (*ContextGenerator)();
2208
2209
2210/**
2211 * Profiler modules.
2212 *
2213 * In V8, profiler consists of several modules: CPU profiler, and different
2214 * kinds of heap profiling. Each can be turned on / off independently.
2215 * When PROFILER_MODULE_HEAP_SNAPSHOT flag is passed to ResumeProfilerEx,
2216 * modules are enabled only temporarily for making a snapshot of the heap.
2217 */
2218enum ProfilerModules {
2219 PROFILER_MODULE_NONE = 0,
2220 PROFILER_MODULE_CPU = 1,
2221 PROFILER_MODULE_HEAP_STATS = 1 << 1,
2222 PROFILER_MODULE_JS_CONSTRUCTORS = 1 << 2,
2223 PROFILER_MODULE_HEAP_SNAPSHOT = 1 << 16
2224};
2225
2226
2227/**
Steve Block3ce2e202009-11-05 08:53:23 +00002228 * Collection of V8 heap information.
2229 *
2230 * Instances of this class can be passed to v8::V8::HeapStatistics to
2231 * get heap statistics from V8.
2232 */
2233class V8EXPORT HeapStatistics {
2234 public:
2235 HeapStatistics();
2236 size_t total_heap_size() { return total_heap_size_; }
2237 size_t used_heap_size() { return used_heap_size_; }
2238
2239 private:
2240 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
2241 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2242
2243 size_t total_heap_size_;
2244 size_t used_heap_size_;
2245
2246 friend class V8;
2247};
2248
2249
2250/**
Steve Blocka7e24c12009-10-30 11:49:00 +00002251 * Container class for static utility functions.
2252 */
2253class V8EXPORT V8 {
2254 public:
2255 /** Set the callback to invoke in case of fatal errors. */
2256 static void SetFatalErrorHandler(FatalErrorCallback that);
2257
2258 /**
2259 * Ignore out-of-memory exceptions.
2260 *
2261 * V8 running out of memory is treated as a fatal error by default.
2262 * This means that the fatal error handler is called and that V8 is
2263 * terminated.
2264 *
2265 * IgnoreOutOfMemoryException can be used to not treat a
2266 * out-of-memory situation as a fatal error. This way, the contexts
2267 * that did not cause the out of memory problem might be able to
2268 * continue execution.
2269 */
2270 static void IgnoreOutOfMemoryException();
2271
2272 /**
2273 * Check if V8 is dead and therefore unusable. This is the case after
2274 * fatal errors such as out-of-memory situations.
2275 */
2276 static bool IsDead();
2277
2278 /**
2279 * Adds a message listener.
2280 *
2281 * The same message listener can be added more than once and it that
2282 * case it will be called more than once for each message.
2283 */
2284 static bool AddMessageListener(MessageCallback that,
2285 Handle<Value> data = Handle<Value>());
2286
2287 /**
2288 * Remove all message listeners from the specified callback function.
2289 */
2290 static void RemoveMessageListeners(MessageCallback that);
2291
2292 /**
2293 * Sets V8 flags from a string.
2294 */
2295 static void SetFlagsFromString(const char* str, int length);
2296
2297 /**
2298 * Sets V8 flags from the command line.
2299 */
2300 static void SetFlagsFromCommandLine(int* argc,
2301 char** argv,
2302 bool remove_flags);
2303
2304 /** Get the version string. */
2305 static const char* GetVersion();
2306
2307 /**
2308 * Enables the host application to provide a mechanism for recording
2309 * statistics counters.
2310 */
2311 static void SetCounterFunction(CounterLookupCallback);
2312
2313 /**
2314 * Enables the host application to provide a mechanism for recording
2315 * histograms. The CreateHistogram function returns a
2316 * histogram which will later be passed to the AddHistogramSample
2317 * function.
2318 */
2319 static void SetCreateHistogramFunction(CreateHistogramCallback);
2320 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
2321
2322 /**
2323 * Enables the computation of a sliding window of states. The sliding
2324 * window information is recorded in statistics counters.
2325 */
2326 static void EnableSlidingStateWindow();
2327
2328 /** Callback function for reporting failed access checks.*/
2329 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
2330
2331 /**
2332 * Enables the host application to receive a notification before a
Steve Block6ded16b2010-05-10 14:33:55 +01002333 * garbage collection. Allocations are not allowed in the
2334 * callback function, you therefore cannot manipulate objects (set
2335 * or delete properties for example) since it is possible such
2336 * operations will result in the allocation of objects. It is possible
2337 * to specify the GCType filter for your callback. But it is not possible to
2338 * register the same callback function two times with different
2339 * GCType filters.
2340 */
2341 static void AddGCPrologueCallback(
2342 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
2343
2344 /**
2345 * This function removes callback which was installed by
2346 * AddGCPrologueCallback function.
2347 */
2348 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
2349
2350 /**
2351 * The function is deprecated. Please use AddGCPrologueCallback instead.
2352 * Enables the host application to receive a notification before a
2353 * garbage collection. Allocations are not allowed in the
Steve Blocka7e24c12009-10-30 11:49:00 +00002354 * callback function, you therefore cannot manipulate objects (set
2355 * or delete properties for example) since it is possible such
2356 * operations will result in the allocation of objects.
2357 */
2358 static void SetGlobalGCPrologueCallback(GCCallback);
2359
2360 /**
2361 * Enables the host application to receive a notification after a
Steve Block6ded16b2010-05-10 14:33:55 +01002362 * garbage collection. Allocations are not allowed in the
2363 * callback function, you therefore cannot manipulate objects (set
2364 * or delete properties for example) since it is possible such
2365 * operations will result in the allocation of objects. It is possible
2366 * to specify the GCType filter for your callback. But it is not possible to
2367 * register the same callback function two times with different
2368 * GCType filters.
2369 */
2370 static void AddGCEpilogueCallback(
2371 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
2372
2373 /**
2374 * This function removes callback which was installed by
2375 * AddGCEpilogueCallback function.
2376 */
2377 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
2378
2379 /**
2380 * The function is deprecated. Please use AddGCEpilogueCallback instead.
2381 * Enables the host application to receive a notification after a
Steve Blocka7e24c12009-10-30 11:49:00 +00002382 * major garbage collection. Allocations are not allowed in the
2383 * callback function, you therefore cannot manipulate objects (set
2384 * or delete properties for example) since it is possible such
2385 * operations will result in the allocation of objects.
2386 */
2387 static void SetGlobalGCEpilogueCallback(GCCallback);
2388
2389 /**
2390 * Allows the host application to group objects together. If one
2391 * object in the group is alive, all objects in the group are alive.
2392 * After each garbage collection, object groups are removed. It is
2393 * intended to be used in the before-garbage-collection callback
2394 * function, for instance to simulate DOM tree connections among JS
2395 * wrapper objects.
2396 */
2397 static void AddObjectGroup(Persistent<Value>* objects, size_t length);
2398
2399 /**
2400 * Initializes from snapshot if possible. Otherwise, attempts to
2401 * initialize from scratch. This function is called implicitly if
2402 * you use the API without calling it first.
2403 */
2404 static bool Initialize();
2405
2406 /**
2407 * Adjusts the amount of registered external memory. Used to give
2408 * V8 an indication of the amount of externally allocated memory
2409 * that is kept alive by JavaScript objects. V8 uses this to decide
2410 * when to perform global garbage collections. Registering
2411 * externally allocated memory will trigger global garbage
2412 * collections more often than otherwise in an attempt to garbage
2413 * collect the JavaScript objects keeping the externally allocated
2414 * memory alive.
2415 *
2416 * \param change_in_bytes the change in externally allocated memory
2417 * that is kept alive by JavaScript objects.
2418 * \returns the adjusted value.
2419 */
2420 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
2421
2422 /**
2423 * Suspends recording of tick samples in the profiler.
2424 * When the V8 profiling mode is enabled (usually via command line
2425 * switches) this function suspends recording of tick samples.
2426 * Profiling ticks are discarded until ResumeProfiler() is called.
2427 *
2428 * See also the --prof and --prof_auto command line switches to
2429 * enable V8 profiling.
2430 */
2431 static void PauseProfiler();
2432
2433 /**
2434 * Resumes recording of tick samples in the profiler.
2435 * See also PauseProfiler().
2436 */
2437 static void ResumeProfiler();
2438
2439 /**
2440 * Return whether profiler is currently paused.
2441 */
2442 static bool IsProfilerPaused();
2443
2444 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002445 * Resumes specified profiler modules. Can be called several times to
2446 * mark the opening of a profiler events block with the given tag.
2447 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002448 * "ResumeProfiler" is equivalent to "ResumeProfilerEx(PROFILER_MODULE_CPU)".
2449 * See ProfilerModules enum.
2450 *
2451 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002452 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002453 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002454 static void ResumeProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002455
2456 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002457 * Pauses specified profiler modules. Each call to "PauseProfilerEx" closes
2458 * a block of profiler events opened by a call to "ResumeProfilerEx" with the
2459 * same tag value. There is no need for blocks to be properly nested.
2460 * The profiler is paused when the last opened block is closed.
2461 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002462 * "PauseProfiler" is equivalent to "PauseProfilerEx(PROFILER_MODULE_CPU)".
2463 * See ProfilerModules enum.
2464 *
2465 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002466 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002467 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002468 static void PauseProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002469
2470 /**
2471 * Returns active (resumed) profiler modules.
2472 * See ProfilerModules enum.
2473 *
2474 * \returns active profiler modules.
2475 */
2476 static int GetActiveProfilerModules();
2477
2478 /**
2479 * If logging is performed into a memory buffer (via --logfile=*), allows to
2480 * retrieve previously written messages. This can be used for retrieving
2481 * profiler log data in the application. This function is thread-safe.
2482 *
2483 * Caller provides a destination buffer that must exist during GetLogLines
2484 * call. Only whole log lines are copied into the buffer.
2485 *
2486 * \param from_pos specified a point in a buffer to read from, 0 is the
2487 * beginning of a buffer. It is assumed that caller updates its current
2488 * position using returned size value from the previous call.
2489 * \param dest_buf destination buffer for log data.
2490 * \param max_size size of the destination buffer.
2491 * \returns actual size of log data copied into buffer.
2492 */
2493 static int GetLogLines(int from_pos, char* dest_buf, int max_size);
2494
2495 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002496 * The minimum allowed size for a log lines buffer. If the size of
2497 * the buffer given will not be enough to hold a line of the maximum
2498 * length, an attempt to find a log line end in GetLogLines will
2499 * fail, and an empty result will be returned.
2500 */
2501 static const int kMinimumSizeForLogLinesBuffer = 2048;
2502
2503 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002504 * Retrieve the V8 thread id of the calling thread.
2505 *
2506 * The thread id for a thread should only be retrieved after the V8
2507 * lock has been acquired with a Locker object with that thread.
2508 */
2509 static int GetCurrentThreadId();
2510
2511 /**
2512 * Forcefully terminate execution of a JavaScript thread. This can
2513 * be used to terminate long-running scripts.
2514 *
2515 * TerminateExecution should only be called when then V8 lock has
2516 * been acquired with a Locker object. Therefore, in order to be
2517 * able to terminate long-running threads, preemption must be
2518 * enabled to allow the user of TerminateExecution to acquire the
2519 * lock.
2520 *
2521 * The termination is achieved by throwing an exception that is
2522 * uncatchable by JavaScript exception handlers. Termination
2523 * exceptions act as if they were caught by a C++ TryCatch exception
2524 * handlers. If forceful termination is used, any C++ TryCatch
2525 * exception handler that catches an exception should check if that
2526 * exception is a termination exception and immediately return if
2527 * that is the case. Returning immediately in that case will
2528 * continue the propagation of the termination exception if needed.
2529 *
2530 * The thread id passed to TerminateExecution must have been
2531 * obtained by calling GetCurrentThreadId on the thread in question.
2532 *
2533 * \param thread_id The thread id of the thread to terminate.
2534 */
2535 static void TerminateExecution(int thread_id);
2536
2537 /**
2538 * Forcefully terminate the current thread of JavaScript execution.
2539 *
2540 * This method can be used by any thread even if that thread has not
2541 * acquired the V8 lock with a Locker object.
2542 */
2543 static void TerminateExecution();
2544
2545 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002546 * Is V8 terminating JavaScript execution.
2547 *
2548 * Returns true if JavaScript execution is currently terminating
2549 * because of a call to TerminateExecution. In that case there are
2550 * still JavaScript frames on the stack and the termination
2551 * exception is still active.
2552 */
2553 static bool IsExecutionTerminating();
2554
2555 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002556 * Releases any resources used by v8 and stops any utility threads
2557 * that may be running. Note that disposing v8 is permanent, it
2558 * cannot be reinitialized.
2559 *
2560 * It should generally not be necessary to dispose v8 before exiting
2561 * a process, this should happen automatically. It is only necessary
2562 * to use if the process needs the resources taken up by v8.
2563 */
2564 static bool Dispose();
2565
Steve Block3ce2e202009-11-05 08:53:23 +00002566 /**
2567 * Get statistics about the heap memory usage.
2568 */
2569 static void GetHeapStatistics(HeapStatistics* heap_statistics);
Steve Blocka7e24c12009-10-30 11:49:00 +00002570
2571 /**
2572 * Optional notification that the embedder is idle.
2573 * V8 uses the notification to reduce memory footprint.
2574 * This call can be used repeatedly if the embedder remains idle.
Steve Blocka7e24c12009-10-30 11:49:00 +00002575 * Returns true if the embedder should stop calling IdleNotification
2576 * until real work has been done. This indicates that V8 has done
2577 * as much cleanup as it will be able to do.
2578 */
Steve Block3ce2e202009-11-05 08:53:23 +00002579 static bool IdleNotification();
Steve Blocka7e24c12009-10-30 11:49:00 +00002580
2581 /**
2582 * Optional notification that the system is running low on memory.
2583 * V8 uses these notifications to attempt to free memory.
2584 */
2585 static void LowMemoryNotification();
2586
Steve Block6ded16b2010-05-10 14:33:55 +01002587 /**
2588 * Optional notification that a context has been disposed. V8 uses
2589 * these notifications to guide the GC heuristic. Returns the number
2590 * of context disposals - including this one - since the last time
2591 * V8 had a chance to clean up.
2592 */
2593 static int ContextDisposedNotification();
2594
Steve Blocka7e24c12009-10-30 11:49:00 +00002595 private:
2596 V8();
2597
2598 static internal::Object** GlobalizeReference(internal::Object** handle);
2599 static void DisposeGlobal(internal::Object** global_handle);
2600 static void MakeWeak(internal::Object** global_handle,
2601 void* data,
2602 WeakReferenceCallback);
2603 static void ClearWeak(internal::Object** global_handle);
2604 static bool IsGlobalNearDeath(internal::Object** global_handle);
2605 static bool IsGlobalWeak(internal::Object** global_handle);
2606
2607 template <class T> friend class Handle;
2608 template <class T> friend class Local;
2609 template <class T> friend class Persistent;
2610 friend class Context;
2611};
2612
2613
2614/**
2615 * An external exception handler.
2616 */
2617class V8EXPORT TryCatch {
2618 public:
2619
2620 /**
2621 * Creates a new try/catch block and registers it with v8.
2622 */
2623 TryCatch();
2624
2625 /**
2626 * Unregisters and deletes this try/catch block.
2627 */
2628 ~TryCatch();
2629
2630 /**
2631 * Returns true if an exception has been caught by this try/catch block.
2632 */
2633 bool HasCaught() const;
2634
2635 /**
2636 * For certain types of exceptions, it makes no sense to continue
2637 * execution.
2638 *
2639 * Currently, the only type of exception that can be caught by a
2640 * TryCatch handler and for which it does not make sense to continue
2641 * is termination exception. Such exceptions are thrown when the
2642 * TerminateExecution methods are called to terminate a long-running
2643 * script.
2644 *
2645 * If CanContinue returns false, the correct action is to perform
2646 * any C++ cleanup needed and then return.
2647 */
2648 bool CanContinue() const;
2649
2650 /**
Steve Blockd0582a62009-12-15 09:54:21 +00002651 * Throws the exception caught by this TryCatch in a way that avoids
2652 * it being caught again by this same TryCatch. As with ThrowException
2653 * it is illegal to execute any JavaScript operations after calling
2654 * ReThrow; the caller must return immediately to where the exception
2655 * is caught.
2656 */
2657 Handle<Value> ReThrow();
2658
2659 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002660 * Returns the exception caught by this try/catch block. If no exception has
2661 * been caught an empty handle is returned.
2662 *
2663 * The returned handle is valid until this TryCatch block has been destroyed.
2664 */
2665 Local<Value> Exception() const;
2666
2667 /**
2668 * Returns the .stack property of the thrown object. If no .stack
2669 * property is present an empty handle is returned.
2670 */
2671 Local<Value> StackTrace() const;
2672
2673 /**
2674 * Returns the message associated with this exception. If there is
2675 * no message associated an empty handle is returned.
2676 *
2677 * The returned handle is valid until this TryCatch block has been
2678 * destroyed.
2679 */
2680 Local<v8::Message> Message() const;
2681
2682 /**
2683 * Clears any exceptions that may have been caught by this try/catch block.
2684 * After this method has been called, HasCaught() will return false.
2685 *
2686 * It is not necessary to clear a try/catch block before using it again; if
2687 * another exception is thrown the previously caught exception will just be
2688 * overwritten. However, it is often a good idea since it makes it easier
2689 * to determine which operation threw a given exception.
2690 */
2691 void Reset();
2692
2693 /**
2694 * Set verbosity of the external exception handler.
2695 *
2696 * By default, exceptions that are caught by an external exception
2697 * handler are not reported. Call SetVerbose with true on an
2698 * external exception handler to have exceptions caught by the
2699 * handler reported as if they were not caught.
2700 */
2701 void SetVerbose(bool value);
2702
2703 /**
2704 * Set whether or not this TryCatch should capture a Message object
2705 * which holds source information about where the exception
2706 * occurred. True by default.
2707 */
2708 void SetCaptureMessage(bool value);
2709
Steve Blockd0582a62009-12-15 09:54:21 +00002710 private:
2711 void* next_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002712 void* exception_;
2713 void* message_;
Steve Blockd0582a62009-12-15 09:54:21 +00002714 bool is_verbose_ : 1;
2715 bool can_continue_ : 1;
2716 bool capture_message_ : 1;
2717 bool rethrow_ : 1;
2718
2719 friend class v8::internal::Top;
Steve Blocka7e24c12009-10-30 11:49:00 +00002720};
2721
2722
2723// --- C o n t e x t ---
2724
2725
2726/**
2727 * Ignore
2728 */
2729class V8EXPORT ExtensionConfiguration {
2730 public:
2731 ExtensionConfiguration(int name_count, const char* names[])
2732 : name_count_(name_count), names_(names) { }
2733 private:
2734 friend class ImplementationUtilities;
2735 int name_count_;
2736 const char** names_;
2737};
2738
2739
2740/**
2741 * A sandboxed execution context with its own set of built-in objects
2742 * and functions.
2743 */
2744class V8EXPORT Context {
2745 public:
2746 /** Returns the global object of the context. */
2747 Local<Object> Global();
2748
2749 /**
2750 * Detaches the global object from its context before
2751 * the global object can be reused to create a new context.
2752 */
2753 void DetachGlobal();
2754
Andrei Popescu74b3c142010-03-29 12:03:09 +01002755 /**
2756 * Reattaches a global object to a context. This can be used to
2757 * restore the connection between a global object and a context
2758 * after DetachGlobal has been called.
2759 *
2760 * \param global_object The global object to reattach to the
2761 * context. For this to work, the global object must be the global
2762 * object that was associated with this context before a call to
2763 * DetachGlobal.
2764 */
2765 void ReattachGlobal(Handle<Object> global_object);
2766
Steve Blocka7e24c12009-10-30 11:49:00 +00002767 /** Creates a new context. */
2768 static Persistent<Context> New(
Andrei Popescu31002712010-02-23 13:46:05 +00002769 ExtensionConfiguration* extensions = NULL,
Steve Blocka7e24c12009-10-30 11:49:00 +00002770 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
2771 Handle<Value> global_object = Handle<Value>());
2772
2773 /** Returns the last entered context. */
2774 static Local<Context> GetEntered();
2775
2776 /** Returns the context that is on the top of the stack. */
2777 static Local<Context> GetCurrent();
2778
2779 /**
2780 * Returns the context of the calling JavaScript code. That is the
2781 * context of the top-most JavaScript frame. If there are no
2782 * JavaScript frames an empty handle is returned.
2783 */
2784 static Local<Context> GetCalling();
2785
2786 /**
2787 * Sets the security token for the context. To access an object in
2788 * another context, the security tokens must match.
2789 */
2790 void SetSecurityToken(Handle<Value> token);
2791
2792 /** Restores the security token to the default value. */
2793 void UseDefaultSecurityToken();
2794
2795 /** Returns the security token of this context.*/
2796 Handle<Value> GetSecurityToken();
2797
2798 /**
2799 * Enter this context. After entering a context, all code compiled
2800 * and run is compiled and run in this context. If another context
2801 * is already entered, this old context is saved so it can be
2802 * restored when the new context is exited.
2803 */
2804 void Enter();
2805
2806 /**
2807 * Exit this context. Exiting the current context restores the
2808 * context that was in place when entering the current context.
2809 */
2810 void Exit();
2811
2812 /** Returns true if the context has experienced an out of memory situation. */
2813 bool HasOutOfMemoryException();
2814
2815 /** Returns true if V8 has a current context. */
2816 static bool InContext();
2817
2818 /**
2819 * Associate an additional data object with the context. This is mainly used
2820 * with the debugger to provide additional information on the context through
2821 * the debugger API.
2822 */
Steve Blockd0582a62009-12-15 09:54:21 +00002823 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00002824 Local<Value> GetData();
2825
2826 /**
2827 * Stack-allocated class which sets the execution context for all
2828 * operations executed within a local scope.
2829 */
2830 class V8EXPORT Scope {
2831 public:
2832 inline Scope(Handle<Context> context) : context_(context) {
2833 context_->Enter();
2834 }
2835 inline ~Scope() { context_->Exit(); }
2836 private:
2837 Handle<Context> context_;
2838 };
2839
2840 private:
2841 friend class Value;
2842 friend class Script;
2843 friend class Object;
2844 friend class Function;
2845};
2846
2847
2848/**
2849 * Multiple threads in V8 are allowed, but only one thread at a time
2850 * is allowed to use V8. The definition of 'using V8' includes
2851 * accessing handles or holding onto object pointers obtained from V8
2852 * handles. It is up to the user of V8 to ensure (perhaps with
2853 * locking) that this constraint is not violated.
2854 *
2855 * If you wish to start using V8 in a thread you can do this by constructing
2856 * a v8::Locker object. After the code using V8 has completed for the
2857 * current thread you can call the destructor. This can be combined
2858 * with C++ scope-based construction as follows:
2859 *
2860 * \code
2861 * ...
2862 * {
2863 * v8::Locker locker;
2864 * ...
2865 * // Code using V8 goes here.
2866 * ...
2867 * } // Destructor called here
2868 * \endcode
2869 *
2870 * If you wish to stop using V8 in a thread A you can do this by either
2871 * by destroying the v8::Locker object as above or by constructing a
2872 * v8::Unlocker object:
2873 *
2874 * \code
2875 * {
2876 * v8::Unlocker unlocker;
2877 * ...
2878 * // Code not using V8 goes here while V8 can run in another thread.
2879 * ...
2880 * } // Destructor called here.
2881 * \endcode
2882 *
2883 * The Unlocker object is intended for use in a long-running callback
2884 * from V8, where you want to release the V8 lock for other threads to
2885 * use.
2886 *
2887 * The v8::Locker is a recursive lock. That is, you can lock more than
2888 * once in a given thread. This can be useful if you have code that can
2889 * be called either from code that holds the lock or from code that does
2890 * not. The Unlocker is not recursive so you can not have several
2891 * Unlockers on the stack at once, and you can not use an Unlocker in a
2892 * thread that is not inside a Locker's scope.
2893 *
2894 * An unlocker will unlock several lockers if it has to and reinstate
2895 * the correct depth of locking on its destruction. eg.:
2896 *
2897 * \code
2898 * // V8 not locked.
2899 * {
2900 * v8::Locker locker;
2901 * // V8 locked.
2902 * {
2903 * v8::Locker another_locker;
2904 * // V8 still locked (2 levels).
2905 * {
2906 * v8::Unlocker unlocker;
2907 * // V8 not locked.
2908 * }
2909 * // V8 locked again (2 levels).
2910 * }
2911 * // V8 still locked (1 level).
2912 * }
2913 * // V8 Now no longer locked.
2914 * \endcode
2915 */
2916class V8EXPORT Unlocker {
2917 public:
2918 Unlocker();
2919 ~Unlocker();
2920};
2921
2922
2923class V8EXPORT Locker {
2924 public:
2925 Locker();
2926 ~Locker();
2927
2928 /**
2929 * Start preemption.
2930 *
2931 * When preemption is started, a timer is fired every n milli seconds
2932 * that will switch between multiple threads that are in contention
2933 * for the V8 lock.
2934 */
2935 static void StartPreemption(int every_n_ms);
2936
2937 /**
2938 * Stop preemption.
2939 */
2940 static void StopPreemption();
2941
2942 /**
2943 * Returns whether or not the locker is locked by the current thread.
2944 */
2945 static bool IsLocked();
2946
2947 /**
2948 * Returns whether v8::Locker is being used by this V8 instance.
2949 */
2950 static bool IsActive() { return active_; }
2951
2952 private:
2953 bool has_lock_;
2954 bool top_level_;
2955
2956 static bool active_;
2957
2958 // Disallow copying and assigning.
2959 Locker(const Locker&);
2960 void operator=(const Locker&);
2961};
2962
2963
2964
2965// --- I m p l e m e n t a t i o n ---
2966
2967
2968namespace internal {
2969
2970
2971// Tag information for HeapObject.
2972const int kHeapObjectTag = 1;
2973const int kHeapObjectTagSize = 2;
2974const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
2975
Steve Blocka7e24c12009-10-30 11:49:00 +00002976// Tag information for Smi.
2977const int kSmiTag = 0;
2978const int kSmiTagSize = 1;
2979const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
2980
Steve Block3ce2e202009-11-05 08:53:23 +00002981template <size_t ptr_size> struct SmiConstants;
2982
2983// Smi constants for 32-bit systems.
2984template <> struct SmiConstants<4> {
2985 static const int kSmiShiftSize = 0;
2986 static const int kSmiValueSize = 31;
2987 static inline int SmiToInt(internal::Object* value) {
2988 int shift_bits = kSmiTagSize + kSmiShiftSize;
2989 // Throw away top 32 bits and shift down (requires >> to be sign extending).
2990 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
2991 }
2992};
2993
2994// Smi constants for 64-bit systems.
2995template <> struct SmiConstants<8> {
2996 static const int kSmiShiftSize = 31;
2997 static const int kSmiValueSize = 32;
2998 static inline int SmiToInt(internal::Object* value) {
2999 int shift_bits = kSmiTagSize + kSmiShiftSize;
3000 // Shift down and throw away top 32 bits.
3001 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3002 }
3003};
3004
3005const int kSmiShiftSize = SmiConstants<sizeof(void*)>::kSmiShiftSize;
3006const int kSmiValueSize = SmiConstants<sizeof(void*)>::kSmiValueSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003007
Steve Blockd0582a62009-12-15 09:54:21 +00003008template <size_t ptr_size> struct InternalConstants;
3009
3010// Internal constants for 32-bit systems.
3011template <> struct InternalConstants<4> {
3012 static const int kStringResourceOffset = 3 * sizeof(void*);
3013};
3014
3015// Internal constants for 64-bit systems.
3016template <> struct InternalConstants<8> {
Steve Block6ded16b2010-05-10 14:33:55 +01003017 static const int kStringResourceOffset = 3 * sizeof(void*);
Steve Blockd0582a62009-12-15 09:54:21 +00003018};
3019
Steve Blocka7e24c12009-10-30 11:49:00 +00003020/**
3021 * This class exports constants and functionality from within v8 that
3022 * is necessary to implement inline functions in the v8 api. Don't
3023 * depend on functions and constants defined here.
3024 */
3025class Internals {
3026 public:
3027
3028 // These values match non-compiler-dependent values defined within
3029 // the implementation of v8.
3030 static const int kHeapObjectMapOffset = 0;
3031 static const int kMapInstanceTypeOffset = sizeof(void*) + sizeof(int);
Steve Blockd0582a62009-12-15 09:54:21 +00003032 static const int kStringResourceOffset =
3033 InternalConstants<sizeof(void*)>::kStringResourceOffset;
3034
Steve Blocka7e24c12009-10-30 11:49:00 +00003035 static const int kProxyProxyOffset = sizeof(void*);
3036 static const int kJSObjectHeaderSize = 3 * sizeof(void*);
3037 static const int kFullStringRepresentationMask = 0x07;
3038 static const int kExternalTwoByteRepresentationTag = 0x03;
Steve Blocka7e24c12009-10-30 11:49:00 +00003039
3040 // These constants are compiler dependent so their values must be
3041 // defined within the implementation.
3042 V8EXPORT static int kJSObjectType;
3043 V8EXPORT static int kFirstNonstringType;
3044 V8EXPORT static int kProxyType;
3045
3046 static inline bool HasHeapObjectTag(internal::Object* value) {
3047 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3048 kHeapObjectTag);
3049 }
3050
3051 static inline bool HasSmiTag(internal::Object* value) {
3052 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3053 }
3054
3055 static inline int SmiValue(internal::Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00003056 return SmiConstants<sizeof(void*)>::SmiToInt(value);
3057 }
3058
3059 static inline int GetInstanceType(internal::Object* obj) {
3060 typedef internal::Object O;
3061 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3062 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3063 }
3064
3065 static inline void* GetExternalPointer(internal::Object* obj) {
3066 if (HasSmiTag(obj)) {
3067 return obj;
3068 } else if (GetInstanceType(obj) == kProxyType) {
3069 return ReadField<void*>(obj, kProxyProxyOffset);
3070 } else {
3071 return NULL;
3072 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003073 }
3074
3075 static inline bool IsExternalTwoByteString(int instance_type) {
3076 int representation = (instance_type & kFullStringRepresentationMask);
3077 return representation == kExternalTwoByteRepresentationTag;
3078 }
3079
3080 template <typename T>
3081 static inline T ReadField(Object* ptr, int offset) {
3082 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3083 return *reinterpret_cast<T*>(addr);
3084 }
3085
3086};
3087
3088}
3089
3090
3091template <class T>
3092Handle<T>::Handle() : val_(0) { }
3093
3094
3095template <class T>
3096Local<T>::Local() : Handle<T>() { }
3097
3098
3099template <class T>
3100Local<T> Local<T>::New(Handle<T> that) {
3101 if (that.IsEmpty()) return Local<T>();
3102 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3103 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3104}
3105
3106
3107template <class T>
3108Persistent<T> Persistent<T>::New(Handle<T> that) {
3109 if (that.IsEmpty()) return Persistent<T>();
3110 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3111 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3112}
3113
3114
3115template <class T>
3116bool Persistent<T>::IsNearDeath() const {
3117 if (this->IsEmpty()) return false;
3118 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3119}
3120
3121
3122template <class T>
3123bool Persistent<T>::IsWeak() const {
3124 if (this->IsEmpty()) return false;
3125 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3126}
3127
3128
3129template <class T>
3130void Persistent<T>::Dispose() {
3131 if (this->IsEmpty()) return;
3132 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3133}
3134
3135
3136template <class T>
3137Persistent<T>::Persistent() : Handle<T>() { }
3138
3139template <class T>
3140void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3141 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3142 parameters,
3143 callback);
3144}
3145
3146template <class T>
3147void Persistent<T>::ClearWeak() {
3148 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
3149}
3150
3151Local<Value> Arguments::operator[](int i) const {
3152 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
3153 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
3154}
3155
3156
3157Local<Function> Arguments::Callee() const {
3158 return callee_;
3159}
3160
3161
3162Local<Object> Arguments::This() const {
3163 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
3164}
3165
3166
3167Local<Object> Arguments::Holder() const {
3168 return holder_;
3169}
3170
3171
3172Local<Value> Arguments::Data() const {
3173 return data_;
3174}
3175
3176
3177bool Arguments::IsConstructCall() const {
3178 return is_construct_call_;
3179}
3180
3181
3182int Arguments::Length() const {
3183 return length_;
3184}
3185
3186
3187template <class T>
3188Local<T> HandleScope::Close(Handle<T> value) {
3189 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
3190 internal::Object** after = RawClose(before);
3191 return Local<T>(reinterpret_cast<T*>(after));
3192}
3193
3194Handle<Value> ScriptOrigin::ResourceName() const {
3195 return resource_name_;
3196}
3197
3198
3199Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
3200 return resource_line_offset_;
3201}
3202
3203
3204Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
3205 return resource_column_offset_;
3206}
3207
3208
3209Handle<Boolean> Boolean::New(bool value) {
3210 return value ? True() : False();
3211}
3212
3213
3214void Template::Set(const char* name, v8::Handle<Data> value) {
3215 Set(v8::String::New(name), value);
3216}
3217
3218
3219Local<Value> Object::GetInternalField(int index) {
3220#ifndef V8_ENABLE_CHECKS
3221 Local<Value> quick_result = UncheckedGetInternalField(index);
3222 if (!quick_result.IsEmpty()) return quick_result;
3223#endif
3224 return CheckedGetInternalField(index);
3225}
3226
3227
3228Local<Value> Object::UncheckedGetInternalField(int index) {
3229 typedef internal::Object O;
3230 typedef internal::Internals I;
3231 O* obj = *reinterpret_cast<O**>(this);
Steve Block3ce2e202009-11-05 08:53:23 +00003232 if (I::GetInstanceType(obj) == I::kJSObjectType) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003233 // If the object is a plain JSObject, which is the common case,
3234 // we know where to find the internal fields and can return the
3235 // value directly.
3236 int offset = I::kJSObjectHeaderSize + (sizeof(void*) * index);
3237 O* value = I::ReadField<O*>(obj, offset);
3238 O** result = HandleScope::CreateHandle(value);
3239 return Local<Value>(reinterpret_cast<Value*>(result));
3240 } else {
3241 return Local<Value>();
3242 }
3243}
3244
3245
3246void* External::Unwrap(Handle<v8::Value> obj) {
3247#ifdef V8_ENABLE_CHECKS
3248 return FullUnwrap(obj);
3249#else
3250 return QuickUnwrap(obj);
3251#endif
3252}
3253
3254
3255void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
3256 typedef internal::Object O;
Steve Blocka7e24c12009-10-30 11:49:00 +00003257 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
Steve Block3ce2e202009-11-05 08:53:23 +00003258 return internal::Internals::GetExternalPointer(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00003259}
3260
3261
3262void* Object::GetPointerFromInternalField(int index) {
Steve Block3ce2e202009-11-05 08:53:23 +00003263 typedef internal::Object O;
3264 typedef internal::Internals I;
3265
3266 O* obj = *reinterpret_cast<O**>(this);
3267
3268 if (I::GetInstanceType(obj) == I::kJSObjectType) {
3269 // If the object is a plain JSObject, which is the common case,
3270 // we know where to find the internal fields and can return the
3271 // value directly.
3272 int offset = I::kJSObjectHeaderSize + (sizeof(void*) * index);
3273 O* value = I::ReadField<O*>(obj, offset);
3274 return I::GetExternalPointer(value);
3275 }
3276
3277 return SlowGetPointerFromInternalField(index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003278}
3279
3280
3281String* String::Cast(v8::Value* value) {
3282#ifdef V8_ENABLE_CHECKS
3283 CheckCast(value);
3284#endif
3285 return static_cast<String*>(value);
3286}
3287
3288
3289String::ExternalStringResource* String::GetExternalStringResource() const {
3290 typedef internal::Object O;
3291 typedef internal::Internals I;
3292 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
Steve Blocka7e24c12009-10-30 11:49:00 +00003293 String::ExternalStringResource* result;
Steve Block3ce2e202009-11-05 08:53:23 +00003294 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003295 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
3296 result = reinterpret_cast<String::ExternalStringResource*>(value);
3297 } else {
3298 result = NULL;
3299 }
3300#ifdef V8_ENABLE_CHECKS
3301 VerifyExternalStringResource(result);
3302#endif
3303 return result;
3304}
3305
3306
3307bool Value::IsString() const {
3308#ifdef V8_ENABLE_CHECKS
3309 return FullIsString();
3310#else
3311 return QuickIsString();
3312#endif
3313}
3314
3315bool Value::QuickIsString() const {
3316 typedef internal::Object O;
3317 typedef internal::Internals I;
3318 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
3319 if (!I::HasHeapObjectTag(obj)) return false;
Steve Block3ce2e202009-11-05 08:53:23 +00003320 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
Steve Blocka7e24c12009-10-30 11:49:00 +00003321}
3322
3323
3324Number* Number::Cast(v8::Value* value) {
3325#ifdef V8_ENABLE_CHECKS
3326 CheckCast(value);
3327#endif
3328 return static_cast<Number*>(value);
3329}
3330
3331
3332Integer* Integer::Cast(v8::Value* value) {
3333#ifdef V8_ENABLE_CHECKS
3334 CheckCast(value);
3335#endif
3336 return static_cast<Integer*>(value);
3337}
3338
3339
3340Date* Date::Cast(v8::Value* value) {
3341#ifdef V8_ENABLE_CHECKS
3342 CheckCast(value);
3343#endif
3344 return static_cast<Date*>(value);
3345}
3346
3347
3348Object* Object::Cast(v8::Value* value) {
3349#ifdef V8_ENABLE_CHECKS
3350 CheckCast(value);
3351#endif
3352 return static_cast<Object*>(value);
3353}
3354
3355
3356Array* Array::Cast(v8::Value* value) {
3357#ifdef V8_ENABLE_CHECKS
3358 CheckCast(value);
3359#endif
3360 return static_cast<Array*>(value);
3361}
3362
3363
3364Function* Function::Cast(v8::Value* value) {
3365#ifdef V8_ENABLE_CHECKS
3366 CheckCast(value);
3367#endif
3368 return static_cast<Function*>(value);
3369}
3370
3371
3372External* External::Cast(v8::Value* value) {
3373#ifdef V8_ENABLE_CHECKS
3374 CheckCast(value);
3375#endif
3376 return static_cast<External*>(value);
3377}
3378
3379
3380Local<Value> AccessorInfo::Data() const {
Steve Block6ded16b2010-05-10 14:33:55 +01003381 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003382}
3383
3384
3385Local<Object> AccessorInfo::This() const {
3386 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
3387}
3388
3389
3390Local<Object> AccessorInfo::Holder() const {
3391 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
3392}
3393
3394
3395/**
3396 * \example shell.cc
3397 * A simple shell that takes a list of expressions on the
3398 * command-line and executes them.
3399 */
3400
3401
3402/**
3403 * \example process.cc
3404 */
3405
3406
3407} // namespace v8
3408
3409
3410#undef V8EXPORT
3411#undef V8EXPORT_INLINE
3412#undef TYPE_CHECK
3413
3414
3415#endif // V8_H_