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