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