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