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