Bug 752461 - Hide click-to-play overlays when choosing "never activate plugins.....
[gecko.git] / js / src / jsapi.h
blob5601b2ff6f657f2589504c8a44ff5c29affc3f66
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sw=4 et tw=78:
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
15 * License.
17 * The Original Code is Mozilla Communicator client code, released
18 * March 31, 1998.
20 * The Initial Developer of the Original Code is
21 * Netscape Communications Corporation.
22 * Portions created by the Initial Developer are Copyright (C) 1998
23 * the Initial Developer. All Rights Reserved.
25 * Contributor(s):
27 * Alternatively, the contents of this file may be used under the terms of
28 * either of the GNU General Public License Version 2 or later (the "GPL"),
29 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30 * in which case the provisions of the GPL or the LGPL are applicable instead
31 * of those above. If you wish to allow use of your version of this file only
32 * under the terms of either the GPL or the LGPL, and not to allow others to
33 * use your version of this file under the terms of the MPL, indicate your
34 * decision by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL or the LGPL. If you do not delete
36 * the provisions above, a recipient may use your version of this file under
37 * the terms of any one of the MPL, the GPL or the LGPL.
39 * ***** END LICENSE BLOCK ***** */
41 #ifndef jsapi_h___
42 #define jsapi_h___
44 * JavaScript API.
47 #include "mozilla/Attributes.h"
48 #include "mozilla/FloatingPoint.h"
49 #include "mozilla/StandardInteger.h"
51 #include <stddef.h>
52 #include <stdio.h>
53 #include "js-config.h"
54 #include "jspubtd.h"
55 #include "jsutil.h"
56 #include "jsval.h"
58 #include "js/Utility.h"
59 #include "gc/Root.h"
61 #ifdef __cplusplus
62 #include <limits> /* for std::numeric_limits */
64 #include "jsalloc.h"
65 #include "js/Vector.h"
66 #endif
68 /************************************************************************/
70 /* JS::Value can store a full int32_t. */
71 #define JSVAL_INT_BITS 32
72 #define JSVAL_INT_MIN ((int32_t)0x80000000)
73 #define JSVAL_INT_MAX ((int32_t)0x7fffffff)
75 /************************************************************************/
77 #define JS_Assert MOZ_Assert
79 #ifdef __cplusplus
80 namespace JS {
83 * Protecting non-jsval, non-JSObject *, non-JSString * values from collection
85 * Most of the time, the garbage collector's conservative stack scanner works
86 * behind the scenes, finding all live values and protecting them from being
87 * collected. However, when JSAPI client code obtains a pointer to data the
88 * scanner does not know about, owned by an object the scanner does know about,
89 * Care Must Be Taken.
91 * The scanner recognizes only a select set of types: pointers to JSObjects and
92 * similar things (JSFunctions, and so on), pointers to JSStrings, and jsvals.
93 * So while the scanner finds all live |JSString| pointers, it does not notice
94 * |jschar| pointers.
96 * So suppose we have:
98 * void f(JSString *str) {
99 * const jschar *ch = JS_GetStringCharsZ(str);
100 * ... do stuff with ch, but no uses of str ...;
103 * After the call to |JS_GetStringCharsZ|, there are no further uses of
104 * |str|, which means that the compiler is within its rights to not store
105 * it anywhere. But because the stack scanner will not notice |ch|, there
106 * is no longer any live value in this frame that would keep the string
107 * alive. If |str| is the last reference to that |JSString|, and the
108 * collector runs while we are using |ch|, the string's array of |jschar|s
109 * may be freed out from under us.
111 * Note that there is only an issue when 1) we extract a thing X the scanner
112 * doesn't recognize from 2) a thing Y the scanner does recognize, and 3) if Y
113 * gets garbage-collected, then X gets freed. If we have code like this:
115 * void g(JSObject *obj) {
116 * jsval x;
117 * JS_GetProperty(obj, "x", &x);
118 * ... do stuff with x ...
121 * there's no problem, because the value we've extracted, x, is a jsval, a
122 * type that the conservative scanner recognizes.
124 * Conservative GC frees us from the obligation to explicitly root the types it
125 * knows about, but when we work with derived values like |ch|, we must root
126 * their owners, as the derived value alone won't keep them alive.
128 * A JS::Anchor is a kind of GC root that allows us to keep the owners of
129 * derived values like |ch| alive throughout the Anchor's lifetime. We could
130 * fix the above code as follows:
132 * void f(JSString *str) {
133 * JS::Anchor<JSString *> a_str(str);
134 * const jschar *ch = JS_GetStringCharsZ(str);
135 * ... do stuff with ch, but no uses of str ...;
138 * This simply ensures that |str| will be live until |a_str| goes out of scope.
139 * As long as we don't retain a pointer to the string's characters for longer
140 * than that, we have avoided all garbage collection hazards.
142 template<typename T> class AnchorPermitted;
143 template<> class AnchorPermitted<JSObject *> { };
144 template<> class AnchorPermitted<const JSObject *> { };
145 template<> class AnchorPermitted<JSFunction *> { };
146 template<> class AnchorPermitted<const JSFunction *> { };
147 template<> class AnchorPermitted<JSString *> { };
148 template<> class AnchorPermitted<const JSString *> { };
149 template<> class AnchorPermitted<Value> { };
150 template<> class AnchorPermitted<const JSScript *> { };
151 template<> class AnchorPermitted<JSScript *> { };
153 template<typename T>
154 class Anchor: AnchorPermitted<T>
156 public:
157 Anchor() { }
158 explicit Anchor(T t) { hold = t; }
159 inline ~Anchor();
160 T &get() { return hold; }
161 const T &get() const { return hold; }
162 void set(const T &t) { hold = t; }
163 void operator=(const T &t) { hold = t; }
164 void clear() { hold = 0; }
165 private:
166 T hold;
167 Anchor(const Anchor &) MOZ_DELETE;
168 const Anchor &operator=(const Anchor &) MOZ_DELETE;
171 #ifdef __GNUC__
172 template<typename T>
173 inline Anchor<T>::~Anchor()
176 * No code is generated for this. But because this is marked 'volatile', G++ will
177 * assume it has important side-effects, and won't delete it. (G++ never looks at
178 * the actual text and notices it's empty.) And because we have passed |hold| to
179 * it, GCC will keep |hold| alive until this point.
181 * The "memory" clobber operand ensures that G++ will not move prior memory
182 * accesses after the asm --- it's a barrier. Unfortunately, it also means that
183 * G++ will assume that all memory has changed after the asm, as it would for a
184 * call to an unknown function. I don't know of a way to avoid that consequence.
186 asm volatile("":: "g" (hold) : "memory");
188 #else
189 template<typename T>
190 inline Anchor<T>::~Anchor()
193 * An adequate portable substitute, for non-structure types.
195 * The compiler promises that, by the end of an expression statement, the
196 * last-stored value to a volatile object is the same as it would be in an
197 * unoptimized, direct implementation (the "abstract machine" whose behavior the
198 * language spec describes). However, the compiler is still free to reorder
199 * non-volatile accesses across this store --- which is what we must prevent. So
200 * assigning the held value to a volatile variable, as we do here, is not enough.
202 * In our case, however, garbage collection only occurs at function calls, so it
203 * is sufficient to ensure that the destructor's store isn't moved earlier across
204 * any function calls that could collect. It is hard to imagine the compiler
205 * analyzing the program so thoroughly that it could prove that such motion was
206 * safe. In practice, compilers treat calls to the collector as opaque operations
207 * --- in particular, as operations which could access volatile variables, across
208 * which this destructor must not be moved.
210 * ("Objection, your honor! *Alleged* killer whale!")
212 * The disadvantage of this approach is that it does generate code for the store.
213 * We do need to use Anchors in some cases where cycles are tight.
215 * NB: there is a Anchor<Value>::~Anchor() specialization below.
217 volatile T sink;
218 sink = hold;
220 #endif /* defined(__GNUC__) */
223 * JS::Value is the C++ interface for a single JavaScript Engine value.
224 * A few general notes on JS::Value:
226 * - JS::Value has setX() and isX() members for X in
228 * { Int32, Double, String, Boolean, Undefined, Null, Object, Magic }
230 * JS::Value also contains toX() for each of the non-singleton types.
232 * - Magic is a singleton type whose payload contains a JSWhyMagic "reason" for
233 * the magic value. By providing JSWhyMagic values when creating and checking
234 * for magic values, it is possible to assert, at runtime, that only magic
235 * values with the expected reason flow through a particular value. For
236 * example, if cx->exception has a magic value, the reason must be
237 * JS_GENERATOR_CLOSING.
239 * - A key difference between JSVAL_* and JS::Value operations is that
240 * JS::Value gives null a separate type. Thus
242 * JSVAL_IS_OBJECT(v) === v.isObjectOrNull()
243 * !JSVAL_IS_PRIMITIVE(v) === v.isObject()
245 * To help prevent mistakenly boxing a nullable JSObject* as an object,
246 * Value::setObject takes a JSObject&. (Conversely, Value::asObject returns a
247 * JSObject&. A convenience member Value::setObjectOrNull is provided.
249 * - JSVAL_VOID is the same as the singleton value of the Undefined type.
251 * - Note that JS::Value is 8 bytes on 32 and 64-bit architectures. Thus, on
252 * 32-bit user code should avoid copying jsval/JS::Value as much as possible,
253 * preferring to pass by const Value &.
255 class Value
257 public:
259 * N.B. the default constructor leaves Value unitialized. Adding a default
260 * constructor prevents Value from being stored in a union.
263 /*** Mutators ***/
265 JS_ALWAYS_INLINE
266 void setNull() {
267 data.asBits = BUILD_JSVAL(JSVAL_TAG_NULL, 0).asBits;
270 JS_ALWAYS_INLINE
271 void setUndefined() {
272 data.asBits = BUILD_JSVAL(JSVAL_TAG_UNDEFINED, 0).asBits;
275 JS_ALWAYS_INLINE
276 void setInt32(int32_t i) {
277 data = INT32_TO_JSVAL_IMPL(i);
280 JS_ALWAYS_INLINE
281 int32_t &getInt32Ref() {
282 JS_ASSERT(isInt32());
283 return data.s.payload.i32;
286 JS_ALWAYS_INLINE
287 void setDouble(double d) {
288 data = DOUBLE_TO_JSVAL_IMPL(d);
291 JS_ALWAYS_INLINE
292 double &getDoubleRef() {
293 JS_ASSERT(isDouble());
294 return data.asDouble;
297 JS_ALWAYS_INLINE
298 void setString(JSString *str) {
299 JS_ASSERT(!IsPoisonedPtr(str));
300 data = STRING_TO_JSVAL_IMPL(str);
303 JS_ALWAYS_INLINE
304 void setString(const JS::Anchor<JSString *> &str) {
305 setString(str.get());
308 JS_ALWAYS_INLINE
309 void setObject(JSObject &obj) {
310 JS_ASSERT(!IsPoisonedPtr(&obj));
311 data = OBJECT_TO_JSVAL_IMPL(&obj);
314 JS_ALWAYS_INLINE
315 void setBoolean(bool b) {
316 data = BOOLEAN_TO_JSVAL_IMPL(b);
319 JS_ALWAYS_INLINE
320 void setMagic(JSWhyMagic why) {
321 data = MAGIC_TO_JSVAL_IMPL(why);
324 JS_ALWAYS_INLINE
325 bool setNumber(uint32_t ui) {
326 if (ui > JSVAL_INT_MAX) {
327 setDouble((double)ui);
328 return false;
329 } else {
330 setInt32((int32_t)ui);
331 return true;
335 JS_ALWAYS_INLINE
336 bool setNumber(double d) {
337 int32_t i;
338 if (MOZ_DOUBLE_IS_INT32(d, &i)) {
339 setInt32(i);
340 return true;
341 } else {
342 setDouble(d);
343 return false;
347 JS_ALWAYS_INLINE
348 void setObjectOrNull(JSObject *arg) {
349 if (arg)
350 setObject(*arg);
351 else
352 setNull();
355 JS_ALWAYS_INLINE
356 void swap(Value &rhs) {
357 uint64_t tmp = rhs.data.asBits;
358 rhs.data.asBits = data.asBits;
359 data.asBits = tmp;
362 /*** Value type queries ***/
364 JS_ALWAYS_INLINE
365 bool isUndefined() const {
366 return JSVAL_IS_UNDEFINED_IMPL(data);
369 JS_ALWAYS_INLINE
370 bool isNull() const {
371 return JSVAL_IS_NULL_IMPL(data);
374 JS_ALWAYS_INLINE
375 bool isNullOrUndefined() const {
376 return isNull() || isUndefined();
379 JS_ALWAYS_INLINE
380 bool isInt32() const {
381 return JSVAL_IS_INT32_IMPL(data);
384 JS_ALWAYS_INLINE
385 bool isInt32(int32_t i32) const {
386 return JSVAL_IS_SPECIFIC_INT32_IMPL(data, i32);
389 JS_ALWAYS_INLINE
390 bool isDouble() const {
391 return JSVAL_IS_DOUBLE_IMPL(data);
394 JS_ALWAYS_INLINE
395 bool isNumber() const {
396 return JSVAL_IS_NUMBER_IMPL(data);
399 JS_ALWAYS_INLINE
400 bool isString() const {
401 return JSVAL_IS_STRING_IMPL(data);
404 JS_ALWAYS_INLINE
405 bool isObject() const {
406 return JSVAL_IS_OBJECT_IMPL(data);
409 JS_ALWAYS_INLINE
410 bool isPrimitive() const {
411 return JSVAL_IS_PRIMITIVE_IMPL(data);
414 JS_ALWAYS_INLINE
415 bool isObjectOrNull() const {
416 return JSVAL_IS_OBJECT_OR_NULL_IMPL(data);
419 JS_ALWAYS_INLINE
420 bool isGCThing() const {
421 return JSVAL_IS_GCTHING_IMPL(data);
424 JS_ALWAYS_INLINE
425 bool isBoolean() const {
426 return JSVAL_IS_BOOLEAN_IMPL(data);
429 JS_ALWAYS_INLINE
430 bool isTrue() const {
431 return JSVAL_IS_SPECIFIC_BOOLEAN(data, true);
434 JS_ALWAYS_INLINE
435 bool isFalse() const {
436 return JSVAL_IS_SPECIFIC_BOOLEAN(data, false);
439 JS_ALWAYS_INLINE
440 bool isMagic() const {
441 return JSVAL_IS_MAGIC_IMPL(data);
444 JS_ALWAYS_INLINE
445 bool isMagic(JSWhyMagic why) const {
446 JS_ASSERT_IF(isMagic(), data.s.payload.why == why);
447 return JSVAL_IS_MAGIC_IMPL(data);
450 JS_ALWAYS_INLINE
451 bool isMarkable() const {
452 return JSVAL_IS_TRACEABLE_IMPL(data);
455 JS_ALWAYS_INLINE
456 JSGCTraceKind gcKind() const {
457 JS_ASSERT(isMarkable());
458 return JSGCTraceKind(JSVAL_TRACE_KIND_IMPL(data));
461 JS_ALWAYS_INLINE
462 JSWhyMagic whyMagic() const {
463 JS_ASSERT(isMagic());
464 return data.s.payload.why;
467 /*** Comparison ***/
469 JS_ALWAYS_INLINE
470 bool operator==(const Value &rhs) const {
471 return data.asBits == rhs.data.asBits;
474 JS_ALWAYS_INLINE
475 bool operator!=(const Value &rhs) const {
476 return data.asBits != rhs.data.asBits;
479 friend inline bool SameType(const Value &lhs, const Value &rhs);
481 /*** Extract the value's typed payload ***/
483 JS_ALWAYS_INLINE
484 int32_t toInt32() const {
485 JS_ASSERT(isInt32());
486 return JSVAL_TO_INT32_IMPL(data);
489 JS_ALWAYS_INLINE
490 double toDouble() const {
491 JS_ASSERT(isDouble());
492 return data.asDouble;
495 JS_ALWAYS_INLINE
496 double toNumber() const {
497 JS_ASSERT(isNumber());
498 return isDouble() ? toDouble() : double(toInt32());
501 JS_ALWAYS_INLINE
502 JSString *toString() const {
503 JS_ASSERT(isString());
504 return JSVAL_TO_STRING_IMPL(data);
507 JS_ALWAYS_INLINE
508 JSObject &toObject() const {
509 JS_ASSERT(isObject());
510 return *JSVAL_TO_OBJECT_IMPL(data);
513 JS_ALWAYS_INLINE
514 JSObject *toObjectOrNull() const {
515 JS_ASSERT(isObjectOrNull());
516 return JSVAL_TO_OBJECT_IMPL(data);
519 JS_ALWAYS_INLINE
520 void *toGCThing() const {
521 JS_ASSERT(isGCThing());
522 return JSVAL_TO_GCTHING_IMPL(data);
525 JS_ALWAYS_INLINE
526 bool toBoolean() const {
527 JS_ASSERT(isBoolean());
528 return JSVAL_TO_BOOLEAN_IMPL(data);
531 JS_ALWAYS_INLINE
532 uint32_t payloadAsRawUint32() const {
533 JS_ASSERT(!isDouble());
534 return data.s.payload.u32;
537 JS_ALWAYS_INLINE
538 uint64_t asRawBits() const {
539 return data.asBits;
542 JS_ALWAYS_INLINE
543 JSValueType extractNonDoubleType() const {
544 return JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(data);
548 * Private API
550 * Private setters/getters allow the caller to read/write arbitrary types
551 * that fit in the 64-bit payload. It is the caller's responsibility, after
552 * storing to a value with setPrivateX to read only using getPrivateX.
553 * Privates values are given a type type which ensures they are not marked.
556 JS_ALWAYS_INLINE
557 void setPrivate(void *ptr) {
558 data = PRIVATE_PTR_TO_JSVAL_IMPL(ptr);
561 JS_ALWAYS_INLINE
562 void *toPrivate() const {
563 JS_ASSERT(JSVAL_IS_DOUBLE_IMPL(data));
564 return JSVAL_TO_PRIVATE_PTR_IMPL(data);
567 JS_ALWAYS_INLINE
568 void setPrivateUint32(uint32_t ui) {
569 data = PRIVATE_UINT32_TO_JSVAL_IMPL(ui);
572 JS_ALWAYS_INLINE
573 uint32_t toPrivateUint32() const {
574 JS_ASSERT(JSVAL_IS_DOUBLE_IMPL(data));
575 return JSVAL_TO_PRIVATE_UINT32_IMPL(data);
578 JS_ALWAYS_INLINE
579 uint32_t &getPrivateUint32Ref() {
580 JS_ASSERT(isDouble());
581 return data.s.payload.u32;
585 * An unmarked value is just a void* cast as a Value. Thus, the Value is
586 * not safe for GC and must not be marked. This API avoids raw casts
587 * and the ensuing strict-aliasing warnings.
590 JS_ALWAYS_INLINE
591 void setUnmarkedPtr(void *ptr) {
592 data.asPtr = ptr;
595 JS_ALWAYS_INLINE
596 void *toUnmarkedPtr() const {
597 return data.asPtr;
600 const size_t *payloadWord() const {
601 #if JS_BITS_PER_WORD == 32
602 return &data.s.payload.word;
603 #elif JS_BITS_PER_WORD == 64
604 return &data.asWord;
605 #endif
608 #if !defined(_MSC_VER) && !defined(__sparc)
609 /* To make jsval binary compatible when linking across C and C++ with MSVC,
610 * JS::Value needs to be POD. Otherwise, jsval will be passed in memory
611 * in C++ but by value in C (bug 645111).
612 * Same issue for SPARC ABI. (bug 737344).
614 private:
615 #endif
617 jsval_layout data;
619 private:
620 void staticAssertions() {
621 JS_STATIC_ASSERT(sizeof(JSValueType) == 1);
622 JS_STATIC_ASSERT(sizeof(JSValueTag) == 4);
623 JS_STATIC_ASSERT(sizeof(JSBool) == 4);
624 JS_STATIC_ASSERT(sizeof(JSWhyMagic) <= 4);
625 JS_STATIC_ASSERT(sizeof(Value) == 8);
628 friend jsval_layout (::JSVAL_TO_IMPL)(Value);
629 friend Value (::IMPL_TO_JSVAL)(jsval_layout l);
632 inline bool
633 IsPoisonedValue(const Value &v)
635 if (v.isString())
636 return IsPoisonedPtr(v.toString());
637 if (v.isObject())
638 return IsPoisonedPtr(&v.toObject());
639 return false;
642 /************************************************************************/
644 static JS_ALWAYS_INLINE Value
645 NullValue()
647 Value v;
648 v.setNull();
649 return v;
652 static JS_ALWAYS_INLINE Value
653 UndefinedValue()
655 Value v;
656 v.setUndefined();
657 return v;
660 static JS_ALWAYS_INLINE Value
661 Int32Value(int32_t i32)
663 Value v;
664 v.setInt32(i32);
665 return v;
668 static JS_ALWAYS_INLINE Value
669 DoubleValue(double dbl)
671 Value v;
672 v.setDouble(dbl);
673 return v;
676 static JS_ALWAYS_INLINE Value
677 StringValue(JSString *str)
679 Value v;
680 v.setString(str);
681 return v;
684 static JS_ALWAYS_INLINE Value
685 BooleanValue(bool boo)
687 Value v;
688 v.setBoolean(boo);
689 return v;
692 static JS_ALWAYS_INLINE Value
693 ObjectValue(JSObject &obj)
695 Value v;
696 v.setObject(obj);
697 return v;
700 static JS_ALWAYS_INLINE Value
701 MagicValue(JSWhyMagic why)
703 Value v;
704 v.setMagic(why);
705 return v;
708 static JS_ALWAYS_INLINE Value
709 NumberValue(float f)
711 Value v;
712 v.setNumber(f);
713 return v;
716 static JS_ALWAYS_INLINE Value
717 NumberValue(double dbl)
719 Value v;
720 v.setNumber(dbl);
721 return v;
724 static JS_ALWAYS_INLINE Value
725 NumberValue(int8_t i)
727 return Int32Value(i);
730 static JS_ALWAYS_INLINE Value
731 NumberValue(uint8_t i)
733 return Int32Value(i);
736 static JS_ALWAYS_INLINE Value
737 NumberValue(int16_t i)
739 return Int32Value(i);
742 static JS_ALWAYS_INLINE Value
743 NumberValue(uint16_t i)
745 return Int32Value(i);
748 static JS_ALWAYS_INLINE Value
749 NumberValue(int32_t i)
751 return Int32Value(i);
754 static JS_ALWAYS_INLINE Value
755 NumberValue(uint32_t i)
757 Value v;
758 v.setNumber(i);
759 return v;
762 namespace detail {
764 template <bool Signed>
765 class MakeNumberValue
767 public:
768 template<typename T>
769 static inline Value create(const T t)
771 Value v;
772 if (JSVAL_INT_MIN <= t && t <= JSVAL_INT_MAX)
773 v.setInt32(int32_t(t));
774 else
775 v.setDouble(double(t));
776 return v;
780 template <>
781 class MakeNumberValue<false>
783 public:
784 template<typename T>
785 static inline Value create(const T t)
787 Value v;
788 if (t <= JSVAL_INT_MAX)
789 v.setInt32(int32_t(t));
790 else
791 v.setDouble(double(t));
792 return v;
796 } /* namespace detail */
798 template <typename T>
799 static JS_ALWAYS_INLINE Value
800 NumberValue(const T t)
802 MOZ_ASSERT(T(double(t)) == t, "value creation would be lossy");
803 return detail::MakeNumberValue<std::numeric_limits<T>::is_signed>::create(t);
806 static JS_ALWAYS_INLINE Value
807 ObjectOrNullValue(JSObject *obj)
809 Value v;
810 v.setObjectOrNull(obj);
811 return v;
814 static JS_ALWAYS_INLINE Value
815 PrivateValue(void *ptr)
817 Value v;
818 v.setPrivate(ptr);
819 return v;
822 static JS_ALWAYS_INLINE Value
823 PrivateUint32Value(uint32_t ui)
825 Value v;
826 v.setPrivateUint32(ui);
827 return v;
830 JS_ALWAYS_INLINE bool
831 SameType(const Value &lhs, const Value &rhs)
833 return JSVAL_SAME_TYPE_IMPL(lhs.data, rhs.data);
836 template <> struct RootMethods<const Value>
838 static Value initial() { return UndefinedValue(); }
839 static ThingRootKind kind() { return THING_ROOT_VALUE; }
840 static bool poisoned(const Value &v) { return IsPoisonedValue(v); }
843 template <> struct RootMethods<Value>
845 static Value initial() { return UndefinedValue(); }
846 static ThingRootKind kind() { return THING_ROOT_VALUE; }
847 static bool poisoned(const Value &v) { return IsPoisonedValue(v); }
850 /************************************************************************/
852 #ifndef __GNUC__
855 * The default assignment operator for |struct C| has the signature:
857 * C& C::operator=(const C&)
859 * And in particular requires implicit conversion of |this| to type |C| for the
860 * return value. But |volatile C| cannot thus be converted to |C|, so just
861 * doing |sink = hold| as in the non-specialized version would fail to compile.
862 * Do the assignment on asBits instead, since I don't think we want to give
863 * jsval_layout an assignment operator returning |volatile jsval_layout|.
865 template<>
866 inline Anchor<Value>::~Anchor()
868 volatile uint64_t bits;
869 bits = JSVAL_TO_IMPL(hold).asBits;
872 #endif
874 #if defined JS_THREADSAFE && defined DEBUG
876 class JS_PUBLIC_API(AutoCheckRequestDepth)
878 JSContext *cx;
879 public:
880 AutoCheckRequestDepth(JSContext *cx);
881 ~AutoCheckRequestDepth();
884 # define CHECK_REQUEST(cx) \
885 JS::AutoCheckRequestDepth _autoCheckRequestDepth(cx)
887 #else
889 # define CHECK_REQUEST(cx) \
890 ((void) 0)
892 #endif /* JS_THREADSAFE && DEBUG */
894 #ifdef DEBUG
895 /* Assert that we're not doing GC on cx, that we're in a request as
896 needed, and that the compartments for cx and v are correct. */
897 JS_PUBLIC_API(void)
898 AssertArgumentsAreSane(JSContext *cx, const Value &v);
899 #else
900 inline void AssertArgumentsAreSane(JSContext *cx, const Value &v) {
901 /* Do nothing */
903 #endif /* DEBUG */
905 class JS_PUBLIC_API(AutoGCRooter) {
906 public:
907 AutoGCRooter(JSContext *cx, ptrdiff_t tag);
909 ~AutoGCRooter() {
910 JS_ASSERT(this == *stackTop);
911 *stackTop = down;
914 /* Implemented in jsgc.cpp. */
915 inline void trace(JSTracer *trc);
916 static void traceAll(JSTracer *trc);
918 protected:
919 AutoGCRooter * const down;
922 * Discriminates actual subclass of this being used. If non-negative, the
923 * subclass roots an array of values of the length stored in this field.
924 * If negative, meaning is indicated by the corresponding value in the enum
925 * below. Any other negative value indicates some deeper problem such as
926 * memory corruption.
928 ptrdiff_t tag;
930 enum {
931 JSVAL = -1, /* js::AutoValueRooter */
932 VALARRAY = -2, /* js::AutoValueArrayRooter */
933 PARSER = -3, /* js::Parser */
934 SHAPEVECTOR = -4, /* js::AutoShapeVector */
935 ENUMERATOR = -5, /* js::AutoEnumStateRooter */
936 IDARRAY = -6, /* js::AutoIdArray */
937 DESCRIPTORS = -7, /* js::AutoPropDescArrayRooter */
938 NAMESPACES = -8, /* js::AutoNamespaceArray */
939 XML = -9, /* js::AutoXMLRooter */
940 OBJECT = -10, /* js::AutoObjectRooter */
941 ID = -11, /* js::AutoIdRooter */
942 VALVECTOR = -12, /* js::AutoValueVector */
943 DESCRIPTOR = -13, /* js::AutoPropertyDescriptorRooter */
944 STRING = -14, /* js::AutoStringRooter */
945 IDVECTOR = -15, /* js::AutoIdVector */
946 OBJVECTOR = -16, /* js::AutoObjectVector */
947 SCRIPTVECTOR =-17 /* js::AutoScriptVector */
950 private:
951 AutoGCRooter ** const stackTop;
953 /* No copy or assignment semantics. */
954 AutoGCRooter(AutoGCRooter &ida) MOZ_DELETE;
955 void operator=(AutoGCRooter &ida) MOZ_DELETE;
958 class AutoValueRooter : private AutoGCRooter
960 public:
961 explicit AutoValueRooter(JSContext *cx
962 JS_GUARD_OBJECT_NOTIFIER_PARAM)
963 : AutoGCRooter(cx, JSVAL), val(NullValue())
965 JS_GUARD_OBJECT_NOTIFIER_INIT;
968 AutoValueRooter(JSContext *cx, const Value &v
969 JS_GUARD_OBJECT_NOTIFIER_PARAM)
970 : AutoGCRooter(cx, JSVAL), val(v)
972 JS_GUARD_OBJECT_NOTIFIER_INIT;
976 * If you are looking for Object* overloads, use AutoObjectRooter instead;
977 * rooting Object*s as a js::Value requires discerning whether or not it is
978 * a function object. Also, AutoObjectRooter is smaller.
981 void set(Value v) {
982 JS_ASSERT(tag == JSVAL);
983 val = v;
986 const Value &value() const {
987 JS_ASSERT(tag == JSVAL);
988 return val;
991 Value *addr() {
992 JS_ASSERT(tag == JSVAL);
993 return &val;
996 const Value &jsval_value() const {
997 JS_ASSERT(tag == JSVAL);
998 return val;
1001 Value *jsval_addr() {
1002 JS_ASSERT(tag == JSVAL);
1003 return &val;
1006 friend void AutoGCRooter::trace(JSTracer *trc);
1008 private:
1009 Value val;
1010 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1013 class AutoObjectRooter : private AutoGCRooter {
1014 public:
1015 AutoObjectRooter(JSContext *cx, JSObject *obj = NULL
1016 JS_GUARD_OBJECT_NOTIFIER_PARAM)
1017 : AutoGCRooter(cx, OBJECT), obj(obj)
1019 JS_GUARD_OBJECT_NOTIFIER_INIT;
1022 void setObject(JSObject *obj) {
1023 this->obj = obj;
1026 JSObject * object() const {
1027 return obj;
1030 JSObject ** addr() {
1031 return &obj;
1034 friend void AutoGCRooter::trace(JSTracer *trc);
1036 private:
1037 JSObject *obj;
1038 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1041 class AutoStringRooter : private AutoGCRooter {
1042 public:
1043 AutoStringRooter(JSContext *cx, JSString *str = NULL
1044 JS_GUARD_OBJECT_NOTIFIER_PARAM)
1045 : AutoGCRooter(cx, STRING), str(str)
1047 JS_GUARD_OBJECT_NOTIFIER_INIT;
1050 void setString(JSString *str) {
1051 this->str = str;
1054 JSString * string() const {
1055 return str;
1058 JSString ** addr() {
1059 return &str;
1062 friend void AutoGCRooter::trace(JSTracer *trc);
1064 private:
1065 JSString *str;
1066 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1069 class AutoArrayRooter : private AutoGCRooter {
1070 public:
1071 AutoArrayRooter(JSContext *cx, size_t len, Value *vec
1072 JS_GUARD_OBJECT_NOTIFIER_PARAM)
1073 : AutoGCRooter(cx, len), array(vec), skip(cx, array, len)
1075 JS_GUARD_OBJECT_NOTIFIER_INIT;
1076 JS_ASSERT(tag >= 0);
1079 void changeLength(size_t newLength) {
1080 tag = ptrdiff_t(newLength);
1081 JS_ASSERT(tag >= 0);
1084 void changeArray(Value *newArray, size_t newLength) {
1085 changeLength(newLength);
1086 array = newArray;
1089 Value *array;
1091 friend void AutoGCRooter::trace(JSTracer *trc);
1093 private:
1094 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1096 SkipRoot skip;
1099 /* The auto-root for enumeration object and its state. */
1100 class AutoEnumStateRooter : private AutoGCRooter
1102 public:
1103 AutoEnumStateRooter(JSContext *cx, JSObject *obj
1104 JS_GUARD_OBJECT_NOTIFIER_PARAM)
1105 : AutoGCRooter(cx, ENUMERATOR), obj(obj), stateValue(), context(cx)
1107 JS_GUARD_OBJECT_NOTIFIER_INIT;
1108 JS_ASSERT(obj);
1111 ~AutoEnumStateRooter();
1113 friend void AutoGCRooter::trace(JSTracer *trc);
1115 const Value &state() const { return stateValue; }
1116 Value *addr() { return &stateValue; }
1118 protected:
1119 void trace(JSTracer *trc);
1121 JSObject *obj;
1123 private:
1124 Value stateValue;
1125 JSContext *context;
1126 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1129 template<class T>
1130 class AutoVectorRooter : protected AutoGCRooter
1132 public:
1133 explicit AutoVectorRooter(JSContext *cx, ptrdiff_t tag
1134 JS_GUARD_OBJECT_NOTIFIER_PARAM)
1135 : AutoGCRooter(cx, tag), vector(cx), vectorRoot(cx, &vector)
1137 JS_GUARD_OBJECT_NOTIFIER_INIT;
1140 size_t length() const { return vector.length(); }
1142 bool append(const T &v) { return vector.append(v); }
1144 /* For use when space has already been reserved. */
1145 void infallibleAppend(const T &v) { vector.infallibleAppend(v); }
1147 void popBack() { vector.popBack(); }
1148 T popCopy() { return vector.popCopy(); }
1150 bool growBy(size_t inc) {
1151 size_t oldLength = vector.length();
1152 if (!vector.growByUninitialized(inc))
1153 return false;
1154 makeRangeGCSafe(oldLength);
1155 return true;
1158 bool resize(size_t newLength) {
1159 size_t oldLength = vector.length();
1160 if (newLength <= oldLength) {
1161 vector.shrinkBy(oldLength - newLength);
1162 return true;
1164 if (!vector.growByUninitialized(newLength - oldLength))
1165 return false;
1166 makeRangeGCSafe(oldLength);
1167 return true;
1170 void clear() { vector.clear(); }
1172 bool reserve(size_t newLength) {
1173 return vector.reserve(newLength);
1176 T &operator[](size_t i) { return vector[i]; }
1177 const T &operator[](size_t i) const { return vector[i]; }
1179 const T *begin() const { return vector.begin(); }
1180 T *begin() { return vector.begin(); }
1182 const T *end() const { return vector.end(); }
1183 T *end() { return vector.end(); }
1185 const T &back() const { return vector.back(); }
1187 friend void AutoGCRooter::trace(JSTracer *trc);
1189 private:
1190 void makeRangeGCSafe(size_t oldLength) {
1191 T *t = vector.begin() + oldLength;
1192 for (size_t i = oldLength; i < vector.length(); ++i, ++t)
1193 memset(t, 0, sizeof(T));
1196 typedef js::Vector<T, 8> VectorImpl;
1197 VectorImpl vector;
1199 /* Prevent overwriting of inline elements in vector. */
1200 SkipRoot vectorRoot;
1202 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1205 class AutoValueVector : public AutoVectorRooter<Value>
1207 public:
1208 explicit AutoValueVector(JSContext *cx
1209 JS_GUARD_OBJECT_NOTIFIER_PARAM)
1210 : AutoVectorRooter<Value>(cx, VALVECTOR)
1212 JS_GUARD_OBJECT_NOTIFIER_INIT;
1215 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1218 class AutoIdVector : public AutoVectorRooter<jsid>
1220 public:
1221 explicit AutoIdVector(JSContext *cx
1222 JS_GUARD_OBJECT_NOTIFIER_PARAM)
1223 : AutoVectorRooter<jsid>(cx, IDVECTOR)
1225 JS_GUARD_OBJECT_NOTIFIER_INIT;
1228 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1231 class AutoScriptVector : public AutoVectorRooter<JSScript *>
1233 public:
1234 explicit AutoScriptVector(JSContext *cx
1235 JS_GUARD_OBJECT_NOTIFIER_PARAM)
1236 : AutoVectorRooter<JSScript *>(cx, SCRIPTVECTOR)
1238 JS_GUARD_OBJECT_NOTIFIER_INIT;
1241 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1244 } /* namespace JS */
1246 /************************************************************************/
1249 * JS::Value and jsval are the same type; jsval is the old name, kept around
1250 * for backwards compatibility along with all the JSVAL_* operations below.
1251 * jsval_layout is an implementation detail and should not be used externally.
1253 typedef JS::Value jsval;
1255 static JS_ALWAYS_INLINE jsval_layout
1256 JSVAL_TO_IMPL(jsval v)
1258 return v.data;
1261 static JS_ALWAYS_INLINE jsval
1262 IMPL_TO_JSVAL(jsval_layout l)
1264 JS::Value v;
1265 v.data = l;
1266 return v;
1269 #ifdef DEBUG
1270 struct JSValueAlignmentTester { char c; JS::Value v; };
1271 JS_STATIC_ASSERT(sizeof(JSValueAlignmentTester) == 16);
1272 #endif /* DEBUG */
1274 #else /* defined(__cplusplus) */
1277 * For SpiderMonkey C clients, there is no JS::Value class, only the
1278 * traditional jsval with the traditional JSVAL_* operations. Since
1279 * SpiderMonkey itself is always compiled as C++, this relies on the binary
1280 * compatibility of jsval_layout and JS::Value (statically asserted below).
1282 typedef union jsval_layout jsval;
1284 static JS_ALWAYS_INLINE jsval_layout
1285 JSVAL_TO_IMPL(jsval v)
1287 return v;
1290 static JS_ALWAYS_INLINE jsval
1291 IMPL_TO_JSVAL(jsval_layout l)
1293 return l;
1296 #endif /* defined(__cplusplus) */
1298 #ifdef DEBUG
1299 typedef struct { char c; jsval_layout l; } JSLayoutAlignmentTester;
1300 JS_STATIC_ASSERT(sizeof(JSLayoutAlignmentTester) == 16);
1301 #endif /* DEBUG */
1303 JS_STATIC_ASSERT(sizeof(jsval_layout) == sizeof(jsval));
1305 /************************************************************************/
1307 /* JSClass operation signatures. */
1310 * Add, delete, or get a property named by id in obj. Note the jsid id
1311 * type -- id may be a string (Unicode property identifier) or an int (element
1312 * index). The *vp out parameter, on success, is the new property value after
1313 * an add or get. After a successful delete, *vp is JSVAL_FALSE iff
1314 * obj[id] can't be deleted (because it's permanent).
1316 typedef JSBool
1317 (* JSPropertyOp)(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
1320 * Set a property named by id in obj, treating the assignment as strict
1321 * mode code if strict is true. Note the jsid id type -- id may be a string
1322 * (Unicode property identifier) or an int (element index). The *vp out
1323 * parameter, on success, is the new property value after the
1324 * set.
1326 typedef JSBool
1327 (* JSStrictPropertyOp)(JSContext *cx, JSObject *obj, jsid id, JSBool strict, jsval *vp);
1330 * This function type is used for callbacks that enumerate the properties of
1331 * a JSObject. The behavior depends on the value of enum_op:
1333 * JSENUMERATE_INIT
1334 * A new, opaque iterator state should be allocated and stored in *statep.
1335 * (You can use PRIVATE_TO_JSVAL() to tag the pointer to be stored).
1337 * The number of properties that will be enumerated should be returned as
1338 * an integer jsval in *idp, if idp is non-null, and provided the number of
1339 * enumerable properties is known. If idp is non-null and the number of
1340 * enumerable properties can't be computed in advance, *idp should be set
1341 * to JSVAL_ZERO.
1343 * JSENUMERATE_INIT_ALL
1344 * Used identically to JSENUMERATE_INIT, but exposes all properties of the
1345 * object regardless of enumerability.
1347 * JSENUMERATE_NEXT
1348 * A previously allocated opaque iterator state is passed in via statep.
1349 * Return the next jsid in the iteration using *idp. The opaque iterator
1350 * state pointed at by statep is destroyed and *statep is set to JSVAL_NULL
1351 * if there are no properties left to enumerate.
1353 * JSENUMERATE_DESTROY
1354 * Destroy the opaque iterator state previously allocated in *statep by a
1355 * call to this function when enum_op was JSENUMERATE_INIT or
1356 * JSENUMERATE_INIT_ALL.
1358 * The return value is used to indicate success, with a value of JS_FALSE
1359 * indicating failure.
1361 typedef JSBool
1362 (* JSNewEnumerateOp)(JSContext *cx, JSObject *obj, JSIterateOp enum_op,
1363 jsval *statep, jsid *idp);
1366 * The old-style JSClass.enumerate op should define all lazy properties not
1367 * yet reflected in obj.
1369 typedef JSBool
1370 (* JSEnumerateOp)(JSContext *cx, JSObject *obj);
1373 * Resolve a lazy property named by id in obj by defining it directly in obj.
1374 * Lazy properties are those reflected from some peer native property space
1375 * (e.g., the DOM attributes for a given node reflected as obj) on demand.
1377 * JS looks for a property in an object, and if not found, tries to resolve
1378 * the given id. If resolve succeeds, the engine looks again in case resolve
1379 * defined obj[id]. If no such property exists directly in obj, the process
1380 * is repeated with obj's prototype, etc.
1382 * NB: JSNewResolveOp provides a cheaper way to resolve lazy properties.
1384 typedef JSBool
1385 (* JSResolveOp)(JSContext *cx, JSObject *obj, jsid id);
1388 * Like JSResolveOp, but flags provide contextual information as follows:
1390 * JSRESOLVE_QUALIFIED a qualified property id: obj.id or obj[id], not id
1391 * JSRESOLVE_ASSIGNING obj[id] is on the left-hand side of an assignment
1392 * JSRESOLVE_DETECTING 'if (o.p)...' or similar detection opcode sequence
1393 * JSRESOLVE_DECLARING var, const, or function prolog declaration opcode
1394 * JSRESOLVE_CLASSNAME class name used when constructing
1396 * The *objp out parameter, on success, should be null to indicate that id
1397 * was not resolved; and non-null, referring to obj or one of its prototypes,
1398 * if id was resolved.
1400 * This hook instead of JSResolveOp is called via the JSClass.resolve member
1401 * if JSCLASS_NEW_RESOLVE is set in JSClass.flags.
1403 * Setting JSCLASS_NEW_RESOLVE and JSCLASS_NEW_RESOLVE_GETS_START further
1404 * extends this hook by passing in the starting object on the prototype chain
1405 * via *objp. Thus a resolve hook implementation may define the property id
1406 * being resolved in the object in which the id was first sought, rather than
1407 * in a prototype object whose class led to the resolve hook being called.
1409 * When using JSCLASS_NEW_RESOLVE_GETS_START, the resolve hook must therefore
1410 * null *objp to signify "not resolved". With only JSCLASS_NEW_RESOLVE and no
1411 * JSCLASS_NEW_RESOLVE_GETS_START, the hook can assume *objp is null on entry.
1412 * This is not good practice, but enough existing hook implementations count
1413 * on it that we can't break compatibility by passing the starting object in
1414 * *objp without a new JSClass flag.
1416 typedef JSBool
1417 (* JSNewResolveOp)(JSContext *cx, JSObject *obj, jsid id, unsigned flags,
1418 JSObject **objp);
1421 * Convert obj to the given type, returning true with the resulting value in
1422 * *vp on success, and returning false on error or exception.
1424 typedef JSBool
1425 (* JSConvertOp)(JSContext *cx, JSObject *obj, JSType type, jsval *vp);
1428 * Delegate typeof to an object so it can cloak a primitive or another object.
1430 typedef JSType
1431 (* JSTypeOfOp)(JSContext *cx, JSObject *obj);
1433 typedef struct JSFreeOp JSFreeOp;
1435 struct JSFreeOp {
1436 #ifndef __cplusplus
1437 JSRuntime *runtime;
1438 #else
1439 private:
1440 JSRuntime *runtime_;
1442 protected:
1443 JSFreeOp(JSRuntime *rt)
1444 : runtime_(rt) { }
1446 public:
1447 JSRuntime *runtime() const {
1448 return runtime_;
1450 #endif
1454 * Finalize obj, which the garbage collector has determined to be unreachable
1455 * from other live objects or from GC roots. Obviously, finalizers must never
1456 * store a reference to obj.
1458 typedef void
1459 (* JSFinalizeOp)(JSFreeOp *fop, JSObject *obj);
1462 * Finalizes external strings created by JS_NewExternalString.
1464 typedef struct JSStringFinalizer JSStringFinalizer;
1466 struct JSStringFinalizer {
1467 void (*finalize)(const JSStringFinalizer *fin, jschar *chars);
1471 * JSClass.checkAccess type: check whether obj[id] may be accessed per mode,
1472 * returning false on error/exception, true on success with obj[id]'s last-got
1473 * value in *vp, and its attributes in *attrsp. As for JSPropertyOp above, id
1474 * is either a string or an int jsval.
1476 typedef JSBool
1477 (* JSCheckAccessOp)(JSContext *cx, JSObject *obj, jsid id, JSAccessMode mode,
1478 jsval *vp);
1481 * Check whether v is an instance of obj. Return false on error or exception,
1482 * true on success with JS_TRUE in *bp if v is an instance of obj, JS_FALSE in
1483 * *bp otherwise.
1485 typedef JSBool
1486 (* JSHasInstanceOp)(JSContext *cx, JSObject *obj, const jsval *v, JSBool *bp);
1489 * Function type for trace operation of the class called to enumerate all
1490 * traceable things reachable from obj's private data structure. For each such
1491 * thing, a trace implementation must call
1493 * JS_CallTracer(trc, thing, kind);
1495 * or one of its convenience macros as described in jsapi.h.
1497 * JSTraceOp implementation can assume that no other threads mutates object
1498 * state. It must not change state of the object or corresponding native
1499 * structures. The only exception for this rule is the case when the embedding
1500 * needs a tight integration with GC. In that case the embedding can check if
1501 * the traversal is a part of the marking phase through calling
1502 * JS_IsGCMarkingTracer and apply a special code like emptying caches or
1503 * marking its native structures.
1505 typedef void
1506 (* JSTraceOp)(JSTracer *trc, JSObject *obj);
1509 * DEBUG only callback that JSTraceOp implementation can provide to return
1510 * a string describing the reference traced with JS_CallTracer.
1512 typedef void
1513 (* JSTraceNamePrinter)(JSTracer *trc, char *buf, size_t bufsize);
1515 typedef JSBool
1516 (* JSEqualityOp)(JSContext *cx, JSObject *obj, const jsval *v, JSBool *bp);
1519 * Typedef for native functions called by the JS VM.
1521 * See jsapi.h, the JS_CALLEE, JS_THIS, etc. macros.
1524 typedef JSBool
1525 (* JSNative)(JSContext *cx, unsigned argc, jsval *vp);
1527 /* Callbacks and their arguments. */
1529 typedef enum JSContextOp {
1530 JSCONTEXT_NEW,
1531 JSCONTEXT_DESTROY
1532 } JSContextOp;
1535 * The possible values for contextOp when the runtime calls the callback are:
1536 * JSCONTEXT_NEW JS_NewContext successfully created a new JSContext
1537 * instance. The callback can initialize the instance as
1538 * required. If the callback returns false, the instance
1539 * will be destroyed and JS_NewContext returns null. In
1540 * this case the callback is not called again.
1541 * JSCONTEXT_DESTROY One of JS_DestroyContext* methods is called. The
1542 * callback may perform its own cleanup and must always
1543 * return true.
1544 * Any other value For future compatibility the callback must do nothing
1545 * and return true in this case.
1547 typedef JSBool
1548 (* JSContextCallback)(JSContext *cx, unsigned contextOp);
1550 typedef enum JSGCStatus {
1551 JSGC_BEGIN,
1552 JSGC_END
1553 } JSGCStatus;
1555 typedef void
1556 (* JSGCCallback)(JSRuntime *rt, JSGCStatus status);
1558 typedef enum JSFinalizeStatus {
1559 JSFINALIZE_START,
1560 JSFINALIZE_END
1561 } JSFinalizeStatus;
1563 typedef void
1564 (* JSFinalizeCallback)(JSFreeOp *fop, JSFinalizeStatus status);
1567 * Generic trace operation that calls JS_CallTracer on each traceable thing
1568 * stored in data.
1570 typedef void
1571 (* JSTraceDataOp)(JSTracer *trc, void *data);
1573 typedef JSBool
1574 (* JSOperationCallback)(JSContext *cx);
1576 typedef void
1577 (* JSErrorReporter)(JSContext *cx, const char *message, JSErrorReport *report);
1579 #ifdef MOZ_TRACE_JSCALLS
1580 typedef void
1581 (* JSFunctionCallback)(const JSFunction *fun,
1582 const JSScript *scr,
1583 const JSContext *cx,
1584 int entering);
1585 #endif
1588 * Possible exception types. These types are part of a JSErrorFormatString
1589 * structure. They define which error to throw in case of a runtime error.
1590 * JSEXN_NONE marks an unthrowable error.
1592 typedef enum JSExnType {
1593 JSEXN_NONE = -1,
1594 JSEXN_ERR,
1595 JSEXN_INTERNALERR,
1596 JSEXN_EVALERR,
1597 JSEXN_RANGEERR,
1598 JSEXN_REFERENCEERR,
1599 JSEXN_SYNTAXERR,
1600 JSEXN_TYPEERR,
1601 JSEXN_URIERR,
1602 JSEXN_LIMIT
1603 } JSExnType;
1605 typedef struct JSErrorFormatString {
1606 /* The error format string (UTF-8 if js_CStringsAreUTF8). */
1607 const char *format;
1609 /* The number of arguments to expand in the formatted error message. */
1610 uint16_t argCount;
1612 /* One of the JSExnType constants above. */
1613 int16_t exnType;
1614 } JSErrorFormatString;
1616 typedef const JSErrorFormatString *
1617 (* JSErrorCallback)(void *userRef, const char *locale,
1618 const unsigned errorNumber);
1620 #ifdef va_start
1621 #define JS_ARGUMENT_FORMATTER_DEFINED 1
1623 typedef JSBool
1624 (* JSArgumentFormatter)(JSContext *cx, const char *format, JSBool fromJS,
1625 jsval **vpp, va_list *app);
1626 #endif
1628 typedef JSBool
1629 (* JSLocaleToUpperCase)(JSContext *cx, JSString *src, jsval *rval);
1631 typedef JSBool
1632 (* JSLocaleToLowerCase)(JSContext *cx, JSString *src, jsval *rval);
1634 typedef JSBool
1635 (* JSLocaleCompare)(JSContext *cx, JSString *src1, JSString *src2,
1636 jsval *rval);
1638 typedef JSBool
1639 (* JSLocaleToUnicode)(JSContext *cx, const char *src, jsval *rval);
1642 * Security protocol types.
1645 typedef void
1646 (* JSDestroyPrincipalsOp)(JSPrincipals *principals);
1648 typedef JSBool
1649 (* JSSubsumePrincipalsOp)(JSPrincipals *principals1, JSPrincipals *principals2);
1652 * Return a weak reference to the principals associated with obj, possibly via
1653 * the immutable parent chain leading from obj to a top-level container (e.g.,
1654 * a window object in the DOM level 0). If there are no principals associated
1655 * with obj, return null. Therefore null does not mean an error was reported;
1656 * in no event should an error be reported or an exception be thrown by this
1657 * callback's implementation.
1659 typedef JSPrincipals *
1660 (* JSObjectPrincipalsFinder)(JSObject *obj);
1663 * Used to check if a CSP instance wants to disable eval() and friends.
1664 * See js_CheckCSPPermitsJSAction() in jsobj.
1666 typedef JSBool
1667 (* JSCSPEvalChecker)(JSContext *cx);
1670 * Security callbacks for pushing and popping context principals. These are only
1671 * temporarily necessary and will hopefully be gone again in a matter of weeks.
1673 typedef JSBool
1674 (* JSPushContextPrincipalOp)(JSContext *cx, JSPrincipals *principals);
1676 typedef JSBool
1677 (* JSPopContextPrincipalOp)(JSContext *cx);
1680 * Callback used to ask the embedding for the cross compartment wrapper handler
1681 * that implements the desired prolicy for this kind of object in the
1682 * destination compartment.
1684 typedef JSObject *
1685 (* JSWrapObjectCallback)(JSContext *cx, JSObject *obj, JSObject *proto, JSObject *parent,
1686 unsigned flags);
1689 * Callback used by the wrap hook to ask the embedding to prepare an object
1690 * for wrapping in a context. This might include unwrapping other wrappers
1691 * or even finding a more suitable object for the new compartment.
1693 typedef JSObject *
1694 (* JSPreWrapCallback)(JSContext *cx, JSObject *scope, JSObject *obj, unsigned flags);
1696 typedef void
1697 (* JSDestroyCompartmentCallback)(JSFreeOp *fop, JSCompartment *compartment);
1700 * Read structured data from the reader r. This hook is used to read a value
1701 * previously serialized by a call to the WriteStructuredCloneOp hook.
1703 * tag and data are the pair of uint32_t values from the header. The callback
1704 * may use the JS_Read* APIs to read any other relevant parts of the object
1705 * from the reader r. closure is any value passed to the JS_ReadStructuredClone
1706 * function. Return the new object on success, NULL on error/exception.
1708 typedef JSObject *(*ReadStructuredCloneOp)(JSContext *cx, JSStructuredCloneReader *r,
1709 uint32_t tag, uint32_t data, void *closure);
1712 * Structured data serialization hook. The engine can write primitive values,
1713 * Objects, Arrays, Dates, RegExps, TypedArrays, and ArrayBuffers. Any other
1714 * type of object requires application support. This callback must first use
1715 * the JS_WriteUint32Pair API to write an object header, passing a value
1716 * greater than JS_SCTAG_USER to the tag parameter. Then it can use the
1717 * JS_Write* APIs to write any other relevant parts of the value v to the
1718 * writer w. closure is any value passed to the JS_WriteStructuredCLone function.
1720 * Return true on success, false on error/exception.
1722 typedef JSBool (*WriteStructuredCloneOp)(JSContext *cx, JSStructuredCloneWriter *w,
1723 JSObject *obj, void *closure);
1726 * This is called when JS_WriteStructuredClone finds that the object to be
1727 * written is recursive. To follow HTML5, the application must throw a
1728 * DATA_CLONE_ERR DOMException. errorid is always JS_SCERR_RECURSION.
1730 typedef void (*StructuredCloneErrorOp)(JSContext *cx, uint32_t errorid);
1732 /************************************************************************/
1734 JS_BEGIN_EXTERN_C
1737 * Silence warning about returning JS::Value (aka jsval) from functions with C
1738 * linkage. For C JSAPI clients, jsval will be jsval_layout, which should be
1739 * ABI compatible.
1741 #ifdef _MSC_VER
1742 # pragma warning(disable:4190)
1743 #endif
1745 /************************************************************************/
1748 * JS constants. For efficiency, prefer predicates (e.g., JSVAL_IS_NULL).
1749 * N.B. These constants are initialized at startup.
1751 extern JS_PUBLIC_DATA(const jsval) JSVAL_NULL;
1752 extern JS_PUBLIC_DATA(const jsval) JSVAL_ZERO;
1753 extern JS_PUBLIC_DATA(const jsval) JSVAL_ONE;
1754 extern JS_PUBLIC_DATA(const jsval) JSVAL_FALSE;
1755 extern JS_PUBLIC_DATA(const jsval) JSVAL_TRUE;
1756 extern JS_PUBLIC_DATA(const jsval) JSVAL_VOID;
1758 /************************************************************************/
1760 static JS_ALWAYS_INLINE JSBool
1761 JSVAL_IS_NULL(jsval v)
1763 return JSVAL_IS_NULL_IMPL(JSVAL_TO_IMPL(v));
1766 static JS_ALWAYS_INLINE JSBool
1767 JSVAL_IS_VOID(jsval v)
1769 return JSVAL_IS_UNDEFINED_IMPL(JSVAL_TO_IMPL(v));
1772 static JS_ALWAYS_INLINE JSBool
1773 JSVAL_IS_INT(jsval v)
1775 return JSVAL_IS_INT32_IMPL(JSVAL_TO_IMPL(v));
1778 static JS_ALWAYS_INLINE int32_t
1779 JSVAL_TO_INT(jsval v)
1781 JS_ASSERT(JSVAL_IS_INT(v));
1782 return JSVAL_TO_INT32_IMPL(JSVAL_TO_IMPL(v));
1785 static JS_ALWAYS_INLINE jsval
1786 INT_TO_JSVAL(int32_t i)
1788 return IMPL_TO_JSVAL(INT32_TO_JSVAL_IMPL(i));
1791 static JS_ALWAYS_INLINE JSBool
1792 JSVAL_IS_DOUBLE(jsval v)
1794 return JSVAL_IS_DOUBLE_IMPL(JSVAL_TO_IMPL(v));
1797 static JS_ALWAYS_INLINE double
1798 JSVAL_TO_DOUBLE(jsval v)
1800 jsval_layout l;
1801 JS_ASSERT(JSVAL_IS_DOUBLE(v));
1802 l = JSVAL_TO_IMPL(v);
1803 return l.asDouble;
1806 static JS_ALWAYS_INLINE jsval
1807 DOUBLE_TO_JSVAL(double d)
1809 /* This is a manually inlined version of:
1810 * d = JS_CANONICALIZE_NAN(d);
1811 * return IMPL_TO_JSVAL(DOUBLE_TO_JSVAL_IMPL(d));
1812 * because GCC from XCode 3.1.4 miscompiles the above code. */
1813 jsval_layout l;
1814 if (JS_UNLIKELY(d != d)) {
1815 l.asBits = 0x7FF8000000000000LL;
1816 } else {
1817 l.asDouble = d;
1819 return IMPL_TO_JSVAL(l);
1822 static JS_ALWAYS_INLINE jsval
1823 UINT_TO_JSVAL(uint32_t i)
1825 if (i <= JSVAL_INT_MAX)
1826 return INT_TO_JSVAL((int32_t)i);
1827 return DOUBLE_TO_JSVAL((double)i);
1830 static JS_ALWAYS_INLINE JSBool
1831 JSVAL_IS_NUMBER(jsval v)
1833 return JSVAL_IS_NUMBER_IMPL(JSVAL_TO_IMPL(v));
1836 static JS_ALWAYS_INLINE JSBool
1837 JSVAL_IS_STRING(jsval v)
1839 return JSVAL_IS_STRING_IMPL(JSVAL_TO_IMPL(v));
1842 static JS_ALWAYS_INLINE JSString *
1843 JSVAL_TO_STRING(jsval v)
1845 JS_ASSERT(JSVAL_IS_STRING(v));
1846 return JSVAL_TO_STRING_IMPL(JSVAL_TO_IMPL(v));
1849 static JS_ALWAYS_INLINE jsval
1850 STRING_TO_JSVAL(JSString *str)
1852 return IMPL_TO_JSVAL(STRING_TO_JSVAL_IMPL(str));
1855 static JS_ALWAYS_INLINE JSBool
1856 JSVAL_IS_OBJECT(jsval v)
1858 return JSVAL_IS_OBJECT_OR_NULL_IMPL(JSVAL_TO_IMPL(v));
1861 static JS_ALWAYS_INLINE JSObject *
1862 JSVAL_TO_OBJECT(jsval v)
1864 JS_ASSERT(JSVAL_IS_OBJECT(v));
1865 return JSVAL_TO_OBJECT_IMPL(JSVAL_TO_IMPL(v));
1868 static JS_ALWAYS_INLINE jsval
1869 OBJECT_TO_JSVAL(JSObject *obj)
1871 if (obj)
1872 return IMPL_TO_JSVAL(OBJECT_TO_JSVAL_IMPL(obj));
1873 return JSVAL_NULL;
1876 static JS_ALWAYS_INLINE JSBool
1877 JSVAL_IS_BOOLEAN(jsval v)
1879 return JSVAL_IS_BOOLEAN_IMPL(JSVAL_TO_IMPL(v));
1882 static JS_ALWAYS_INLINE JSBool
1883 JSVAL_TO_BOOLEAN(jsval v)
1885 JS_ASSERT(JSVAL_IS_BOOLEAN(v));
1886 return JSVAL_TO_BOOLEAN_IMPL(JSVAL_TO_IMPL(v));
1889 static JS_ALWAYS_INLINE jsval
1890 BOOLEAN_TO_JSVAL(JSBool b)
1892 return IMPL_TO_JSVAL(BOOLEAN_TO_JSVAL_IMPL(b));
1895 static JS_ALWAYS_INLINE JSBool
1896 JSVAL_IS_PRIMITIVE(jsval v)
1898 return JSVAL_IS_PRIMITIVE_IMPL(JSVAL_TO_IMPL(v));
1901 static JS_ALWAYS_INLINE JSBool
1902 JSVAL_IS_GCTHING(jsval v)
1904 return JSVAL_IS_GCTHING_IMPL(JSVAL_TO_IMPL(v));
1907 static JS_ALWAYS_INLINE void *
1908 JSVAL_TO_GCTHING(jsval v)
1910 JS_ASSERT(JSVAL_IS_GCTHING(v));
1911 return JSVAL_TO_GCTHING_IMPL(JSVAL_TO_IMPL(v));
1914 /* To be GC-safe, privates are tagged as doubles. */
1916 static JS_ALWAYS_INLINE jsval
1917 PRIVATE_TO_JSVAL(void *ptr)
1919 return IMPL_TO_JSVAL(PRIVATE_PTR_TO_JSVAL_IMPL(ptr));
1922 static JS_ALWAYS_INLINE void *
1923 JSVAL_TO_PRIVATE(jsval v)
1925 JS_ASSERT(JSVAL_IS_DOUBLE(v));
1926 return JSVAL_TO_PRIVATE_PTR_IMPL(JSVAL_TO_IMPL(v));
1929 /************************************************************************/
1932 * A jsid is an identifier for a property or method of an object which is
1933 * either a 31-bit signed integer, interned string or object. If XML is
1934 * enabled, there is an additional singleton jsid value; see
1935 * JS_DEFAULT_XML_NAMESPACE_ID below. Finally, there is an additional jsid
1936 * value, JSID_VOID, which does not occur in JS scripts but may be used to
1937 * indicate the absence of a valid jsid.
1939 * A jsid is not implicitly convertible to or from a jsval; JS_ValueToId or
1940 * JS_IdToValue must be used instead.
1943 #define JSID_TYPE_STRING 0x0
1944 #define JSID_TYPE_INT 0x1
1945 #define JSID_TYPE_VOID 0x2
1946 #define JSID_TYPE_OBJECT 0x4
1947 #define JSID_TYPE_DEFAULT_XML_NAMESPACE 0x6
1948 #define JSID_TYPE_MASK 0x7
1951 * Avoid using canonical 'id' for jsid parameters since this is a magic word in
1952 * Objective-C++ which, apparently, wants to be able to #include jsapi.h.
1954 #define id iden
1956 static JS_ALWAYS_INLINE JSBool
1957 JSID_IS_STRING(jsid id)
1959 return (JSID_BITS(id) & JSID_TYPE_MASK) == 0;
1962 static JS_ALWAYS_INLINE JSString *
1963 JSID_TO_STRING(jsid id)
1965 JS_ASSERT(JSID_IS_STRING(id));
1966 return (JSString *)JSID_BITS(id);
1969 static JS_ALWAYS_INLINE JSBool
1970 JSID_IS_ZERO(jsid id)
1972 return JSID_BITS(id) == 0;
1975 JS_PUBLIC_API(JSBool)
1976 JS_StringHasBeenInterned(JSContext *cx, JSString *str);
1979 * Only JSStrings that have been interned via the JSAPI can be turned into
1980 * jsids by API clients.
1982 * N.B. if a jsid is backed by a string which has not been interned, that
1983 * string must be appropriately rooted to avoid being collected by the GC.
1985 JS_PUBLIC_API(jsid)
1986 INTERNED_STRING_TO_JSID(JSContext *cx, JSString *str);
1988 static JS_ALWAYS_INLINE JSBool
1989 JSID_IS_INT(jsid id)
1991 return !!(JSID_BITS(id) & JSID_TYPE_INT);
1994 static JS_ALWAYS_INLINE int32_t
1995 JSID_TO_INT(jsid id)
1997 JS_ASSERT(JSID_IS_INT(id));
1998 return ((uint32_t)JSID_BITS(id)) >> 1;
2001 #define JSID_INT_MIN 0
2002 #define JSID_INT_MAX INT32_MAX
2004 static JS_ALWAYS_INLINE JSBool
2005 INT_FITS_IN_JSID(int32_t i)
2007 return i >= 0;
2010 static JS_ALWAYS_INLINE jsid
2011 INT_TO_JSID(int32_t i)
2013 jsid id;
2014 JS_ASSERT(INT_FITS_IN_JSID(i));
2015 JSID_BITS(id) = ((i << 1) | JSID_TYPE_INT);
2016 return id;
2019 static JS_ALWAYS_INLINE JSBool
2020 JSID_IS_OBJECT(jsid id)
2022 return (JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_OBJECT &&
2023 (size_t)JSID_BITS(id) != JSID_TYPE_OBJECT;
2026 static JS_ALWAYS_INLINE JSObject *
2027 JSID_TO_OBJECT(jsid id)
2029 JS_ASSERT(JSID_IS_OBJECT(id));
2030 return (JSObject *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK);
2033 static JS_ALWAYS_INLINE jsid
2034 OBJECT_TO_JSID(JSObject *obj)
2036 jsid id;
2037 JS_ASSERT(obj != NULL);
2038 JS_ASSERT(((size_t)obj & JSID_TYPE_MASK) == 0);
2039 JSID_BITS(id) = ((size_t)obj | JSID_TYPE_OBJECT);
2040 return id;
2043 static JS_ALWAYS_INLINE JSBool
2044 JSID_IS_GCTHING(jsid id)
2046 return JSID_IS_STRING(id) || JSID_IS_OBJECT(id);
2049 static JS_ALWAYS_INLINE void *
2050 JSID_TO_GCTHING(jsid id)
2052 return (void *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK);
2056 * The magic XML namespace id is not a valid jsid. Global object classes in
2057 * embeddings that enable JS_HAS_XML_SUPPORT (E4X) should handle this id.
2060 static JS_ALWAYS_INLINE JSBool
2061 JSID_IS_DEFAULT_XML_NAMESPACE(jsid id)
2063 JS_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_DEFAULT_XML_NAMESPACE,
2064 JSID_BITS(id) == JSID_TYPE_DEFAULT_XML_NAMESPACE);
2065 return ((size_t)JSID_BITS(id) == JSID_TYPE_DEFAULT_XML_NAMESPACE);
2068 #ifdef JS_USE_JSID_STRUCT_TYPES
2069 extern JS_PUBLIC_DATA(jsid) JS_DEFAULT_XML_NAMESPACE_ID;
2070 #else
2071 # define JS_DEFAULT_XML_NAMESPACE_ID ((jsid)JSID_TYPE_DEFAULT_XML_NAMESPACE)
2072 #endif
2075 * A void jsid is not a valid id and only arises as an exceptional API return
2076 * value, such as in JS_NextProperty. Embeddings must not pass JSID_VOID into
2077 * JSAPI entry points expecting a jsid and do not need to handle JSID_VOID in
2078 * hooks receiving a jsid except when explicitly noted in the API contract.
2081 static JS_ALWAYS_INLINE JSBool
2082 JSID_IS_VOID(jsid id)
2084 JS_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_VOID,
2085 JSID_BITS(id) == JSID_TYPE_VOID);
2086 return ((size_t)JSID_BITS(id) == JSID_TYPE_VOID);
2089 static JS_ALWAYS_INLINE JSBool
2090 JSID_IS_EMPTY(jsid id)
2092 return ((size_t)JSID_BITS(id) == JSID_TYPE_OBJECT);
2095 #undef id
2097 #ifdef JS_USE_JSID_STRUCT_TYPES
2098 extern JS_PUBLIC_DATA(jsid) JSID_VOID;
2099 extern JS_PUBLIC_DATA(jsid) JSID_EMPTY;
2100 #else
2101 # define JSID_VOID ((jsid)JSID_TYPE_VOID)
2102 # define JSID_EMPTY ((jsid)JSID_TYPE_OBJECT)
2103 #endif
2106 * Returns true iff the given jsval is immune to GC and can be used across
2107 * multiple JSRuntimes without requiring any conversion API.
2109 static JS_ALWAYS_INLINE JSBool
2110 JSVAL_IS_UNIVERSAL(jsval v)
2112 return !JSVAL_IS_GCTHING(v);
2115 #ifdef __cplusplus
2117 namespace JS {
2119 class AutoIdRooter : private AutoGCRooter
2121 public:
2122 explicit AutoIdRooter(JSContext *cx, jsid id = INT_TO_JSID(0)
2123 JS_GUARD_OBJECT_NOTIFIER_PARAM)
2124 : AutoGCRooter(cx, ID), id_(id)
2126 JS_GUARD_OBJECT_NOTIFIER_INIT;
2129 jsid id() {
2130 return id_;
2133 jsid * addr() {
2134 return &id_;
2137 friend void AutoGCRooter::trace(JSTracer *trc);
2139 private:
2140 jsid id_;
2141 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
2144 } /* namespace JS */
2146 #endif /* __cplusplus */
2148 /************************************************************************/
2150 /* Lock and unlock the GC thing held by a jsval. */
2151 #define JSVAL_LOCK(cx,v) (JSVAL_IS_GCTHING(v) \
2152 ? JS_LockGCThing(cx, JSVAL_TO_GCTHING(v)) \
2153 : JS_TRUE)
2154 #define JSVAL_UNLOCK(cx,v) (JSVAL_IS_GCTHING(v) \
2155 ? JS_UnlockGCThing(cx, JSVAL_TO_GCTHING(v)) \
2156 : JS_TRUE)
2158 /* Property attributes, set in JSPropertySpec and passed to API functions. */
2159 #define JSPROP_ENUMERATE 0x01 /* property is visible to for/in loop */
2160 #define JSPROP_READONLY 0x02 /* not settable: assignment is no-op.
2161 This flag is only valid when neither
2162 JSPROP_GETTER nor JSPROP_SETTER is
2163 set. */
2164 #define JSPROP_PERMANENT 0x04 /* property cannot be deleted */
2165 #define JSPROP_GETTER 0x10 /* property holds getter function */
2166 #define JSPROP_SETTER 0x20 /* property holds setter function */
2167 #define JSPROP_SHARED 0x40 /* don't allocate a value slot for this
2168 property; don't copy the property on
2169 set of the same-named property in an
2170 object that delegates to a prototype
2171 containing this property */
2172 #define JSPROP_INDEX 0x80 /* name is actually (int) index */
2173 #define JSPROP_SHORTID 0x100 /* set in JS_DefineProperty attrs
2174 if getters/setters use a shortid */
2175 #define JSPROP_NATIVE_ACCESSORS 0x08 /* set in JSPropertyDescriptor.flags
2176 if getters/setters are JSNatives */
2178 /* Function flags, internal use only, returned by JS_GetFunctionFlags. */
2179 #define JSFUN_LAMBDA 0x08 /* expressed, not declared, function */
2180 #define JSFUN_HEAVYWEIGHT 0x80 /* activation requires a Call object */
2182 #define JSFUN_HEAVYWEIGHT_TEST(f) ((f) & JSFUN_HEAVYWEIGHT)
2184 /* 0x0100 is unused */
2185 #define JSFUN_CONSTRUCTOR 0x0200 /* native that can be called as a ctor
2186 without creating a this object */
2188 #define JSFUN_FLAGS_MASK 0x07f8 /* overlay JSFUN_* attributes --
2189 bits 12-15 are used internally to
2190 flag interpreted functions */
2192 #define JSFUN_STUB_GSOPS 0x1000 /* use JS_PropertyStub getter/setter
2193 instead of defaulting to class gsops
2194 for property holding function */
2197 * Re-use JSFUN_LAMBDA, which applies only to scripted functions, for use in
2198 * JSFunctionSpec arrays that specify generic native prototype methods, i.e.,
2199 * methods of a class prototype that are exposed as static methods taking an
2200 * extra leading argument: the generic |this| parameter.
2202 * If you set this flag in a JSFunctionSpec struct's flags initializer, then
2203 * that struct must live at least as long as the native static method object
2204 * created due to this flag by JS_DefineFunctions or JS_InitClass. Typically
2205 * JSFunctionSpec structs are allocated in static arrays.
2207 #define JSFUN_GENERIC_NATIVE JSFUN_LAMBDA
2210 * The first call to JS_CallOnce by any thread in a process will call 'func'.
2211 * Later calls to JS_CallOnce with the same JSCallOnceType object will be
2212 * suppressed.
2214 * Equivalently: each distinct JSCallOnceType object will allow one JS_CallOnce
2215 * to invoke its JSInitCallback.
2217 extern JS_PUBLIC_API(JSBool)
2218 JS_CallOnce(JSCallOnceType *once, JSInitCallback func);
2220 /* Microseconds since the epoch, midnight, January 1, 1970 UTC. */
2221 extern JS_PUBLIC_API(int64_t)
2222 JS_Now(void);
2224 /* Don't want to export data, so provide accessors for non-inline jsvals. */
2225 extern JS_PUBLIC_API(jsval)
2226 JS_GetNaNValue(JSContext *cx);
2228 extern JS_PUBLIC_API(jsval)
2229 JS_GetNegativeInfinityValue(JSContext *cx);
2231 extern JS_PUBLIC_API(jsval)
2232 JS_GetPositiveInfinityValue(JSContext *cx);
2234 extern JS_PUBLIC_API(jsval)
2235 JS_GetEmptyStringValue(JSContext *cx);
2237 extern JS_PUBLIC_API(JSString *)
2238 JS_GetEmptyString(JSRuntime *rt);
2241 * Format is a string of the following characters (spaces are insignificant),
2242 * specifying the tabulated type conversions:
2244 * b JSBool Boolean
2245 * c uint16_t/jschar ECMA uint16_t, Unicode char
2246 * i int32_t ECMA int32_t
2247 * u uint32_t ECMA uint32_t
2248 * j int32_t Rounded int32_t (coordinate)
2249 * d double IEEE double
2250 * I double Integral IEEE double
2251 * S JSString * Unicode string, accessed by a JSString pointer
2252 * W jschar * Unicode character vector, 0-terminated (W for wide)
2253 * o JSObject * Object reference
2254 * f JSFunction * Function private
2255 * v jsval Argument value (no conversion)
2256 * * N/A Skip this argument (no vararg)
2257 * / N/A End of required arguments
2259 * The variable argument list after format must consist of &b, &c, &s, e.g.,
2260 * where those variables have the types given above. For the pointer types
2261 * char *, JSString *, and JSObject *, the pointed-at memory returned belongs
2262 * to the JS runtime, not to the calling native code. The runtime promises
2263 * to keep this memory valid so long as argv refers to allocated stack space
2264 * (so long as the native function is active).
2266 * Fewer arguments than format specifies may be passed only if there is a /
2267 * in format after the last required argument specifier and argc is at least
2268 * the number of required arguments. More arguments than format specifies
2269 * may be passed without error; it is up to the caller to deal with trailing
2270 * unconverted arguments.
2272 extern JS_PUBLIC_API(JSBool)
2273 JS_ConvertArguments(JSContext *cx, unsigned argc, jsval *argv, const char *format,
2274 ...);
2276 #ifdef va_start
2277 extern JS_PUBLIC_API(JSBool)
2278 JS_ConvertArgumentsVA(JSContext *cx, unsigned argc, jsval *argv,
2279 const char *format, va_list ap);
2280 #endif
2282 #ifdef JS_ARGUMENT_FORMATTER_DEFINED
2285 * Add and remove a format string handler for JS_{Convert,Push}Arguments{,VA}.
2286 * The handler function has this signature:
2288 * JSBool MyArgumentFormatter(JSContext *cx, const char *format,
2289 * JSBool fromJS, jsval **vpp, va_list *app);
2291 * It should return true on success, and return false after reporting an error
2292 * or detecting an already-reported error.
2294 * For a given format string, for example "AA", the formatter is called from
2295 * JS_ConvertArgumentsVA like so:
2297 * formatter(cx, "AA...", JS_TRUE, &sp, &ap);
2299 * sp points into the arguments array on the JS stack, while ap points into
2300 * the stdarg.h va_list on the C stack. The JS_TRUE passed for fromJS tells
2301 * the formatter to convert zero or more jsvals at sp to zero or more C values
2302 * accessed via pointers-to-values at ap, updating both sp (via *vpp) and ap
2303 * (via *app) to point past the converted arguments and their result pointers
2304 * on the C stack.
2306 * When called from JS_PushArgumentsVA, the formatter is invoked thus:
2308 * formatter(cx, "AA...", JS_FALSE, &sp, &ap);
2310 * where JS_FALSE for fromJS means to wrap the C values at ap according to the
2311 * format specifier and store them at sp, updating ap and sp appropriately.
2313 * The "..." after "AA" is the rest of the format string that was passed into
2314 * JS_{Convert,Push}Arguments{,VA}. The actual format trailing substring used
2315 * in each Convert or PushArguments call is passed to the formatter, so that
2316 * one such function may implement several formats, in order to share code.
2318 * Remove just forgets about any handler associated with format. Add does not
2319 * copy format, it points at the string storage allocated by the caller, which
2320 * is typically a string constant. If format is in dynamic storage, it is up
2321 * to the caller to keep the string alive until Remove is called.
2323 extern JS_PUBLIC_API(JSBool)
2324 JS_AddArgumentFormatter(JSContext *cx, const char *format,
2325 JSArgumentFormatter formatter);
2327 extern JS_PUBLIC_API(void)
2328 JS_RemoveArgumentFormatter(JSContext *cx, const char *format);
2330 #endif /* JS_ARGUMENT_FORMATTER_DEFINED */
2332 extern JS_PUBLIC_API(JSBool)
2333 JS_ConvertValue(JSContext *cx, jsval v, JSType type, jsval *vp);
2335 extern JS_PUBLIC_API(JSBool)
2336 JS_ValueToObject(JSContext *cx, jsval v, JSObject **objp);
2338 extern JS_PUBLIC_API(JSFunction *)
2339 JS_ValueToFunction(JSContext *cx, jsval v);
2341 extern JS_PUBLIC_API(JSFunction *)
2342 JS_ValueToConstructor(JSContext *cx, jsval v);
2344 extern JS_PUBLIC_API(JSString *)
2345 JS_ValueToString(JSContext *cx, jsval v);
2347 extern JS_PUBLIC_API(JSString *)
2348 JS_ValueToSource(JSContext *cx, jsval v);
2350 extern JS_PUBLIC_API(JSBool)
2351 JS_ValueToNumber(JSContext *cx, jsval v, double *dp);
2353 #ifdef __cplusplus
2354 namespace js {
2356 * DO NOT CALL THIS. Use JS::ToNumber
2358 extern JS_PUBLIC_API(bool)
2359 ToNumberSlow(JSContext *cx, JS::Value v, double *dp);
2360 } /* namespace js */
2362 namespace JS {
2364 /* ES5 9.3 ToNumber. */
2365 JS_ALWAYS_INLINE bool
2366 ToNumber(JSContext *cx, const Value &v, double *out)
2368 AssertArgumentsAreSane(cx, v);
2370 if (v.isNumber()) {
2371 *out = v.toNumber();
2372 MaybeCheckStackRoots(cx);
2373 return true;
2375 return js::ToNumberSlow(cx, v, out);
2378 } /* namespace JS */
2379 #endif /* __cplusplus */
2381 extern JS_PUBLIC_API(JSBool)
2382 JS_DoubleIsInt32(double d, int32_t *ip);
2384 extern JS_PUBLIC_API(int32_t)
2385 JS_DoubleToInt32(double d);
2387 extern JS_PUBLIC_API(uint32_t)
2388 JS_DoubleToUint32(double d);
2391 * Convert a value to a number, then to an int32_t, according to the ECMA rules
2392 * for ToInt32.
2394 extern JS_PUBLIC_API(JSBool)
2395 JS_ValueToECMAInt32(JSContext *cx, jsval v, int32_t *ip);
2397 #ifdef __cplusplus
2398 namespace js {
2400 * DO NOT CALL THIS. Use JS::ToInt32
2402 extern JS_PUBLIC_API(bool)
2403 ToInt32Slow(JSContext *cx, const JS::Value &v, int32_t *out);
2404 } /* namespace js */
2406 namespace JS {
2408 JS_ALWAYS_INLINE bool
2409 ToInt32(JSContext *cx, const js::Value &v, int32_t *out)
2411 AssertArgumentsAreSane(cx, v);
2412 if (v.isInt32()) {
2413 *out = v.toInt32();
2414 return true;
2416 return js::ToInt32Slow(cx, v, out);
2419 } /* namespace JS */
2420 #endif /* __cplusplus */
2423 * Convert a value to a number, then to a uint32_t, according to the ECMA rules
2424 * for ToUint32.
2426 extern JS_PUBLIC_API(JSBool)
2427 JS_ValueToECMAUint32(JSContext *cx, jsval v, uint32_t *ip);
2430 * Convert a value to a number, then to an int32_t if it fits by rounding to
2431 * nearest; but failing with an error report if the double is out of range
2432 * or unordered.
2434 extern JS_PUBLIC_API(JSBool)
2435 JS_ValueToInt32(JSContext *cx, jsval v, int32_t *ip);
2438 * ECMA ToUint16, for mapping a jsval to a Unicode point.
2440 extern JS_PUBLIC_API(JSBool)
2441 JS_ValueToUint16(JSContext *cx, jsval v, uint16_t *ip);
2443 extern JS_PUBLIC_API(JSBool)
2444 JS_ValueToBoolean(JSContext *cx, jsval v, JSBool *bp);
2446 extern JS_PUBLIC_API(JSType)
2447 JS_TypeOfValue(JSContext *cx, jsval v);
2449 extern JS_PUBLIC_API(const char *)
2450 JS_GetTypeName(JSContext *cx, JSType type);
2452 extern JS_PUBLIC_API(JSBool)
2453 JS_StrictlyEqual(JSContext *cx, jsval v1, jsval v2, JSBool *equal);
2455 extern JS_PUBLIC_API(JSBool)
2456 JS_LooselyEqual(JSContext *cx, jsval v1, jsval v2, JSBool *equal);
2458 extern JS_PUBLIC_API(JSBool)
2459 JS_SameValue(JSContext *cx, jsval v1, jsval v2, JSBool *same);
2461 /* True iff fun is the global eval function. */
2462 extern JS_PUBLIC_API(JSBool)
2463 JS_IsBuiltinEvalFunction(JSFunction *fun);
2465 /* True iff fun is the Function constructor. */
2466 extern JS_PUBLIC_API(JSBool)
2467 JS_IsBuiltinFunctionConstructor(JSFunction *fun);
2469 /************************************************************************/
2472 * Initialization, locking, contexts, and memory allocation.
2474 * It is important that the first runtime and first context be created in a
2475 * single-threaded fashion, otherwise the behavior of the library is undefined.
2476 * See: http://developer.mozilla.org/en/docs/Category:JSAPI_Reference
2478 #define JS_NewRuntime JS_Init
2479 #define JS_DestroyRuntime JS_Finish
2480 #define JS_LockRuntime JS_Lock
2481 #define JS_UnlockRuntime JS_Unlock
2483 extern JS_PUBLIC_API(JSRuntime *)
2484 JS_NewRuntime(uint32_t maxbytes);
2486 /* Deprecated. */
2487 #define JS_CommenceRuntimeShutDown(rt) ((void) 0)
2489 extern JS_PUBLIC_API(void)
2490 JS_DestroyRuntime(JSRuntime *rt);
2492 extern JS_PUBLIC_API(void)
2493 JS_ShutDown(void);
2495 JS_PUBLIC_API(void *)
2496 JS_GetRuntimePrivate(JSRuntime *rt);
2498 extern JS_PUBLIC_API(JSRuntime *)
2499 JS_GetRuntime(JSContext *cx);
2501 JS_PUBLIC_API(void)
2502 JS_SetRuntimePrivate(JSRuntime *rt, void *data);
2504 extern JS_PUBLIC_API(void)
2505 JS_BeginRequest(JSContext *cx);
2507 extern JS_PUBLIC_API(void)
2508 JS_EndRequest(JSContext *cx);
2510 /* Yield to pending GC operations, regardless of request depth */
2511 extern JS_PUBLIC_API(void)
2512 JS_YieldRequest(JSContext *cx);
2514 extern JS_PUBLIC_API(unsigned)
2515 JS_SuspendRequest(JSContext *cx);
2517 extern JS_PUBLIC_API(void)
2518 JS_ResumeRequest(JSContext *cx, unsigned saveDepth);
2520 extern JS_PUBLIC_API(JSBool)
2521 JS_IsInRequest(JSRuntime *rt);
2523 extern JS_PUBLIC_API(JSBool)
2524 JS_IsInSuspendedRequest(JSRuntime *rt);
2526 #ifdef __cplusplus
2527 JS_END_EXTERN_C
2529 namespace JS {
2531 inline bool
2532 IsPoisonedId(jsid iden)
2534 if (JSID_IS_STRING(iden))
2535 return JS::IsPoisonedPtr(JSID_TO_STRING(iden));
2536 if (JSID_IS_OBJECT(iden))
2537 return JS::IsPoisonedPtr(JSID_TO_OBJECT(iden));
2538 return false;
2541 template <> struct RootMethods<const jsid>
2543 static jsid initial() { return JSID_VOID; }
2544 static ThingRootKind kind() { return THING_ROOT_ID; }
2545 static bool poisoned(jsid id) { return IsPoisonedId(id); }
2548 template <> struct RootMethods<jsid>
2550 static jsid initial() { return JSID_VOID; }
2551 static ThingRootKind kind() { return THING_ROOT_ID; }
2552 static bool poisoned(jsid id) { return IsPoisonedId(id); }
2555 } /* namespace JS */
2557 class JSAutoRequest {
2558 public:
2559 JSAutoRequest(JSContext *cx JS_GUARD_OBJECT_NOTIFIER_PARAM)
2560 : mContext(cx), mSaveDepth(0) {
2561 JS_GUARD_OBJECT_NOTIFIER_INIT;
2562 JS_BeginRequest(mContext);
2564 ~JSAutoRequest() {
2565 JS_EndRequest(mContext);
2568 void suspend() {
2569 mSaveDepth = JS_SuspendRequest(mContext);
2571 void resume() {
2572 JS_ResumeRequest(mContext, mSaveDepth);
2575 protected:
2576 JSContext *mContext;
2577 unsigned mSaveDepth;
2578 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
2580 #if 0
2581 private:
2582 static void *operator new(size_t) CPP_THROW_NEW { return 0; };
2583 static void operator delete(void *, size_t) { };
2584 #endif
2587 class JSAutoSuspendRequest {
2588 public:
2589 JSAutoSuspendRequest(JSContext *cx JS_GUARD_OBJECT_NOTIFIER_PARAM)
2590 : mContext(cx), mSaveDepth(0) {
2591 JS_GUARD_OBJECT_NOTIFIER_INIT;
2592 if (mContext) {
2593 mSaveDepth = JS_SuspendRequest(mContext);
2596 ~JSAutoSuspendRequest() {
2597 resume();
2600 void resume() {
2601 if (mContext) {
2602 JS_ResumeRequest(mContext, mSaveDepth);
2603 mContext = 0;
2607 protected:
2608 JSContext *mContext;
2609 unsigned mSaveDepth;
2610 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
2612 #if 0
2613 private:
2614 static void *operator new(size_t) CPP_THROW_NEW { return 0; };
2615 static void operator delete(void *, size_t) { };
2616 #endif
2619 class JSAutoCheckRequest {
2620 public:
2621 JSAutoCheckRequest(JSContext *cx JS_GUARD_OBJECT_NOTIFIER_PARAM) {
2622 #if defined JS_THREADSAFE && defined DEBUG
2623 mContext = cx;
2624 JS_ASSERT(JS_IsInRequest(JS_GetRuntime(cx)));
2625 #endif
2626 JS_GUARD_OBJECT_NOTIFIER_INIT;
2629 ~JSAutoCheckRequest() {
2630 #if defined JS_THREADSAFE && defined DEBUG
2631 JS_ASSERT(JS_IsInRequest(JS_GetRuntime(mContext)));
2632 #endif
2636 private:
2637 #if defined JS_THREADSAFE && defined DEBUG
2638 JSContext *mContext;
2639 #endif
2640 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
2643 JS_BEGIN_EXTERN_C
2644 #endif
2646 extern JS_PUBLIC_API(JSContextCallback)
2647 JS_SetContextCallback(JSRuntime *rt, JSContextCallback cxCallback);
2649 extern JS_PUBLIC_API(JSContext *)
2650 JS_NewContext(JSRuntime *rt, size_t stackChunkSize);
2652 extern JS_PUBLIC_API(void)
2653 JS_DestroyContext(JSContext *cx);
2655 extern JS_PUBLIC_API(void)
2656 JS_DestroyContextNoGC(JSContext *cx);
2658 extern JS_PUBLIC_API(void *)
2659 JS_GetContextPrivate(JSContext *cx);
2661 extern JS_PUBLIC_API(void)
2662 JS_SetContextPrivate(JSContext *cx, void *data);
2664 extern JS_PUBLIC_API(void *)
2665 JS_GetSecondContextPrivate(JSContext *cx);
2667 extern JS_PUBLIC_API(void)
2668 JS_SetSecondContextPrivate(JSContext *cx, void *data);
2670 extern JS_PUBLIC_API(JSRuntime *)
2671 JS_GetRuntime(JSContext *cx);
2673 extern JS_PUBLIC_API(JSContext *)
2674 JS_ContextIterator(JSRuntime *rt, JSContext **iterp);
2676 extern JS_PUBLIC_API(JSVersion)
2677 JS_GetVersion(JSContext *cx);
2679 extern JS_PUBLIC_API(JSVersion)
2680 JS_SetVersion(JSContext *cx, JSVersion version);
2682 extern JS_PUBLIC_API(const char *)
2683 JS_VersionToString(JSVersion version);
2685 extern JS_PUBLIC_API(JSVersion)
2686 JS_StringToVersion(const char *string);
2689 * JS options are orthogonal to version, and may be freely composed with one
2690 * another as well as with version.
2692 * JSOPTION_VAROBJFIX is recommended -- see the comments associated with the
2693 * prototypes for JS_ExecuteScript, JS_EvaluateScript, etc.
2695 #define JSOPTION_STRICT JS_BIT(0) /* warn on dubious practice */
2696 #define JSOPTION_WERROR JS_BIT(1) /* convert warning to error */
2697 #define JSOPTION_VAROBJFIX JS_BIT(2) /* make JS_EvaluateScript use
2698 the last object on its 'obj'
2699 param's scope chain as the
2700 ECMA 'variables object' */
2701 #define JSOPTION_PRIVATE_IS_NSISUPPORTS \
2702 JS_BIT(3) /* context private data points
2703 to an nsISupports subclass */
2704 #define JSOPTION_COMPILE_N_GO JS_BIT(4) /* caller of JS_Compile*Script
2705 promises to execute compiled
2706 script once only; enables
2707 compile-time scope chain
2708 resolution of consts. */
2709 #define JSOPTION_ATLINE JS_BIT(5) /* //@line number ["filename"]
2710 option supported for the
2711 XUL preprocessor and kindred
2712 beasts. */
2713 #define JSOPTION_XML JS_BIT(6) /* EMCAScript for XML support:
2714 parse <!-- --> as a token,
2715 not backward compatible with
2716 the comment-hiding hack used
2717 in HTML script tags. */
2718 #define JSOPTION_DONT_REPORT_UNCAUGHT \
2719 JS_BIT(8) /* When returning from the
2720 outermost API call, prevent
2721 uncaught exceptions from
2722 being converted to error
2723 reports */
2725 #define JSOPTION_RELIMIT JS_BIT(9) /* Throw exception on any
2726 regular expression which
2727 backtracks more than n^3
2728 times, where n is length
2729 of the input string */
2730 /* JS_BIT(10) is currently unused. */
2732 /* JS_BIT(11) is currently unused. */
2734 #define JSOPTION_NO_SCRIPT_RVAL JS_BIT(12) /* A promise to the compiler
2735 that a null rval out-param
2736 will be passed to each call
2737 to JS_ExecuteScript. */
2738 #define JSOPTION_UNROOTED_GLOBAL JS_BIT(13) /* The GC will not root the
2739 contexts' global objects
2740 (see JS_GetGlobalObject),
2741 leaving that up to the
2742 embedding. */
2744 #define JSOPTION_METHODJIT JS_BIT(14) /* Whole-method JIT. */
2746 /* JS_BIT(15) is currently unused. */
2748 #define JSOPTION_METHODJIT_ALWAYS \
2749 JS_BIT(16) /* Always whole-method JIT,
2750 don't tune at run-time. */
2751 #define JSOPTION_PCCOUNT JS_BIT(17) /* Collect per-op execution counts */
2753 #define JSOPTION_TYPE_INFERENCE JS_BIT(18) /* Perform type inference. */
2754 #define JSOPTION_STRICT_MODE JS_BIT(19) /* Provides a way to force
2755 strict mode for all code
2756 without requiring
2757 "use strict" annotations. */
2759 /* Options which reflect compile-time properties of scripts. */
2760 #define JSCOMPILEOPTION_MASK (JSOPTION_XML)
2762 #define JSRUNOPTION_MASK (JS_BITMASK(20) & ~JSCOMPILEOPTION_MASK)
2763 #define JSALLOPTION_MASK (JSCOMPILEOPTION_MASK | JSRUNOPTION_MASK)
2765 extern JS_PUBLIC_API(uint32_t)
2766 JS_GetOptions(JSContext *cx);
2768 extern JS_PUBLIC_API(uint32_t)
2769 JS_SetOptions(JSContext *cx, uint32_t options);
2771 extern JS_PUBLIC_API(uint32_t)
2772 JS_ToggleOptions(JSContext *cx, uint32_t options);
2774 extern JS_PUBLIC_API(void)
2775 JS_SetJitHardening(JSRuntime *rt, JSBool enabled);
2777 extern JS_PUBLIC_API(const char *)
2778 JS_GetImplementationVersion(void);
2780 extern JS_PUBLIC_API(void)
2781 JS_SetDestroyCompartmentCallback(JSRuntime *rt, JSDestroyCompartmentCallback callback);
2783 extern JS_PUBLIC_API(JSWrapObjectCallback)
2784 JS_SetWrapObjectCallbacks(JSRuntime *rt,
2785 JSWrapObjectCallback callback,
2786 JSPreWrapCallback precallback);
2788 extern JS_PUBLIC_API(JSCrossCompartmentCall *)
2789 JS_EnterCrossCompartmentCall(JSContext *cx, JSObject *target);
2791 extern JS_PUBLIC_API(void)
2792 JS_LeaveCrossCompartmentCall(JSCrossCompartmentCall *call);
2794 extern JS_PUBLIC_API(void)
2795 JS_SetCompartmentPrivate(JSCompartment *compartment, void *data);
2797 extern JS_PUBLIC_API(void *)
2798 JS_GetCompartmentPrivate(JSCompartment *compartment);
2800 extern JS_PUBLIC_API(JSBool)
2801 JS_WrapObject(JSContext *cx, JSObject **objp);
2803 extern JS_PUBLIC_API(JSBool)
2804 JS_WrapValue(JSContext *cx, jsval *vp);
2806 extern JS_PUBLIC_API(JSObject *)
2807 JS_TransplantObject(JSContext *cx, JSObject *origobj, JSObject *target);
2809 extern JS_FRIEND_API(JSObject *)
2810 js_TransplantObjectWithWrapper(JSContext *cx,
2811 JSObject *origobj,
2812 JSObject *origwrapper,
2813 JSObject *targetobj,
2814 JSObject *targetwrapper);
2816 extern JS_FRIEND_API(JSObject *)
2817 js_TransplantObjectWithWrapper(JSContext *cx,
2818 JSObject *origobj,
2819 JSObject *origwrapper,
2820 JSObject *targetobj,
2821 JSObject *targetwrapper);
2823 #ifdef __cplusplus
2824 JS_END_EXTERN_C
2826 namespace js {
2827 class AutoCompartment;
2830 class JS_PUBLIC_API(JSAutoEnterCompartment)
2833 * This is a poor man's Maybe<AutoCompartment>, because we don't have
2834 * access to the AutoCompartment definition here. We statically assert in
2835 * jsapi.cpp that we have the right size here.
2837 * In practice, 32-bit Windows and Android get 16-word |bytes|, while
2838 * other platforms get 13-word |bytes|.
2840 void* bytes[sizeof(void*) == 4 && MOZ_ALIGNOF(uint64_t) == 8 ? 16 : 13];
2842 protected:
2843 js::AutoCompartment *getAutoCompartment() {
2844 JS_ASSERT(state == STATE_OTHER_COMPARTMENT);
2845 return reinterpret_cast<js::AutoCompartment*>(bytes);
2849 * This object may be in one of three states. If enter() or
2850 * enterAndIgnoreErrors() hasn't been called, it's in STATE_UNENTERED.
2851 * Otherwise, if we were asked to enter into the current compartment, our
2852 * state is STATE_SAME_COMPARTMENT. If we actually created an
2853 * AutoCompartment and entered another compartment, our state is
2854 * STATE_OTHER_COMPARTMENT.
2856 enum State {
2857 STATE_UNENTERED,
2858 STATE_SAME_COMPARTMENT,
2859 STATE_OTHER_COMPARTMENT
2860 } state;
2862 public:
2863 JSAutoEnterCompartment() : state(STATE_UNENTERED) {}
2865 bool enter(JSContext *cx, JSObject *target);
2867 void enterAndIgnoreErrors(JSContext *cx, JSObject *target);
2869 bool entered() const { return state != STATE_UNENTERED; }
2871 ~JSAutoEnterCompartment();
2874 JS_BEGIN_EXTERN_C
2875 #endif
2877 typedef void (*JSIterateCompartmentCallback)(JSRuntime *rt, void *data, JSCompartment *compartment);
2880 * This function calls |compartmentCallback| on every compartment. Beware that
2881 * there is no guarantee that the compartment will survive after the callback
2882 * returns.
2884 extern JS_PUBLIC_API(void)
2885 JS_IterateCompartments(JSRuntime *rt, void *data,
2886 JSIterateCompartmentCallback compartmentCallback);
2888 extern JS_PUBLIC_API(JSObject *)
2889 JS_GetGlobalObject(JSContext *cx);
2891 extern JS_PUBLIC_API(void)
2892 JS_SetGlobalObject(JSContext *cx, JSObject *obj);
2895 * Initialize standard JS class constructors, prototypes, and any top-level
2896 * functions and constants associated with the standard classes (e.g. isNaN
2897 * for Number).
2899 * NB: This sets cx's global object to obj if it was null.
2901 extern JS_PUBLIC_API(JSBool)
2902 JS_InitStandardClasses(JSContext *cx, JSObject *obj);
2905 * Resolve id, which must contain either a string or an int, to a standard
2906 * class name in obj if possible, defining the class's constructor and/or
2907 * prototype and storing true in *resolved. If id does not name a standard
2908 * class or a top-level property induced by initializing a standard class,
2909 * store false in *resolved and just return true. Return false on error,
2910 * as usual for JSBool result-typed API entry points.
2912 * This API can be called directly from a global object class's resolve op,
2913 * to define standard classes lazily. The class's enumerate op should call
2914 * JS_EnumerateStandardClasses(cx, obj), to define eagerly during for..in
2915 * loops any classes not yet resolved lazily.
2917 extern JS_PUBLIC_API(JSBool)
2918 JS_ResolveStandardClass(JSContext *cx, JSObject *obj, jsid id,
2919 JSBool *resolved);
2921 extern JS_PUBLIC_API(JSBool)
2922 JS_EnumerateStandardClasses(JSContext *cx, JSObject *obj);
2925 * Enumerate any already-resolved standard class ids into ida, or into a new
2926 * JSIdArray if ida is null. Return the augmented array on success, null on
2927 * failure with ida (if it was non-null on entry) destroyed.
2929 extern JS_PUBLIC_API(JSIdArray *)
2930 JS_EnumerateResolvedStandardClasses(JSContext *cx, JSObject *obj,
2931 JSIdArray *ida);
2933 extern JS_PUBLIC_API(JSBool)
2934 JS_GetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key,
2935 JSObject **objp);
2938 * Returns the original value of |Function.prototype| from the global object in
2939 * which |forObj| was created.
2941 extern JS_PUBLIC_API(JSObject *)
2942 JS_GetFunctionPrototype(JSContext *cx, JSObject *forObj);
2945 * Returns the original value of |Object.prototype| from the global object in
2946 * which |forObj| was created.
2948 extern JS_PUBLIC_API(JSObject *)
2949 JS_GetObjectPrototype(JSContext *cx, JSObject *forObj);
2951 extern JS_PUBLIC_API(JSObject *)
2952 JS_GetGlobalForObject(JSContext *cx, JSObject *obj);
2954 extern JS_PUBLIC_API(JSObject *)
2955 JS_GetGlobalForScopeChain(JSContext *cx);
2957 extern JS_PUBLIC_API(JSObject *)
2958 JS_GetScriptedGlobal(JSContext *cx);
2961 * Initialize the 'Reflect' object on a global object.
2963 extern JS_PUBLIC_API(JSObject *)
2964 JS_InitReflect(JSContext *cx, JSObject *global);
2966 #ifdef JS_HAS_CTYPES
2968 * Initialize the 'ctypes' object on a global variable 'obj'. The 'ctypes'
2969 * object will be sealed.
2971 extern JS_PUBLIC_API(JSBool)
2972 JS_InitCTypesClass(JSContext *cx, JSObject *global);
2975 * Convert a unicode string 'source' of length 'slen' to the platform native
2976 * charset, returning a null-terminated string allocated with JS_malloc. On
2977 * failure, this function should report an error.
2979 typedef char *
2980 (* JSCTypesUnicodeToNativeFun)(JSContext *cx, const jschar *source, size_t slen);
2983 * Set of function pointers that ctypes can use for various internal functions.
2984 * See JS_SetCTypesCallbacks below. Providing NULL for a function is safe,
2985 * and will result in the applicable ctypes functionality not being available.
2987 struct JSCTypesCallbacks {
2988 JSCTypesUnicodeToNativeFun unicodeToNative;
2991 typedef struct JSCTypesCallbacks JSCTypesCallbacks;
2994 * Set the callbacks on the provided 'ctypesObj' object. 'callbacks' should be a
2995 * pointer to static data that exists for the lifetime of 'ctypesObj', but it
2996 * may safely be altered after calling this function and without having
2997 * to call this function again.
2999 extern JS_PUBLIC_API(void)
3000 JS_SetCTypesCallbacks(JSObject *ctypesObj, JSCTypesCallbacks *callbacks);
3001 #endif
3003 typedef JSBool
3004 (* JSEnumerateDiagnosticMemoryCallback)(void *ptr, size_t length);
3007 * Enumerate memory regions that contain diagnostic information
3008 * intended to be included in crash report minidumps.
3010 extern JS_PUBLIC_API(void)
3011 JS_EnumerateDiagnosticMemoryRegions(JSEnumerateDiagnosticMemoryCallback callback);
3014 * Macros to hide interpreter stack layout details from a JSFastNative using
3015 * its jsval *vp parameter. The stack layout underlying invocation can't change
3016 * without breaking source and binary compatibility (argv[-2] is well-known to
3017 * be the callee jsval, and argv[-1] is as well known to be |this|).
3019 * Note well: However, argv[-1] may be JSVAL_NULL where with slow natives it
3020 * is the global object, so embeddings implementing fast natives *must* call
3021 * JS_THIS or JS_THIS_OBJECT and test for failure indicated by a null return,
3022 * which should propagate as a false return from native functions and hooks.
3024 * To reduce boilerplace checks, JS_InstanceOf and JS_GetInstancePrivate now
3025 * handle a null obj parameter by returning false (throwing a TypeError if
3026 * given non-null argv), so most native functions that type-check their |this|
3027 * parameter need not add null checking.
3029 * NB: there is an anti-dependency between JS_CALLEE and JS_SET_RVAL: native
3030 * methods that may inspect their callee must defer setting their return value
3031 * until after any such possible inspection. Otherwise the return value will be
3032 * inspected instead of the callee function object.
3034 * WARNING: These are not (yet) mandatory macros, but new code outside of the
3035 * engine should use them. In the Mozilla 2.0 milestone their definitions may
3036 * change incompatibly.
3038 * N.B. constructors must not use JS_THIS, as no 'this' object has been created.
3041 #define JS_CALLEE(cx,vp) ((vp)[0])
3042 #define JS_THIS(cx,vp) JS_ComputeThis(cx, vp)
3043 #define JS_THIS_OBJECT(cx,vp) (JSVAL_TO_OBJECT(JS_THIS(cx,vp)))
3044 #define JS_ARGV(cx,vp) ((vp) + 2)
3045 #define JS_RVAL(cx,vp) (*(vp))
3046 #define JS_SET_RVAL(cx,vp,v) (*(vp) = (v))
3048 extern JS_PUBLIC_API(jsval)
3049 JS_ComputeThis(JSContext *cx, jsval *vp);
3051 #ifdef __cplusplus
3052 #undef JS_THIS
3053 static inline jsval
3054 JS_THIS(JSContext *cx, jsval *vp)
3056 return JSVAL_IS_PRIMITIVE(vp[1]) ? JS_ComputeThis(cx, vp) : vp[1];
3058 #endif
3061 * |this| is passed to functions in ES5 without change. Functions themselves
3062 * do any post-processing they desire to box |this|, compute the global object,
3063 * &c. Use this macro to retrieve a function's unboxed |this| value.
3065 * This macro must not be used in conjunction with JS_THIS or JS_THIS_OBJECT,
3066 * or vice versa. Either use the provided this value with this macro, or
3067 * compute the boxed this value using those.
3069 * N.B. constructors must not use JS_THIS_VALUE, as no 'this' object has been
3070 * created.
3072 #define JS_THIS_VALUE(cx,vp) ((vp)[1])
3074 extern JS_PUBLIC_API(void)
3075 JS_MallocInCompartment(JSCompartment *comp, size_t nbytes);
3077 extern JS_PUBLIC_API(void)
3078 JS_FreeInCompartment(JSCompartment *comp, size_t nbytes);
3080 extern JS_PUBLIC_API(void *)
3081 JS_malloc(JSContext *cx, size_t nbytes);
3083 extern JS_PUBLIC_API(void *)
3084 JS_realloc(JSContext *cx, void *p, size_t nbytes);
3087 * A wrapper for js_free(p) that may delay js_free(p) invocation as a
3088 * performance optimization.
3090 extern JS_PUBLIC_API(void)
3091 JS_free(JSContext *cx, void *p);
3094 * A wrapper for js_free(p) that may delay js_free(p) invocation as a
3095 * performance optimization as specified by the given JSFreeOp instance.
3097 extern JS_PUBLIC_API(void)
3098 JS_freeop(JSFreeOp *fop, void *p);
3100 extern JS_PUBLIC_API(JSFreeOp *)
3101 JS_GetDefaultFreeOp(JSRuntime *rt);
3103 extern JS_PUBLIC_API(void)
3104 JS_updateMallocCounter(JSContext *cx, size_t nbytes);
3106 extern JS_PUBLIC_API(char *)
3107 JS_strdup(JSContext *cx, const char *s);
3109 extern JS_PUBLIC_API(JSBool)
3110 JS_NewNumberValue(JSContext *cx, double d, jsval *rval);
3113 * A GC root is a pointer to a jsval, JSObject * or JSString * that itself
3114 * points into the GC heap. JS_AddValueRoot takes a pointer to a jsval and
3115 * JS_AddGCThingRoot takes a pointer to a JSObject * or JString *.
3117 * Note that, since JS_Add*Root stores the address of a variable (of type
3118 * jsval, JSString *, or JSObject *), that variable must live until
3119 * JS_Remove*Root is called to remove that variable. For example, after:
3121 * void some_function() {
3122 * jsval v;
3123 * JS_AddNamedRootedValue(cx, &v, "name");
3125 * the caller must perform
3127 * JS_RemoveRootedValue(cx, &v);
3129 * before some_function() returns.
3131 * Also, use JS_AddNamed*Root(cx, &structPtr->memberObj, "structPtr->memberObj")
3132 * in preference to JS_Add*Root(cx, &structPtr->memberObj), in order to identify
3133 * roots by their source callsites. This way, you can find the callsite while
3134 * debugging if you should fail to do JS_Remove*Root(cx, &structPtr->memberObj)
3135 * before freeing structPtr's memory.
3137 extern JS_PUBLIC_API(JSBool)
3138 JS_AddValueRoot(JSContext *cx, jsval *vp);
3140 extern JS_PUBLIC_API(JSBool)
3141 JS_AddStringRoot(JSContext *cx, JSString **rp);
3143 extern JS_PUBLIC_API(JSBool)
3144 JS_AddObjectRoot(JSContext *cx, JSObject **rp);
3146 extern JS_PUBLIC_API(JSBool)
3147 JS_AddGCThingRoot(JSContext *cx, void **rp);
3149 #ifdef NAME_ALL_GC_ROOTS
3150 #define JS_DEFINE_TO_TOKEN(def) #def
3151 #define JS_DEFINE_TO_STRING(def) JS_DEFINE_TO_TOKEN(def)
3152 #define JS_AddValueRoot(cx,vp) JS_AddNamedValueRoot((cx), (vp), (__FILE__ ":" JS_TOKEN_TO_STRING(__LINE__))
3153 #define JS_AddStringRoot(cx,rp) JS_AddNamedStringRoot((cx), (rp), (__FILE__ ":" JS_TOKEN_TO_STRING(__LINE__))
3154 #define JS_AddObjectRoot(cx,rp) JS_AddNamedObjectRoot((cx), (rp), (__FILE__ ":" JS_TOKEN_TO_STRING(__LINE__))
3155 #define JS_AddGCThingRoot(cx,rp) JS_AddNamedGCThingRoot((cx), (rp), (__FILE__ ":" JS_TOKEN_TO_STRING(__LINE__))
3156 #endif
3158 extern JS_PUBLIC_API(JSBool)
3159 JS_AddNamedValueRoot(JSContext *cx, jsval *vp, const char *name);
3161 extern JS_PUBLIC_API(JSBool)
3162 JS_AddNamedStringRoot(JSContext *cx, JSString **rp, const char *name);
3164 extern JS_PUBLIC_API(JSBool)
3165 JS_AddNamedObjectRoot(JSContext *cx, JSObject **rp, const char *name);
3167 extern JS_PUBLIC_API(JSBool)
3168 JS_AddNamedScriptRoot(JSContext *cx, JSScript **rp, const char *name);
3170 extern JS_PUBLIC_API(JSBool)
3171 JS_AddNamedGCThingRoot(JSContext *cx, void **rp, const char *name);
3173 extern JS_PUBLIC_API(void)
3174 JS_RemoveValueRoot(JSContext *cx, jsval *vp);
3176 extern JS_PUBLIC_API(void)
3177 JS_RemoveStringRoot(JSContext *cx, JSString **rp);
3179 extern JS_PUBLIC_API(void)
3180 JS_RemoveObjectRoot(JSContext *cx, JSObject **rp);
3182 extern JS_PUBLIC_API(void)
3183 JS_RemoveScriptRoot(JSContext *cx, JSScript **rp);
3185 extern JS_PUBLIC_API(void)
3186 JS_RemoveGCThingRoot(JSContext *cx, void **rp);
3188 extern JS_PUBLIC_API(void)
3189 JS_RemoveValueRootRT(JSRuntime *rt, jsval *vp);
3191 extern JS_PUBLIC_API(void)
3192 JS_RemoveStringRootRT(JSRuntime *rt, JSString **rp);
3194 extern JS_PUBLIC_API(void)
3195 JS_RemoveObjectRootRT(JSRuntime *rt, JSObject **rp);
3197 extern JS_PUBLIC_API(void)
3198 JS_RemoveScriptRootRT(JSRuntime *rt, JSScript **rp);
3200 /* TODO: remove these APIs */
3202 extern JS_FRIEND_API(JSBool)
3203 js_AddRootRT(JSRuntime *rt, jsval *vp, const char *name);
3205 extern JS_FRIEND_API(JSBool)
3206 js_AddGCThingRootRT(JSRuntime *rt, void **rp, const char *name);
3208 extern JS_FRIEND_API(void)
3209 js_RemoveRoot(JSRuntime *rt, void *rp);
3212 * C-compatible version of the Anchor class. It should be called after the last
3213 * use of the variable it protects.
3215 extern JS_NEVER_INLINE JS_PUBLIC_API(void)
3216 JS_AnchorPtr(void *p);
3219 * This symbol may be used by embedders to detect the change from the old
3220 * JS_AddRoot(JSContext *, void *) APIs to the new ones above.
3222 #define JS_TYPED_ROOTING_API
3224 /* Obsolete rooting APIs. */
3225 #define JS_EnterLocalRootScope(cx) (JS_TRUE)
3226 #define JS_LeaveLocalRootScope(cx) ((void) 0)
3227 #define JS_LeaveLocalRootScopeWithResult(cx, rval) ((void) 0)
3228 #define JS_ForgetLocalRoot(cx, thing) ((void) 0)
3230 typedef enum JSGCRootType {
3231 JS_GC_ROOT_VALUE_PTR,
3232 JS_GC_ROOT_GCTHING_PTR
3233 } JSGCRootType;
3235 #ifdef DEBUG
3236 extern JS_PUBLIC_API(void)
3237 JS_DumpNamedRoots(JSRuntime *rt,
3238 void (*dump)(const char *name, void *rp, JSGCRootType type, void *data),
3239 void *data);
3240 #endif
3243 * Call JS_MapGCRoots to map the GC's roots table using map(rp, name, data).
3244 * The root is pointed at by rp; if the root is unnamed, name is null; data is
3245 * supplied from the third parameter to JS_MapGCRoots.
3247 * The map function should return JS_MAP_GCROOT_REMOVE to cause the currently
3248 * enumerated root to be removed. To stop enumeration, set JS_MAP_GCROOT_STOP
3249 * in the return value. To keep on mapping, return JS_MAP_GCROOT_NEXT. These
3250 * constants are flags; you can OR them together.
3252 * The JSGCRootType parameter indicates whether rp is a pointer to a Value
3253 * (which is obtained by '(Value *)rp') or a pointer to a GC-thing pointer
3254 * (which is obtained by '(void **)rp').
3256 * JS_MapGCRoots returns the count of roots that were successfully mapped.
3258 #define JS_MAP_GCROOT_NEXT 0 /* continue mapping entries */
3259 #define JS_MAP_GCROOT_STOP 1 /* stop mapping entries */
3260 #define JS_MAP_GCROOT_REMOVE 2 /* remove and free the current entry */
3262 typedef int
3263 (* JSGCRootMapFun)(void *rp, JSGCRootType type, const char *name, void *data);
3265 extern JS_PUBLIC_API(uint32_t)
3266 JS_MapGCRoots(JSRuntime *rt, JSGCRootMapFun map, void *data);
3268 extern JS_PUBLIC_API(JSBool)
3269 JS_LockGCThing(JSContext *cx, void *thing);
3271 extern JS_PUBLIC_API(JSBool)
3272 JS_LockGCThingRT(JSRuntime *rt, void *thing);
3274 extern JS_PUBLIC_API(JSBool)
3275 JS_UnlockGCThing(JSContext *cx, void *thing);
3277 extern JS_PUBLIC_API(JSBool)
3278 JS_UnlockGCThingRT(JSRuntime *rt, void *thing);
3281 * Register externally maintained GC roots.
3283 * traceOp: the trace operation. For each root the implementation should call
3284 * JS_CallTracer whenever the root contains a traceable thing.
3285 * data: the data argument to pass to each invocation of traceOp.
3287 extern JS_PUBLIC_API(void)
3288 JS_SetExtraGCRootsTracer(JSRuntime *rt, JSTraceDataOp traceOp, void *data);
3291 * JS_CallTracer API and related macros for implementors of JSTraceOp, to
3292 * enumerate all references to traceable things reachable via a property or
3293 * other strong ref identified for debugging purposes by name or index or
3294 * a naming callback.
3296 * See the JSTraceOp typedef.
3300 * Use the following macros to check if a particular jsval is a traceable
3301 * thing and to extract the thing and its kind to pass to JS_CallTracer.
3303 static JS_ALWAYS_INLINE JSBool
3304 JSVAL_IS_TRACEABLE(jsval v)
3306 return JSVAL_IS_TRACEABLE_IMPL(JSVAL_TO_IMPL(v));
3309 static JS_ALWAYS_INLINE void *
3310 JSVAL_TO_TRACEABLE(jsval v)
3312 return JSVAL_TO_GCTHING(v);
3315 static JS_ALWAYS_INLINE JSGCTraceKind
3316 JSVAL_TRACE_KIND(jsval v)
3318 JS_ASSERT(JSVAL_IS_GCTHING(v));
3319 return (JSGCTraceKind) JSVAL_TRACE_KIND_IMPL(JSVAL_TO_IMPL(v));
3323 * Tracer callback, called for each traceable thing directly referenced by a
3324 * particular object or runtime structure. It is the callback responsibility
3325 * to ensure the traversal of the full object graph via calling eventually
3326 * JS_TraceChildren on the passed thing. In this case the callback must be
3327 * prepared to deal with cycles in the traversal graph.
3329 * kind argument is one of JSTRACE_OBJECT, JSTRACE_STRING or a tag denoting
3330 * internal implementation-specific traversal kind. In the latter case the only
3331 * operations on thing that the callback can do is to call JS_TraceChildren or
3332 * DEBUG-only JS_PrintTraceThingInfo.
3334 * If eagerlyTraceWeakMaps is true, when we trace a WeakMap visit all
3335 * of its mappings. This should be used in cases where the tracer
3336 * wants to use the existing liveness of entries.
3338 typedef void
3339 (* JSTraceCallback)(JSTracer *trc, void **thingp, JSGCTraceKind kind);
3341 struct JSTracer {
3342 JSRuntime *runtime;
3343 JSTraceCallback callback;
3344 JSTraceNamePrinter debugPrinter;
3345 const void *debugPrintArg;
3346 size_t debugPrintIndex;
3347 JSBool eagerlyTraceWeakMaps;
3348 #ifdef DEBUG
3349 void *realLocation;
3350 #endif
3354 * The method to call on each reference to a traceable thing stored in a
3355 * particular JSObject or other runtime structure. With DEBUG defined the
3356 * caller before calling JS_CallTracer must initialize JSTracer fields
3357 * describing the reference using the macros below.
3359 extern JS_PUBLIC_API(void)
3360 JS_CallTracer(JSTracer *trc, void *thing, JSGCTraceKind kind);
3363 * Set debugging information about a reference to a traceable thing to prepare
3364 * for the following call to JS_CallTracer.
3366 * When printer is null, arg must be const char * or char * C string naming
3367 * the reference and index must be either (size_t)-1 indicating that the name
3368 * alone describes the reference or it must be an index into some array vector
3369 * that stores the reference.
3371 * When printer callback is not null, the arg and index arguments are
3372 * available to the callback as debugPrintArg and debugPrintIndex fields
3373 * of JSTracer.
3375 * The storage for name or callback's arguments needs to live only until
3376 * the following call to JS_CallTracer returns.
3378 #ifdef DEBUG
3379 # define JS_SET_TRACING_DETAILS(trc, printer, arg, index) \
3380 JS_BEGIN_MACRO \
3381 (trc)->debugPrinter = (printer); \
3382 (trc)->debugPrintArg = (arg); \
3383 (trc)->debugPrintIndex = (index); \
3384 JS_END_MACRO
3385 #else
3386 # define JS_SET_TRACING_DETAILS(trc, printer, arg, index) \
3387 JS_BEGIN_MACRO \
3388 JS_END_MACRO
3389 #endif
3392 * Sets the real location for a marked reference, when passing the address
3393 * directly is not feasable.
3395 #ifdef DEBUG
3396 # define JS_SET_TRACING_LOCATION(trc, location) \
3397 JS_BEGIN_MACRO \
3398 (trc)->realLocation = (location); \
3399 JS_END_MACRO
3400 #else
3401 # define JS_SET_TRACING_LOCATION(trc, location) \
3402 JS_BEGIN_MACRO \
3403 JS_END_MACRO
3404 #endif
3408 * Convenience macro to describe the argument of JS_CallTracer using C string
3409 * and index.
3411 # define JS_SET_TRACING_INDEX(trc, name, index) \
3412 JS_SET_TRACING_DETAILS(trc, NULL, name, index)
3415 * Convenience macro to describe the argument of JS_CallTracer using C string.
3417 # define JS_SET_TRACING_NAME(trc, name) \
3418 JS_SET_TRACING_DETAILS(trc, NULL, name, (size_t)-1)
3421 * Convenience macro to invoke JS_CallTracer using C string as the name for
3422 * the reference to a traceable thing.
3424 # define JS_CALL_TRACER(trc, thing, kind, name) \
3425 JS_BEGIN_MACRO \
3426 JS_SET_TRACING_NAME(trc, name); \
3427 JS_CallTracer((trc), (thing), (kind)); \
3428 JS_END_MACRO
3431 * Convenience macros to invoke JS_CallTracer when jsval represents a
3432 * reference to a traceable thing.
3434 #define JS_CALL_VALUE_TRACER(trc, val, name) \
3435 JS_BEGIN_MACRO \
3436 if (JSVAL_IS_TRACEABLE(val)) { \
3437 JS_CALL_TRACER((trc), JSVAL_TO_GCTHING(val), \
3438 JSVAL_TRACE_KIND(val), name); \
3440 JS_END_MACRO
3442 #define JS_CALL_OBJECT_TRACER(trc, object, name) \
3443 JS_BEGIN_MACRO \
3444 JSObject *obj_ = (object); \
3445 JS_ASSERT(obj_); \
3446 JS_CALL_TRACER((trc), obj_, JSTRACE_OBJECT, name); \
3447 JS_END_MACRO
3449 #define JS_CALL_STRING_TRACER(trc, string, name) \
3450 JS_BEGIN_MACRO \
3451 JSString *str_ = (string); \
3452 JS_ASSERT(str_); \
3453 JS_CALL_TRACER((trc), str_, JSTRACE_STRING, name); \
3454 JS_END_MACRO
3457 * API for JSTraceCallback implementations.
3459 extern JS_PUBLIC_API(void)
3460 JS_TracerInit(JSTracer *trc, JSRuntime *rt, JSTraceCallback callback);
3462 extern JS_PUBLIC_API(void)
3463 JS_TraceChildren(JSTracer *trc, void *thing, JSGCTraceKind kind);
3465 extern JS_PUBLIC_API(void)
3466 JS_TraceRuntime(JSTracer *trc);
3468 #ifdef DEBUG
3470 extern JS_PUBLIC_API(void)
3471 JS_PrintTraceThingInfo(char *buf, size_t bufsize, JSTracer *trc,
3472 void *thing, JSGCTraceKind kind, JSBool includeDetails);
3474 extern JS_PUBLIC_API(const char *)
3475 JS_GetTraceEdgeName(JSTracer *trc, char *buffer, int bufferSize);
3478 * DEBUG-only method to dump the object graph of heap-allocated things.
3480 * fp: file for the dump output.
3481 * start: when non-null, dump only things reachable from start
3482 * thing. Otherwise dump all things reachable from the
3483 * runtime roots.
3484 * startKind: trace kind of start if start is not null. Must be
3485 * JSTRACE_OBJECT when start is null.
3486 * thingToFind: dump only paths in the object graph leading to thingToFind
3487 * when non-null.
3488 * maxDepth: the upper bound on the number of edges to descend from the
3489 * graph roots.
3490 * thingToIgnore: thing to ignore during the graph traversal when non-null.
3492 extern JS_PUBLIC_API(JSBool)
3493 JS_DumpHeap(JSRuntime *rt, FILE *fp, void* startThing, JSGCTraceKind kind,
3494 void *thingToFind, size_t maxDepth, void *thingToIgnore);
3496 #endif
3499 * Garbage collector API.
3501 extern JS_PUBLIC_API(void)
3502 JS_GC(JSRuntime *rt);
3504 extern JS_PUBLIC_API(void)
3505 JS_CompartmentGC(JSRuntime *rt, JSCompartment *comp);
3507 extern JS_PUBLIC_API(void)
3508 JS_MaybeGC(JSContext *cx);
3510 extern JS_PUBLIC_API(void)
3511 JS_SetGCCallback(JSRuntime *rt, JSGCCallback cb);
3513 extern JS_PUBLIC_API(void)
3514 JS_SetFinalizeCallback(JSRuntime *rt, JSFinalizeCallback cb);
3516 extern JS_PUBLIC_API(JSBool)
3517 JS_IsGCMarkingTracer(JSTracer *trc);
3519 extern JS_PUBLIC_API(JSBool)
3520 JS_IsAboutToBeFinalized(void *thing);
3522 typedef enum JSGCParamKey {
3523 /* Maximum nominal heap before last ditch GC. */
3524 JSGC_MAX_BYTES = 0,
3526 /* Number of JS_malloc bytes before last ditch GC. */
3527 JSGC_MAX_MALLOC_BYTES = 1,
3529 /* Amount of bytes allocated by the GC. */
3530 JSGC_BYTES = 3,
3532 /* Number of times when GC was invoked. */
3533 JSGC_NUMBER = 4,
3535 /* Max size of the code cache in bytes. */
3536 JSGC_MAX_CODE_CACHE_BYTES = 5,
3538 /* Select GC mode. */
3539 JSGC_MODE = 6,
3541 /* Number of cached empty GC chunks. */
3542 JSGC_UNUSED_CHUNKS = 7,
3544 /* Total number of allocated GC chunks. */
3545 JSGC_TOTAL_CHUNKS = 8,
3547 /* Max milliseconds to spend in an incremental GC slice. */
3548 JSGC_SLICE_TIME_BUDGET = 9,
3550 /* Maximum size the GC mark stack can grow to. */
3551 JSGC_MARK_STACK_LIMIT = 10
3552 } JSGCParamKey;
3554 typedef enum JSGCMode {
3555 /* Perform only global GCs. */
3556 JSGC_MODE_GLOBAL = 0,
3558 /* Perform per-compartment GCs until too much garbage has accumulated. */
3559 JSGC_MODE_COMPARTMENT = 1,
3562 * Collect in short time slices rather than all at once. Implies
3563 * JSGC_MODE_COMPARTMENT.
3565 JSGC_MODE_INCREMENTAL = 2
3566 } JSGCMode;
3568 extern JS_PUBLIC_API(void)
3569 JS_SetGCParameter(JSRuntime *rt, JSGCParamKey key, uint32_t value);
3571 extern JS_PUBLIC_API(uint32_t)
3572 JS_GetGCParameter(JSRuntime *rt, JSGCParamKey key);
3574 extern JS_PUBLIC_API(void)
3575 JS_SetGCParameterForThread(JSContext *cx, JSGCParamKey key, uint32_t value);
3577 extern JS_PUBLIC_API(uint32_t)
3578 JS_GetGCParameterForThread(JSContext *cx, JSGCParamKey key);
3581 * Create a new JSString whose chars member refers to external memory, i.e.,
3582 * memory requiring application-specific finalization.
3584 extern JS_PUBLIC_API(JSString *)
3585 JS_NewExternalString(JSContext *cx, const jschar *chars, size_t length,
3586 const JSStringFinalizer *fin);
3589 * Return whether 'str' was created with JS_NewExternalString or
3590 * JS_NewExternalStringWithClosure.
3592 extern JS_PUBLIC_API(JSBool)
3593 JS_IsExternalString(JSString *str);
3596 * Return the 'closure' arg passed to JS_NewExternalStringWithClosure or NULL
3597 * if the external string was created via JS_NewExternalString.
3599 extern JS_PUBLIC_API(const JSStringFinalizer *)
3600 JS_GetExternalStringFinalizer(JSString *str);
3603 * Set the size of the native stack that should not be exceed. To disable
3604 * stack size checking pass 0.
3606 extern JS_PUBLIC_API(void)
3607 JS_SetNativeStackQuota(JSRuntime *cx, size_t stackSize);
3609 /************************************************************************/
3612 * Classes, objects, and properties.
3614 typedef void (*JSClassInternal)();
3616 struct JSClass {
3617 const char *name;
3618 uint32_t flags;
3620 /* Mandatory non-null function pointer members. */
3621 JSPropertyOp addProperty;
3622 JSPropertyOp delProperty;
3623 JSPropertyOp getProperty;
3624 JSStrictPropertyOp setProperty;
3625 JSEnumerateOp enumerate;
3626 JSResolveOp resolve;
3627 JSConvertOp convert;
3628 JSFinalizeOp finalize;
3630 /* Optionally non-null members start here. */
3631 JSCheckAccessOp checkAccess;
3632 JSNative call;
3633 JSHasInstanceOp hasInstance;
3634 JSNative construct;
3635 JSTraceOp trace;
3637 void *reserved[40];
3640 #define JSCLASS_HAS_PRIVATE (1<<0) /* objects have private slot */
3641 #define JSCLASS_NEW_ENUMERATE (1<<1) /* has JSNewEnumerateOp hook */
3642 #define JSCLASS_NEW_RESOLVE (1<<2) /* has JSNewResolveOp hook */
3643 #define JSCLASS_PRIVATE_IS_NSISUPPORTS (1<<3) /* private is (nsISupports *) */
3644 #define JSCLASS_NEW_RESOLVE_GETS_START (1<<4) /* JSNewResolveOp gets starting
3645 object in prototype chain
3646 passed in via *objp in/out
3647 parameter */
3648 #define JSCLASS_IMPLEMENTS_BARRIERS (1<<5) /* Correctly implements GC read
3649 and write barriers */
3650 #define JSCLASS_DOCUMENT_OBSERVER (1<<6) /* DOM document observer */
3651 #define JSCLASS_USERBIT1 (1<<7) /* Reserved for embeddings. */
3654 * To reserve slots fetched and stored via JS_Get/SetReservedSlot, bitwise-or
3655 * JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where
3656 * n is a constant in [1, 255]. Reserved slots are indexed from 0 to n-1.
3658 #define JSCLASS_RESERVED_SLOTS_SHIFT 8 /* room for 8 flags below */
3659 #define JSCLASS_RESERVED_SLOTS_WIDTH 8 /* and 16 above this field */
3660 #define JSCLASS_RESERVED_SLOTS_MASK JS_BITMASK(JSCLASS_RESERVED_SLOTS_WIDTH)
3661 #define JSCLASS_HAS_RESERVED_SLOTS(n) (((n) & JSCLASS_RESERVED_SLOTS_MASK) \
3662 << JSCLASS_RESERVED_SLOTS_SHIFT)
3663 #define JSCLASS_RESERVED_SLOTS(clasp) (((clasp)->flags \
3664 >> JSCLASS_RESERVED_SLOTS_SHIFT) \
3665 & JSCLASS_RESERVED_SLOTS_MASK)
3667 #define JSCLASS_HIGH_FLAGS_SHIFT (JSCLASS_RESERVED_SLOTS_SHIFT + \
3668 JSCLASS_RESERVED_SLOTS_WIDTH)
3671 * Call the iteratorObject hook only to iterate over contents (for-of), not to
3672 * enumerate properties (for-in, for-each, Object.keys, etc.)
3674 #define JSCLASS_FOR_OF_ITERATION (1<<(JSCLASS_HIGH_FLAGS_SHIFT+0))
3676 #define JSCLASS_IS_ANONYMOUS (1<<(JSCLASS_HIGH_FLAGS_SHIFT+1))
3677 #define JSCLASS_IS_GLOBAL (1<<(JSCLASS_HIGH_FLAGS_SHIFT+2))
3678 #define JSCLASS_INTERNAL_FLAG2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+3))
3679 #define JSCLASS_INTERNAL_FLAG3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+4))
3681 /* Indicate whether the proto or ctor should be frozen. */
3682 #define JSCLASS_FREEZE_PROTO (1<<(JSCLASS_HIGH_FLAGS_SHIFT+5))
3683 #define JSCLASS_FREEZE_CTOR (1<<(JSCLASS_HIGH_FLAGS_SHIFT+6))
3685 #define JSCLASS_XPCONNECT_GLOBAL (1<<(JSCLASS_HIGH_FLAGS_SHIFT+7))
3687 /* Reserved for embeddings. */
3688 #define JSCLASS_USERBIT2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+8))
3689 #define JSCLASS_USERBIT3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+9))
3692 * Bits 26 through 31 are reserved for the CACHED_PROTO_KEY mechanism, see
3693 * below.
3696 /* Global flags. */
3697 #define JSGLOBAL_FLAGS_CLEARED 0x1
3700 * ECMA-262 requires that most constructors used internally create objects
3701 * with "the original Foo.prototype value" as their [[Prototype]] (__proto__)
3702 * member initial value. The "original ... value" verbiage is there because
3703 * in ECMA-262, global properties naming class objects are read/write and
3704 * deleteable, for the most part.
3706 * Implementing this efficiently requires that global objects have classes
3707 * with the following flags. Failure to use JSCLASS_GLOBAL_FLAGS was
3708 * prevously allowed, but is now an ES5 violation and thus unsupported.
3710 #define JSCLASS_GLOBAL_SLOT_COUNT (JSProto_LIMIT * 3 + 8)
3711 #define JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(n) \
3712 (JSCLASS_IS_GLOBAL | JSCLASS_HAS_RESERVED_SLOTS(JSCLASS_GLOBAL_SLOT_COUNT + (n)))
3713 #define JSCLASS_GLOBAL_FLAGS \
3714 JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(0)
3715 #define JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(clasp) \
3716 (((clasp)->flags & JSCLASS_IS_GLOBAL) \
3717 && JSCLASS_RESERVED_SLOTS(clasp) >= JSCLASS_GLOBAL_SLOT_COUNT)
3719 /* Fast access to the original value of each standard class's prototype. */
3720 #define JSCLASS_CACHED_PROTO_SHIFT (JSCLASS_HIGH_FLAGS_SHIFT + 10)
3721 #define JSCLASS_CACHED_PROTO_WIDTH 6
3722 #define JSCLASS_CACHED_PROTO_MASK JS_BITMASK(JSCLASS_CACHED_PROTO_WIDTH)
3723 #define JSCLASS_HAS_CACHED_PROTO(key) (uint32_t(key) << JSCLASS_CACHED_PROTO_SHIFT)
3724 #define JSCLASS_CACHED_PROTO_KEY(clasp) ((JSProtoKey) \
3725 (((clasp)->flags \
3726 >> JSCLASS_CACHED_PROTO_SHIFT) \
3727 & JSCLASS_CACHED_PROTO_MASK))
3729 /* Initializer for unused members of statically initialized JSClass structs. */
3730 #define JSCLASS_NO_INTERNAL_MEMBERS {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
3731 #define JSCLASS_NO_OPTIONAL_MEMBERS 0,0,0,0,0,JSCLASS_NO_INTERNAL_MEMBERS
3733 extern JS_PUBLIC_API(int)
3734 JS_IdArrayLength(JSContext *cx, JSIdArray *ida);
3736 extern JS_PUBLIC_API(jsid)
3737 JS_IdArrayGet(JSContext *cx, JSIdArray *ida, int index);
3739 extern JS_PUBLIC_API(void)
3740 JS_DestroyIdArray(JSContext *cx, JSIdArray *ida);
3742 #ifdef __cplusplus
3744 namespace JS {
3746 class AutoIdArray : private AutoGCRooter {
3747 public:
3748 AutoIdArray(JSContext *cx, JSIdArray *ida JS_GUARD_OBJECT_NOTIFIER_PARAM)
3749 : AutoGCRooter(cx, IDARRAY), context(cx), idArray(ida)
3751 JS_GUARD_OBJECT_NOTIFIER_INIT;
3753 ~AutoIdArray() {
3754 if (idArray)
3755 JS_DestroyIdArray(context, idArray);
3757 bool operator!() {
3758 return !idArray;
3760 jsid operator[](size_t i) const {
3761 JS_ASSERT(idArray);
3762 JS_ASSERT(i < length());
3763 return JS_IdArrayGet(context, idArray, i);
3765 size_t length() const {
3766 return JS_IdArrayLength(context, idArray);
3769 friend void AutoGCRooter::trace(JSTracer *trc);
3771 JSIdArray *steal() {
3772 JSIdArray *copy = idArray;
3773 idArray = NULL;
3774 return copy;
3777 protected:
3778 inline void trace(JSTracer *trc);
3780 private:
3781 JSContext *context;
3782 JSIdArray *idArray;
3783 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
3785 /* No copy or assignment semantics. */
3786 AutoIdArray(AutoIdArray &ida) MOZ_DELETE;
3787 void operator=(AutoIdArray &ida) MOZ_DELETE;
3790 } /* namespace JS */
3792 #endif /* __cplusplus */
3794 extern JS_PUBLIC_API(JSBool)
3795 JS_ValueToId(JSContext *cx, jsval v, jsid *idp);
3797 extern JS_PUBLIC_API(JSBool)
3798 JS_IdToValue(JSContext *cx, jsid id, jsval *vp);
3801 * JSNewResolveOp flag bits.
3803 #define JSRESOLVE_QUALIFIED 0x01 /* resolve a qualified property id */
3804 #define JSRESOLVE_ASSIGNING 0x02 /* resolve on the left of assignment */
3805 #define JSRESOLVE_DETECTING 0x04 /* 'if (o.p)...' or '(o.p) ?...:...' */
3806 #define JSRESOLVE_DECLARING 0x08 /* var, const, or function prolog op */
3807 #define JSRESOLVE_CLASSNAME 0x10 /* class name used when constructing */
3808 #define JSRESOLVE_WITH 0x20 /* resolve inside a with statement */
3811 * Invoke the [[DefaultValue]] hook (see ES5 8.6.2) with the provided hint on
3812 * the specified object, computing a primitive default value for the object.
3813 * The hint must be JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_VOID (no hint). On
3814 * success the resulting value is stored in *vp.
3816 extern JS_PUBLIC_API(JSBool)
3817 JS_DefaultValue(JSContext *cx, JSObject *obj, JSType hint, jsval *vp);
3819 extern JS_PUBLIC_API(JSBool)
3820 JS_PropertyStub(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
3822 extern JS_PUBLIC_API(JSBool)
3823 JS_StrictPropertyStub(JSContext *cx, JSObject *obj, jsid id, JSBool strict, jsval *vp);
3825 extern JS_PUBLIC_API(JSBool)
3826 JS_EnumerateStub(JSContext *cx, JSObject *obj);
3828 extern JS_PUBLIC_API(JSBool)
3829 JS_ResolveStub(JSContext *cx, JSObject *obj, jsid id);
3831 extern JS_PUBLIC_API(JSBool)
3832 JS_ConvertStub(JSContext *cx, JSObject *obj, JSType type, jsval *vp);
3834 struct JSConstDoubleSpec {
3835 double dval;
3836 const char *name;
3837 uint8_t flags;
3838 uint8_t spare[3];
3842 * To define an array element rather than a named property member, cast the
3843 * element's index to (const char *) and initialize name with it, and set the
3844 * JSPROP_INDEX bit in flags.
3846 struct JSPropertySpec {
3847 const char *name;
3848 int8_t tinyid;
3849 uint8_t flags;
3850 JSPropertyOp getter;
3851 JSStrictPropertyOp setter;
3854 struct JSFunctionSpec {
3855 const char *name;
3856 JSNative call;
3857 uint16_t nargs;
3858 uint16_t flags;
3862 * Terminating sentinel initializer to put at the end of a JSFunctionSpec array
3863 * that's passed to JS_DefineFunctions or JS_InitClass.
3865 #define JS_FS_END JS_FS(NULL,NULL,0,0)
3868 * Initializer macros for a JSFunctionSpec array element. JS_FN (whose name
3869 * pays homage to the old JSNative/JSFastNative split) simply adds the flag
3870 * JSFUN_STUB_GSOPS.
3872 #define JS_FS(name,call,nargs,flags) \
3873 {name, call, nargs, flags}
3874 #define JS_FN(name,call,nargs,flags) \
3875 {name, call, nargs, (flags) | JSFUN_STUB_GSOPS}
3877 extern JS_PUBLIC_API(JSObject *)
3878 JS_InitClass(JSContext *cx, JSObject *obj, JSObject *parent_proto,
3879 JSClass *clasp, JSNative constructor, unsigned nargs,
3880 JSPropertySpec *ps, JSFunctionSpec *fs,
3881 JSPropertySpec *static_ps, JSFunctionSpec *static_fs);
3884 * Set up ctor.prototype = proto and proto.constructor = ctor with the
3885 * right property flags.
3887 extern JS_PUBLIC_API(JSBool)
3888 JS_LinkConstructorAndPrototype(JSContext *cx, JSObject *ctor, JSObject *proto);
3890 extern JS_PUBLIC_API(JSClass *)
3891 JS_GetClass(JSObject *obj);
3893 extern JS_PUBLIC_API(JSBool)
3894 JS_InstanceOf(JSContext *cx, JSObject *obj, JSClass *clasp, jsval *argv);
3896 extern JS_PUBLIC_API(JSBool)
3897 JS_HasInstance(JSContext *cx, JSObject *obj, jsval v, JSBool *bp);
3899 extern JS_PUBLIC_API(void *)
3900 JS_GetPrivate(JSObject *obj);
3902 extern JS_PUBLIC_API(void)
3903 JS_SetPrivate(JSObject *obj, void *data);
3905 extern JS_PUBLIC_API(void *)
3906 JS_GetInstancePrivate(JSContext *cx, JSObject *obj, JSClass *clasp,
3907 jsval *argv);
3909 extern JS_PUBLIC_API(JSObject *)
3910 JS_GetPrototype(JSObject *obj);
3912 extern JS_PUBLIC_API(JSBool)
3913 JS_SetPrototype(JSContext *cx, JSObject *obj, JSObject *proto);
3915 extern JS_PUBLIC_API(JSObject *)
3916 JS_GetParent(JSObject *obj);
3918 extern JS_PUBLIC_API(JSBool)
3919 JS_SetParent(JSContext *cx, JSObject *obj, JSObject *parent);
3921 extern JS_PUBLIC_API(JSObject *)
3922 JS_GetConstructor(JSContext *cx, JSObject *proto);
3925 * Get a unique identifier for obj, good for the lifetime of obj (even if it
3926 * is moved by a copying GC). Return false on failure (likely out of memory),
3927 * and true with *idp containing the unique id on success.
3929 extern JS_PUBLIC_API(JSBool)
3930 JS_GetObjectId(JSContext *cx, JSObject *obj, jsid *idp);
3932 extern JS_PUBLIC_API(JSObject *)
3933 JS_NewGlobalObject(JSContext *cx, JSClass *clasp);
3935 extern JS_PUBLIC_API(JSObject *)
3936 JS_NewCompartmentAndGlobalObject(JSContext *cx, JSClass *clasp, JSPrincipals *principals);
3938 extern JS_PUBLIC_API(JSObject *)
3939 JS_NewObject(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent);
3941 /* Queries the [[Extensible]] property of the object. */
3942 extern JS_PUBLIC_API(JSBool)
3943 JS_IsExtensible(JSObject *obj);
3945 extern JS_PUBLIC_API(JSBool)
3946 JS_IsNative(JSObject *obj);
3948 extern JS_PUBLIC_API(JSRuntime *)
3949 JS_GetObjectRuntime(JSObject *obj);
3952 * Unlike JS_NewObject, JS_NewObjectWithGivenProto does not compute a default
3953 * proto if proto's actual parameter value is null.
3955 extern JS_PUBLIC_API(JSObject *)
3956 JS_NewObjectWithGivenProto(JSContext *cx, JSClass *clasp, JSObject *proto,
3957 JSObject *parent);
3960 * Freeze obj, and all objects it refers to, recursively. This will not recurse
3961 * through non-extensible objects, on the assumption that those are already
3962 * deep-frozen.
3964 extern JS_PUBLIC_API(JSBool)
3965 JS_DeepFreezeObject(JSContext *cx, JSObject *obj);
3968 * Freezes an object; see ES5's Object.freeze(obj) method.
3970 extern JS_PUBLIC_API(JSBool)
3971 JS_FreezeObject(JSContext *cx, JSObject *obj);
3973 extern JS_PUBLIC_API(JSObject *)
3974 JS_ConstructObject(JSContext *cx, JSClass *clasp, JSObject *parent);
3976 extern JS_PUBLIC_API(JSObject *)
3977 JS_ConstructObjectWithArguments(JSContext *cx, JSClass *clasp, JSObject *parent,
3978 unsigned argc, jsval *argv);
3980 extern JS_PUBLIC_API(JSObject *)
3981 JS_New(JSContext *cx, JSObject *ctor, unsigned argc, jsval *argv);
3983 extern JS_PUBLIC_API(JSObject *)
3984 JS_DefineObject(JSContext *cx, JSObject *obj, const char *name, JSClass *clasp,
3985 JSObject *proto, unsigned attrs);
3987 extern JS_PUBLIC_API(JSBool)
3988 JS_DefineConstDoubles(JSContext *cx, JSObject *obj, JSConstDoubleSpec *cds);
3990 extern JS_PUBLIC_API(JSBool)
3991 JS_DefineProperties(JSContext *cx, JSObject *obj, JSPropertySpec *ps);
3993 extern JS_PUBLIC_API(JSBool)
3994 JS_DefineProperty(JSContext *cx, JSObject *obj, const char *name, jsval value,
3995 JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs);
3997 extern JS_PUBLIC_API(JSBool)
3998 JS_DefinePropertyById(JSContext *cx, JSObject *obj, jsid id, jsval value,
3999 JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs);
4001 extern JS_PUBLIC_API(JSBool)
4002 JS_DefineOwnProperty(JSContext *cx, JSObject *obj, jsid id, jsval descriptor, JSBool *bp);
4005 * Determine the attributes (JSPROP_* flags) of a property on a given object.
4007 * If the object does not have a property by that name, *foundp will be
4008 * JS_FALSE and the value of *attrsp is undefined.
4010 extern JS_PUBLIC_API(JSBool)
4011 JS_GetPropertyAttributes(JSContext *cx, JSObject *obj, const char *name,
4012 unsigned *attrsp, JSBool *foundp);
4015 * The same, but if the property is native, return its getter and setter via
4016 * *getterp and *setterp, respectively (and only if the out parameter pointer
4017 * is not null).
4019 extern JS_PUBLIC_API(JSBool)
4020 JS_GetPropertyAttrsGetterAndSetter(JSContext *cx, JSObject *obj,
4021 const char *name,
4022 unsigned *attrsp, JSBool *foundp,
4023 JSPropertyOp *getterp,
4024 JSStrictPropertyOp *setterp);
4026 extern JS_PUBLIC_API(JSBool)
4027 JS_GetPropertyAttrsGetterAndSetterById(JSContext *cx, JSObject *obj,
4028 jsid id,
4029 unsigned *attrsp, JSBool *foundp,
4030 JSPropertyOp *getterp,
4031 JSStrictPropertyOp *setterp);
4034 * Set the attributes of a property on a given object.
4036 * If the object does not have a property by that name, *foundp will be
4037 * JS_FALSE and nothing will be altered.
4039 extern JS_PUBLIC_API(JSBool)
4040 JS_SetPropertyAttributes(JSContext *cx, JSObject *obj, const char *name,
4041 unsigned attrs, JSBool *foundp);
4043 extern JS_PUBLIC_API(JSBool)
4044 JS_DefinePropertyWithTinyId(JSContext *cx, JSObject *obj, const char *name,
4045 int8_t tinyid, jsval value,
4046 JSPropertyOp getter, JSStrictPropertyOp setter,
4047 unsigned attrs);
4049 extern JS_PUBLIC_API(JSBool)
4050 JS_AlreadyHasOwnProperty(JSContext *cx, JSObject *obj, const char *name,
4051 JSBool *foundp);
4053 extern JS_PUBLIC_API(JSBool)
4054 JS_AlreadyHasOwnPropertyById(JSContext *cx, JSObject *obj, jsid id,
4055 JSBool *foundp);
4057 extern JS_PUBLIC_API(JSBool)
4058 JS_HasProperty(JSContext *cx, JSObject *obj, const char *name, JSBool *foundp);
4060 extern JS_PUBLIC_API(JSBool)
4061 JS_HasPropertyById(JSContext *cx, JSObject *obj, jsid id, JSBool *foundp);
4063 extern JS_PUBLIC_API(JSBool)
4064 JS_LookupProperty(JSContext *cx, JSObject *obj, const char *name, jsval *vp);
4066 extern JS_PUBLIC_API(JSBool)
4067 JS_LookupPropertyById(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
4069 extern JS_PUBLIC_API(JSBool)
4070 JS_LookupPropertyWithFlags(JSContext *cx, JSObject *obj, const char *name,
4071 unsigned flags, jsval *vp);
4073 extern JS_PUBLIC_API(JSBool)
4074 JS_LookupPropertyWithFlagsById(JSContext *cx, JSObject *obj, jsid id,
4075 unsigned flags, JSObject **objp, jsval *vp);
4077 struct JSPropertyDescriptor {
4078 JSObject *obj;
4079 unsigned attrs;
4080 unsigned shortid;
4081 JSPropertyOp getter;
4082 JSStrictPropertyOp setter;
4083 jsval value;
4087 * Like JS_GetPropertyAttrsGetterAndSetterById but will return a property on
4088 * an object on the prototype chain (returned in objp). If data->obj is null,
4089 * then this property was not found on the prototype chain.
4091 extern JS_PUBLIC_API(JSBool)
4092 JS_GetPropertyDescriptorById(JSContext *cx, JSObject *obj, jsid id, unsigned flags,
4093 JSPropertyDescriptor *desc);
4095 extern JS_PUBLIC_API(JSBool)
4096 JS_GetOwnPropertyDescriptor(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
4098 extern JS_PUBLIC_API(JSBool)
4099 JS_GetProperty(JSContext *cx, JSObject *obj, const char *name, jsval *vp);
4101 extern JS_PUBLIC_API(JSBool)
4102 JS_GetPropertyDefault(JSContext *cx, JSObject *obj, const char *name, jsval def, jsval *vp);
4104 extern JS_PUBLIC_API(JSBool)
4105 JS_GetPropertyById(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
4107 extern JS_PUBLIC_API(JSBool)
4108 JS_GetPropertyByIdDefault(JSContext *cx, JSObject *obj, jsid id, jsval def, jsval *vp);
4110 extern JS_PUBLIC_API(JSBool)
4111 JS_ForwardGetPropertyTo(JSContext *cx, JSObject *obj, jsid id, JSObject *onBehalfOf, jsval *vp);
4113 extern JS_PUBLIC_API(JSBool)
4114 JS_GetMethodById(JSContext *cx, JSObject *obj, jsid id, JSObject **objp,
4115 jsval *vp);
4117 extern JS_PUBLIC_API(JSBool)
4118 JS_GetMethod(JSContext *cx, JSObject *obj, const char *name, JSObject **objp,
4119 jsval *vp);
4121 extern JS_PUBLIC_API(JSBool)
4122 JS_SetProperty(JSContext *cx, JSObject *obj, const char *name, jsval *vp);
4124 extern JS_PUBLIC_API(JSBool)
4125 JS_SetPropertyById(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
4127 extern JS_PUBLIC_API(JSBool)
4128 JS_DeleteProperty(JSContext *cx, JSObject *obj, const char *name);
4130 extern JS_PUBLIC_API(JSBool)
4131 JS_DeleteProperty2(JSContext *cx, JSObject *obj, const char *name,
4132 jsval *rval);
4134 extern JS_PUBLIC_API(JSBool)
4135 JS_DeletePropertyById(JSContext *cx, JSObject *obj, jsid id);
4137 extern JS_PUBLIC_API(JSBool)
4138 JS_DeletePropertyById2(JSContext *cx, JSObject *obj, jsid id, jsval *rval);
4140 extern JS_PUBLIC_API(JSBool)
4141 JS_DefineUCProperty(JSContext *cx, JSObject *obj,
4142 const jschar *name, size_t namelen, jsval value,
4143 JSPropertyOp getter, JSStrictPropertyOp setter,
4144 unsigned attrs);
4147 * Determine the attributes (JSPROP_* flags) of a property on a given object.
4149 * If the object does not have a property by that name, *foundp will be
4150 * JS_FALSE and the value of *attrsp is undefined.
4152 extern JS_PUBLIC_API(JSBool)
4153 JS_GetUCPropertyAttributes(JSContext *cx, JSObject *obj,
4154 const jschar *name, size_t namelen,
4155 unsigned *attrsp, JSBool *foundp);
4158 * The same, but if the property is native, return its getter and setter via
4159 * *getterp and *setterp, respectively (and only if the out parameter pointer
4160 * is not null).
4162 extern JS_PUBLIC_API(JSBool)
4163 JS_GetUCPropertyAttrsGetterAndSetter(JSContext *cx, JSObject *obj,
4164 const jschar *name, size_t namelen,
4165 unsigned *attrsp, JSBool *foundp,
4166 JSPropertyOp *getterp,
4167 JSStrictPropertyOp *setterp);
4170 * Set the attributes of a property on a given object.
4172 * If the object does not have a property by that name, *foundp will be
4173 * JS_FALSE and nothing will be altered.
4175 extern JS_PUBLIC_API(JSBool)
4176 JS_SetUCPropertyAttributes(JSContext *cx, JSObject *obj,
4177 const jschar *name, size_t namelen,
4178 unsigned attrs, JSBool *foundp);
4181 extern JS_PUBLIC_API(JSBool)
4182 JS_DefineUCPropertyWithTinyId(JSContext *cx, JSObject *obj,
4183 const jschar *name, size_t namelen,
4184 int8_t tinyid, jsval value,
4185 JSPropertyOp getter, JSStrictPropertyOp setter,
4186 unsigned attrs);
4188 extern JS_PUBLIC_API(JSBool)
4189 JS_AlreadyHasOwnUCProperty(JSContext *cx, JSObject *obj, const jschar *name,
4190 size_t namelen, JSBool *foundp);
4192 extern JS_PUBLIC_API(JSBool)
4193 JS_HasUCProperty(JSContext *cx, JSObject *obj,
4194 const jschar *name, size_t namelen,
4195 JSBool *vp);
4197 extern JS_PUBLIC_API(JSBool)
4198 JS_LookupUCProperty(JSContext *cx, JSObject *obj,
4199 const jschar *name, size_t namelen,
4200 jsval *vp);
4202 extern JS_PUBLIC_API(JSBool)
4203 JS_GetUCProperty(JSContext *cx, JSObject *obj,
4204 const jschar *name, size_t namelen,
4205 jsval *vp);
4207 extern JS_PUBLIC_API(JSBool)
4208 JS_SetUCProperty(JSContext *cx, JSObject *obj,
4209 const jschar *name, size_t namelen,
4210 jsval *vp);
4212 extern JS_PUBLIC_API(JSBool)
4213 JS_DeleteUCProperty2(JSContext *cx, JSObject *obj,
4214 const jschar *name, size_t namelen,
4215 jsval *rval);
4217 extern JS_PUBLIC_API(JSObject *)
4218 JS_NewArrayObject(JSContext *cx, int length, jsval *vector);
4220 extern JS_PUBLIC_API(JSBool)
4221 JS_IsArrayObject(JSContext *cx, JSObject *obj);
4223 extern JS_PUBLIC_API(JSBool)
4224 JS_GetArrayLength(JSContext *cx, JSObject *obj, uint32_t *lengthp);
4226 extern JS_PUBLIC_API(JSBool)
4227 JS_SetArrayLength(JSContext *cx, JSObject *obj, uint32_t length);
4229 extern JS_PUBLIC_API(JSBool)
4230 JS_DefineElement(JSContext *cx, JSObject *obj, uint32_t index, jsval value,
4231 JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs);
4233 extern JS_PUBLIC_API(JSBool)
4234 JS_AlreadyHasOwnElement(JSContext *cx, JSObject *obj, uint32_t index, JSBool *foundp);
4236 extern JS_PUBLIC_API(JSBool)
4237 JS_HasElement(JSContext *cx, JSObject *obj, uint32_t index, JSBool *foundp);
4239 extern JS_PUBLIC_API(JSBool)
4240 JS_LookupElement(JSContext *cx, JSObject *obj, uint32_t index, jsval *vp);
4242 extern JS_PUBLIC_API(JSBool)
4243 JS_GetElement(JSContext *cx, JSObject *obj, uint32_t index, jsval *vp);
4245 extern JS_PUBLIC_API(JSBool)
4246 JS_ForwardGetElementTo(JSContext *cx, JSObject *obj, uint32_t index, JSObject *onBehalfOf,
4247 jsval *vp);
4250 * Get the property with name given by |index|, if it has one. If
4251 * not, |*present| will be set to false and the value of |vp| must not
4252 * be relied on.
4254 extern JS_PUBLIC_API(JSBool)
4255 JS_GetElementIfPresent(JSContext *cx, JSObject *obj, uint32_t index, JSObject *onBehalfOf,
4256 jsval *vp, JSBool* present);
4258 extern JS_PUBLIC_API(JSBool)
4259 JS_SetElement(JSContext *cx, JSObject *obj, uint32_t index, jsval *vp);
4261 extern JS_PUBLIC_API(JSBool)
4262 JS_DeleteElement(JSContext *cx, JSObject *obj, uint32_t index);
4264 extern JS_PUBLIC_API(JSBool)
4265 JS_DeleteElement2(JSContext *cx, JSObject *obj, uint32_t index, jsval *rval);
4267 extern JS_PUBLIC_API(void)
4268 JS_ClearScope(JSContext *cx, JSObject *obj);
4270 extern JS_PUBLIC_API(JSIdArray *)
4271 JS_Enumerate(JSContext *cx, JSObject *obj);
4274 * Create an object to iterate over enumerable properties of obj, in arbitrary
4275 * property definition order. NB: This differs from longstanding for..in loop
4276 * order, which uses order of property definition in obj.
4278 extern JS_PUBLIC_API(JSObject *)
4279 JS_NewPropertyIterator(JSContext *cx, JSObject *obj);
4282 * Return true on success with *idp containing the id of the next enumerable
4283 * property to visit using iterobj, or JSID_IS_VOID if there is no such property
4284 * left to visit. Return false on error.
4286 extern JS_PUBLIC_API(JSBool)
4287 JS_NextProperty(JSContext *cx, JSObject *iterobj, jsid *idp);
4290 * Create an object to iterate over the elements of obj in for-of order. This
4291 * can be used to implement the iteratorObject hook for an array-like Class.
4293 extern JS_PUBLIC_API(JSObject *)
4294 JS_NewElementIterator(JSContext *cx, JSObject *obj);
4297 * To make your array-like class iterable using the for-of loop, set the
4298 * JSCLASS_FOR_OF_ITERATION bit in the class's flags field and set its
4299 * .ext.iteratorObject hook to this function.
4301 extern JS_PUBLIC_API(JSObject *)
4302 JS_ElementIteratorStub(JSContext *cx, JSObject *obj, JSBool keysonly);
4304 extern JS_PUBLIC_API(JSBool)
4305 JS_CheckAccess(JSContext *cx, JSObject *obj, jsid id, JSAccessMode mode,
4306 jsval *vp, unsigned *attrsp);
4308 extern JS_PUBLIC_API(jsval)
4309 JS_GetReservedSlot(JSObject *obj, uint32_t index);
4311 extern JS_PUBLIC_API(void)
4312 JS_SetReservedSlot(JSObject *obj, uint32_t index, jsval v);
4314 /************************************************************************/
4317 * Security protocol.
4319 struct JSPrincipals {
4320 /* Don't call "destroy"; use reference counting macros below. */
4321 int refcount;
4323 #ifdef DEBUG
4324 /* A helper to facilitate principals debugging. */
4325 uint32_t debugToken;
4326 #endif
4328 #ifdef __cplusplus
4329 void setDebugToken(uint32_t token) {
4330 # ifdef DEBUG
4331 debugToken = token;
4332 # endif
4336 * This is not defined by the JS engine but should be provided by the
4337 * embedding.
4339 JS_PUBLIC_API(void) dump();
4340 #endif
4343 extern JS_PUBLIC_API(void)
4344 JS_HoldPrincipals(JSPrincipals *principals);
4346 extern JS_PUBLIC_API(void)
4347 JS_DropPrincipals(JSRuntime *rt, JSPrincipals *principals);
4349 struct JSSecurityCallbacks {
4350 JSCheckAccessOp checkObjectAccess;
4351 JSSubsumePrincipalsOp subsumePrincipals;
4352 JSObjectPrincipalsFinder findObjectPrincipals;
4353 JSCSPEvalChecker contentSecurityPolicyAllows;
4354 JSPushContextPrincipalOp pushContextPrincipal;
4355 JSPopContextPrincipalOp popContextPrincipal;
4358 extern JS_PUBLIC_API(void)
4359 JS_SetSecurityCallbacks(JSRuntime *rt, const JSSecurityCallbacks *callbacks);
4361 extern JS_PUBLIC_API(const JSSecurityCallbacks *)
4362 JS_GetSecurityCallbacks(JSRuntime *rt);
4365 * Code running with "trusted" principals will be given a deeper stack
4366 * allocation than ordinary scripts. This allows trusted script to run after
4367 * untrusted script has exhausted the stack. This function sets the
4368 * runtime-wide trusted principal.
4370 * This principals is not held (via JS_HoldPrincipals/JS_DropPrincipals) since
4371 * there is no available JSContext. Instead, the caller must ensure that the
4372 * given principals stays valid for as long as 'rt' may point to it. If the
4373 * principals would be destroyed before 'rt', JS_SetTrustedPrincipals must be
4374 * called again, passing NULL for 'prin'.
4376 extern JS_PUBLIC_API(void)
4377 JS_SetTrustedPrincipals(JSRuntime *rt, JSPrincipals *prin);
4380 * Initialize the callback that is called to destroy JSPrincipals instance
4381 * when its reference counter drops to zero. The initialization can be done
4382 * only once per JS runtime.
4384 extern JS_PUBLIC_API(void)
4385 JS_InitDestroyPrincipalsCallback(JSRuntime *rt, JSDestroyPrincipalsOp destroyPrincipals);
4387 /************************************************************************/
4390 * Functions and scripts.
4392 extern JS_PUBLIC_API(JSFunction *)
4393 JS_NewFunction(JSContext *cx, JSNative call, unsigned nargs, unsigned flags,
4394 JSObject *parent, const char *name);
4397 * Create the function with the name given by the id. JSID_IS_STRING(id) must
4398 * be true.
4400 extern JS_PUBLIC_API(JSFunction *)
4401 JS_NewFunctionById(JSContext *cx, JSNative call, unsigned nargs, unsigned flags,
4402 JSObject *parent, jsid id);
4404 extern JS_PUBLIC_API(JSObject *)
4405 JS_GetFunctionObject(JSFunction *fun);
4408 * Return the function's identifier as a JSString, or null if fun is unnamed.
4409 * The returned string lives as long as fun, so you don't need to root a saved
4410 * reference to it if fun is well-connected or rooted, and provided you bound
4411 * the use of the saved reference by fun's lifetime.
4413 extern JS_PUBLIC_API(JSString *)
4414 JS_GetFunctionId(JSFunction *fun);
4417 * Return JSFUN_* flags for fun.
4419 extern JS_PUBLIC_API(unsigned)
4420 JS_GetFunctionFlags(JSFunction *fun);
4423 * Return the arity (length) of fun.
4425 extern JS_PUBLIC_API(uint16_t)
4426 JS_GetFunctionArity(JSFunction *fun);
4429 * Infallible predicate to test whether obj is a function object (faster than
4430 * comparing obj's class name to "Function", but equivalent unless someone has
4431 * overwritten the "Function" identifier with a different constructor and then
4432 * created instances using that constructor that might be passed in as obj).
4434 extern JS_PUBLIC_API(JSBool)
4435 JS_ObjectIsFunction(JSContext *cx, JSObject *obj);
4437 extern JS_PUBLIC_API(JSBool)
4438 JS_ObjectIsCallable(JSContext *cx, JSObject *obj);
4440 extern JS_PUBLIC_API(JSBool)
4441 JS_IsNativeFunction(JSObject *funobj, JSNative call);
4444 * Bind the given callable to use the given object as "this".
4446 * If |callable| is not callable, will throw and return NULL.
4448 extern JS_PUBLIC_API(JSObject*)
4449 JS_BindCallable(JSContext *cx, JSObject *callable, JSObject *newThis);
4451 extern JS_PUBLIC_API(JSBool)
4452 JS_DefineFunctions(JSContext *cx, JSObject *obj, JSFunctionSpec *fs);
4454 extern JS_PUBLIC_API(JSFunction *)
4455 JS_DefineFunction(JSContext *cx, JSObject *obj, const char *name, JSNative call,
4456 unsigned nargs, unsigned attrs);
4458 extern JS_PUBLIC_API(JSFunction *)
4459 JS_DefineUCFunction(JSContext *cx, JSObject *obj,
4460 const jschar *name, size_t namelen, JSNative call,
4461 unsigned nargs, unsigned attrs);
4463 extern JS_PUBLIC_API(JSFunction *)
4464 JS_DefineFunctionById(JSContext *cx, JSObject *obj, jsid id, JSNative call,
4465 unsigned nargs, unsigned attrs);
4467 extern JS_PUBLIC_API(JSObject *)
4468 JS_CloneFunctionObject(JSContext *cx, JSObject *funobj, JSObject *parent);
4471 * Given a buffer, return JS_FALSE if the buffer might become a valid
4472 * javascript statement with the addition of more lines. Otherwise return
4473 * JS_TRUE. The intent is to support interactive compilation - accumulate
4474 * lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to
4475 * the compiler.
4477 extern JS_PUBLIC_API(JSBool)
4478 JS_BufferIsCompilableUnit(JSContext *cx, JSBool bytes_are_utf8,
4479 JSObject *obj, const char *bytes, size_t length);
4481 extern JS_PUBLIC_API(JSScript *)
4482 JS_CompileScript(JSContext *cx, JSObject *obj,
4483 const char *bytes, size_t length,
4484 const char *filename, unsigned lineno);
4486 extern JS_PUBLIC_API(JSScript *)
4487 JS_CompileScriptForPrincipals(JSContext *cx, JSObject *obj,
4488 JSPrincipals *principals,
4489 const char *bytes, size_t length,
4490 const char *filename, unsigned lineno);
4492 extern JS_PUBLIC_API(JSScript *)
4493 JS_CompileScriptForPrincipalsVersion(JSContext *cx, JSObject *obj,
4494 JSPrincipals *principals,
4495 const char *bytes, size_t length,
4496 const char *filename, unsigned lineno,
4497 JSVersion version);
4499 extern JS_PUBLIC_API(JSScript *)
4500 JS_CompileUCScript(JSContext *cx, JSObject *obj,
4501 const jschar *chars, size_t length,
4502 const char *filename, unsigned lineno);
4504 extern JS_PUBLIC_API(JSScript *)
4505 JS_CompileUCScriptForPrincipals(JSContext *cx, JSObject *obj,
4506 JSPrincipals *principals,
4507 const jschar *chars, size_t length,
4508 const char *filename, unsigned lineno);
4510 extern JS_PUBLIC_API(JSScript *)
4511 JS_CompileUCScriptForPrincipalsVersion(JSContext *cx, JSObject *obj,
4512 JSPrincipals *principals,
4513 const jschar *chars, size_t length,
4514 const char *filename, unsigned lineno,
4515 JSVersion version);
4517 * If originPrincipals is null, then the value of principals is used as origin
4518 * principals for the compiled script.
4520 extern JS_PUBLIC_API(JSScript *)
4521 JS_CompileUCScriptForPrincipalsVersionOrigin(JSContext *cx, JSObject *obj,
4522 JSPrincipals *principals,
4523 JSPrincipals *originPrincipals,
4524 const jschar *chars, size_t length,
4525 const char *filename, unsigned lineno,
4526 JSVersion version);
4528 extern JS_PUBLIC_API(JSScript *)
4529 JS_CompileUTF8File(JSContext *cx, JSObject *obj, const char *filename);
4531 extern JS_PUBLIC_API(JSScript *)
4532 JS_CompileUTF8FileHandle(JSContext *cx, JSObject *obj, const char *filename,
4533 FILE *fh);
4535 extern JS_PUBLIC_API(JSScript *)
4536 JS_CompileUTF8FileHandleForPrincipals(JSContext *cx, JSObject *obj,
4537 const char *filename, FILE *fh,
4538 JSPrincipals *principals);
4540 extern JS_PUBLIC_API(JSScript *)
4541 JS_CompileUTF8FileHandleForPrincipalsVersion(JSContext *cx, JSObject *obj,
4542 const char *filename, FILE *fh,
4543 JSPrincipals *principals,
4544 JSVersion version);
4546 extern JS_PUBLIC_API(JSObject *)
4547 JS_GetGlobalFromScript(JSScript *script);
4549 extern JS_PUBLIC_API(JSFunction *)
4550 JS_CompileFunction(JSContext *cx, JSObject *obj, const char *name,
4551 unsigned nargs, const char **argnames,
4552 const char *bytes, size_t length,
4553 const char *filename, unsigned lineno);
4555 extern JS_PUBLIC_API(JSFunction *)
4556 JS_CompileFunctionForPrincipals(JSContext *cx, JSObject *obj,
4557 JSPrincipals *principals, const char *name,
4558 unsigned nargs, const char **argnames,
4559 const char *bytes, size_t length,
4560 const char *filename, unsigned lineno);
4562 extern JS_PUBLIC_API(JSFunction *)
4563 JS_CompileUCFunction(JSContext *cx, JSObject *obj, const char *name,
4564 unsigned nargs, const char **argnames,
4565 const jschar *chars, size_t length,
4566 const char *filename, unsigned lineno);
4568 extern JS_PUBLIC_API(JSFunction *)
4569 JS_CompileUCFunctionForPrincipals(JSContext *cx, JSObject *obj,
4570 JSPrincipals *principals, const char *name,
4571 unsigned nargs, const char **argnames,
4572 const jschar *chars, size_t length,
4573 const char *filename, unsigned lineno);
4575 extern JS_PUBLIC_API(JSFunction *)
4576 JS_CompileUCFunctionForPrincipalsVersion(JSContext *cx, JSObject *obj,
4577 JSPrincipals *principals, const char *name,
4578 unsigned nargs, const char **argnames,
4579 const jschar *chars, size_t length,
4580 const char *filename, unsigned lineno,
4581 JSVersion version);
4583 extern JS_PUBLIC_API(JSString *)
4584 JS_DecompileScript(JSContext *cx, JSScript *script, const char *name, unsigned indent);
4587 * API extension: OR this into indent to avoid pretty-printing the decompiled
4588 * source resulting from JS_DecompileFunction{,Body}.
4590 #define JS_DONT_PRETTY_PRINT ((unsigned)0x8000)
4592 extern JS_PUBLIC_API(JSString *)
4593 JS_DecompileFunction(JSContext *cx, JSFunction *fun, unsigned indent);
4595 extern JS_PUBLIC_API(JSString *)
4596 JS_DecompileFunctionBody(JSContext *cx, JSFunction *fun, unsigned indent);
4599 * NB: JS_ExecuteScript and the JS_Evaluate*Script* quadruplets use the obj
4600 * parameter as the initial scope chain header, the 'this' keyword value, and
4601 * the variables object (ECMA parlance for where 'var' and 'function' bind
4602 * names) of the execution context for script.
4604 * Using obj as the variables object is problematic if obj's parent (which is
4605 * the scope chain link; see JS_SetParent and JS_NewObject) is not null: in
4606 * this case, variables created by 'var x = 0', e.g., go in obj, but variables
4607 * created by assignment to an unbound id, 'x = 0', go in the last object on
4608 * the scope chain linked by parent.
4610 * ECMA calls that last scoping object the "global object", but note that many
4611 * embeddings have several such objects. ECMA requires that "global code" be
4612 * executed with the variables object equal to this global object. But these
4613 * JS API entry points provide freedom to execute code against a "sub-global",
4614 * i.e., a parented or scoped object, in which case the variables object will
4615 * differ from the last object on the scope chain, resulting in confusing and
4616 * non-ECMA explicit vs. implicit variable creation.
4618 * Caveat embedders: unless you already depend on this buggy variables object
4619 * binding behavior, you should call JS_SetOptions(cx, JSOPTION_VAROBJFIX) or
4620 * JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_VAROBJFIX) -- the latter if
4621 * someone may have set other options on cx already -- for each context in the
4622 * application, if you pass parented objects as the obj parameter, or may ever
4623 * pass such objects in the future.
4625 * Why a runtime option? The alternative is to add six or so new API entry
4626 * points with signatures matching the following six, and that doesn't seem
4627 * worth the code bloat cost. Such new entry points would probably have less
4628 * obvious names, too, so would not tend to be used. The JS_SetOption call,
4629 * OTOH, can be more easily hacked into existing code that does not depend on
4630 * the bug; such code can continue to use the familiar JS_EvaluateScript,
4631 * etc., entry points.
4633 extern JS_PUBLIC_API(JSBool)
4634 JS_ExecuteScript(JSContext *cx, JSObject *obj, JSScript *script, jsval *rval);
4636 extern JS_PUBLIC_API(JSBool)
4637 JS_ExecuteScriptVersion(JSContext *cx, JSObject *obj, JSScript *script, jsval *rval,
4638 JSVersion version);
4641 * Execute either the function-defining prolog of a script, or the script's
4642 * main body, but not both.
4644 typedef enum JSExecPart { JSEXEC_PROLOG, JSEXEC_MAIN } JSExecPart;
4646 extern JS_PUBLIC_API(JSBool)
4647 JS_EvaluateScript(JSContext *cx, JSObject *obj,
4648 const char *bytes, unsigned length,
4649 const char *filename, unsigned lineno,
4650 jsval *rval);
4652 extern JS_PUBLIC_API(JSBool)
4653 JS_EvaluateScriptForPrincipals(JSContext *cx, JSObject *obj,
4654 JSPrincipals *principals,
4655 const char *bytes, unsigned length,
4656 const char *filename, unsigned lineno,
4657 jsval *rval);
4659 extern JS_PUBLIC_API(JSBool)
4660 JS_EvaluateScriptForPrincipalsVersion(JSContext *cx, JSObject *obj,
4661 JSPrincipals *principals,
4662 const char *bytes, unsigned length,
4663 const char *filename, unsigned lineno,
4664 jsval *rval, JSVersion version);
4666 extern JS_PUBLIC_API(JSBool)
4667 JS_EvaluateUCScript(JSContext *cx, JSObject *obj,
4668 const jschar *chars, unsigned length,
4669 const char *filename, unsigned lineno,
4670 jsval *rval);
4672 extern JS_PUBLIC_API(JSBool)
4673 JS_EvaluateUCScriptForPrincipals(JSContext *cx, JSObject *obj,
4674 JSPrincipals *principals,
4675 const jschar *chars, unsigned length,
4676 const char *filename, unsigned lineno,
4677 jsval *rval);
4679 extern JS_PUBLIC_API(JSBool)
4680 JS_EvaluateUCScriptForPrincipalsVersion(JSContext *cx, JSObject *obj,
4681 JSPrincipals *principals,
4682 const jschar *chars, unsigned length,
4683 const char *filename, unsigned lineno,
4684 jsval *rval, JSVersion version);
4687 * JSAPI clients may optionally specify the 'originPrincipals' of a script.
4688 * A script's originPrincipals may be retrieved through the debug API (via
4689 * JS_GetScriptOriginPrincipals) and the originPrincipals are transitively
4690 * assigned to any nested scripts (including scripts dynamically created via
4691 * eval and the Function constructor). If originPrincipals is null, then the
4692 * value of principals is used as origin principals for the script.
4694 extern JS_PUBLIC_API(JSBool)
4695 JS_EvaluateUCScriptForPrincipalsVersionOrigin(JSContext *cx, JSObject *obj,
4696 JSPrincipals *principals,
4697 JSPrincipals *originPrincipals,
4698 const jschar *chars, unsigned length,
4699 const char *filename, unsigned lineno,
4700 jsval *rval, JSVersion version);
4702 extern JS_PUBLIC_API(JSBool)
4703 JS_CallFunction(JSContext *cx, JSObject *obj, JSFunction *fun, unsigned argc,
4704 jsval *argv, jsval *rval);
4706 extern JS_PUBLIC_API(JSBool)
4707 JS_CallFunctionName(JSContext *cx, JSObject *obj, const char *name, unsigned argc,
4708 jsval *argv, jsval *rval);
4710 extern JS_PUBLIC_API(JSBool)
4711 JS_CallFunctionValue(JSContext *cx, JSObject *obj, jsval fval, unsigned argc,
4712 jsval *argv, jsval *rval);
4714 #ifdef __cplusplus
4715 JS_END_EXTERN_C
4717 namespace JS {
4719 static inline bool
4720 Call(JSContext *cx, JSObject *thisObj, JSFunction *fun, unsigned argc, jsval *argv, jsval *rval) {
4721 return !!JS_CallFunction(cx, thisObj, fun, argc, argv, rval);
4724 static inline bool
4725 Call(JSContext *cx, JSObject *thisObj, const char *name, unsigned argc, jsval *argv, jsval *rval) {
4726 return !!JS_CallFunctionName(cx, thisObj, name, argc, argv, rval);
4729 static inline bool
4730 Call(JSContext *cx, JSObject *thisObj, jsval fun, unsigned argc, jsval *argv, jsval *rval) {
4731 return !!JS_CallFunctionValue(cx, thisObj, fun, argc, argv, rval);
4734 extern JS_PUBLIC_API(bool)
4735 Call(JSContext *cx, jsval thisv, jsval fun, unsigned argc, jsval *argv, jsval *rval);
4737 static inline bool
4738 Call(JSContext *cx, jsval thisv, JSObject *funObj, unsigned argc, jsval *argv, jsval *rval) {
4739 return Call(cx, thisv, OBJECT_TO_JSVAL(funObj), argc, argv, rval);
4742 } /* namespace JS */
4744 JS_BEGIN_EXTERN_C
4745 #endif /* __cplusplus */
4748 * These functions allow setting an operation callback that will be called
4749 * from the JS thread some time after any thread triggered the callback using
4750 * JS_TriggerOperationCallback(rt).
4752 * To schedule the GC and for other activities the engine internally triggers
4753 * operation callbacks. The embedding should thus not rely on callbacks being
4754 * triggered through the external API only.
4756 * Important note: Additional callbacks can occur inside the callback handler
4757 * if it re-enters the JS engine. The embedding must ensure that the callback
4758 * is disconnected before attempting such re-entry.
4760 extern JS_PUBLIC_API(JSOperationCallback)
4761 JS_SetOperationCallback(JSContext *cx, JSOperationCallback callback);
4763 extern JS_PUBLIC_API(JSOperationCallback)
4764 JS_GetOperationCallback(JSContext *cx);
4766 extern JS_PUBLIC_API(void)
4767 JS_TriggerOperationCallback(JSRuntime *rt);
4769 extern JS_PUBLIC_API(JSBool)
4770 JS_IsRunning(JSContext *cx);
4773 * Saving and restoring frame chains.
4775 * These two functions are used to set aside cx's call stack while that stack
4776 * is inactive. After a call to JS_SaveFrameChain, it looks as if there is no
4777 * code running on cx. Before calling JS_RestoreFrameChain, cx's call stack
4778 * must be balanced and all nested calls to JS_SaveFrameChain must have had
4779 * matching JS_RestoreFrameChain calls.
4781 * JS_SaveFrameChain deals with cx not having any code running on it.
4783 extern JS_PUBLIC_API(JSBool)
4784 JS_SaveFrameChain(JSContext *cx);
4786 extern JS_PUBLIC_API(void)
4787 JS_RestoreFrameChain(JSContext *cx);
4789 #ifdef MOZ_TRACE_JSCALLS
4791 * The callback is expected to be quick and noninvasive. It should not
4792 * trigger interrupts, turn on debugging, or produce uncaught JS
4793 * exceptions. The state of the stack and registers in the context
4794 * cannot be relied upon, since this callback may be invoked directly
4795 * from either JIT. The 'entering' field means we are entering a
4796 * function if it is positive, leaving a function if it is zero or
4797 * negative.
4799 extern JS_PUBLIC_API(void)
4800 JS_SetFunctionCallback(JSContext *cx, JSFunctionCallback fcb);
4802 extern JS_PUBLIC_API(JSFunctionCallback)
4803 JS_GetFunctionCallback(JSContext *cx);
4804 #endif /* MOZ_TRACE_JSCALLS */
4806 /************************************************************************/
4809 * Strings.
4811 * NB: JS_NewUCString takes ownership of bytes on success, avoiding a copy;
4812 * but on error (signified by null return), it leaves chars owned by the
4813 * caller. So the caller must free bytes in the error case, if it has no use
4814 * for them. In contrast, all the JS_New*StringCopy* functions do not take
4815 * ownership of the character memory passed to them -- they copy it.
4817 extern JS_PUBLIC_API(JSString *)
4818 JS_NewStringCopyN(JSContext *cx, const char *s, size_t n);
4820 extern JS_PUBLIC_API(JSString *)
4821 JS_NewStringCopyZ(JSContext *cx, const char *s);
4823 extern JS_PUBLIC_API(JSString *)
4824 JS_InternJSString(JSContext *cx, JSString *str);
4826 extern JS_PUBLIC_API(JSString *)
4827 JS_InternString(JSContext *cx, const char *s);
4829 extern JS_PUBLIC_API(JSString *)
4830 JS_NewUCString(JSContext *cx, jschar *chars, size_t length);
4832 extern JS_PUBLIC_API(JSString *)
4833 JS_NewUCStringCopyN(JSContext *cx, const jschar *s, size_t n);
4835 extern JS_PUBLIC_API(JSString *)
4836 JS_NewUCStringCopyZ(JSContext *cx, const jschar *s);
4838 extern JS_PUBLIC_API(JSString *)
4839 JS_InternUCStringN(JSContext *cx, const jschar *s, size_t length);
4841 extern JS_PUBLIC_API(JSString *)
4842 JS_InternUCString(JSContext *cx, const jschar *s);
4844 extern JS_PUBLIC_API(JSBool)
4845 JS_CompareStrings(JSContext *cx, JSString *str1, JSString *str2, int32_t *result);
4847 extern JS_PUBLIC_API(JSBool)
4848 JS_StringEqualsAscii(JSContext *cx, JSString *str, const char *asciiBytes, JSBool *match);
4850 extern JS_PUBLIC_API(size_t)
4851 JS_PutEscapedString(JSContext *cx, char *buffer, size_t size, JSString *str, char quote);
4853 extern JS_PUBLIC_API(JSBool)
4854 JS_FileEscapedString(FILE *fp, JSString *str, char quote);
4857 * Extracting string characters and length.
4859 * While getting the length of a string is infallible, getting the chars can
4860 * fail. As indicated by the lack of a JSContext parameter, there are two
4861 * special cases where getting the chars is infallible:
4863 * The first case is interned strings, i.e., strings from JS_InternString or
4864 * JSID_TO_STRING(id), using JS_GetInternedStringChars*.
4866 * The second case is "flat" strings that have been explicitly prepared in a
4867 * fallible context by JS_FlattenString. To catch errors, a separate opaque
4868 * JSFlatString type is returned by JS_FlattenString and expected by
4869 * JS_GetFlatStringChars. Note, though, that this is purely a syntactic
4870 * distinction: the input and output of JS_FlattenString are the same actual
4871 * GC-thing so only one needs to be rooted. If a JSString is known to be flat,
4872 * JS_ASSERT_STRING_IS_FLAT can be used to make a debug-checked cast. Example:
4874 * // in a fallible context
4875 * JSFlatString *fstr = JS_FlattenString(cx, str);
4876 * if (!fstr)
4877 * return JS_FALSE;
4878 * JS_ASSERT(fstr == JS_ASSERT_STRING_IS_FLAT(str));
4880 * // in an infallible context, for the same 'str'
4881 * const jschar *chars = JS_GetFlatStringChars(fstr)
4882 * JS_ASSERT(chars);
4884 * The CharsZ APIs guarantee that the returned array has a null character at
4885 * chars[length]. This can require additional copying so clients should prefer
4886 * APIs without CharsZ if possible. The infallible functions also return
4887 * null-terminated arrays. (There is no additional cost or non-Z alternative
4888 * for the infallible functions, so 'Z' is left out of the identifier.)
4891 extern JS_PUBLIC_API(size_t)
4892 JS_GetStringLength(JSString *str);
4894 extern JS_PUBLIC_API(const jschar *)
4895 JS_GetStringCharsAndLength(JSContext *cx, JSString *str, size_t *length);
4897 extern JS_PUBLIC_API(const jschar *)
4898 JS_GetInternedStringChars(JSString *str);
4900 extern JS_PUBLIC_API(const jschar *)
4901 JS_GetInternedStringCharsAndLength(JSString *str, size_t *length);
4903 extern JS_PUBLIC_API(const jschar *)
4904 JS_GetStringCharsZ(JSContext *cx, JSString *str);
4906 extern JS_PUBLIC_API(const jschar *)
4907 JS_GetStringCharsZAndLength(JSContext *cx, JSString *str, size_t *length);
4909 extern JS_PUBLIC_API(JSFlatString *)
4910 JS_FlattenString(JSContext *cx, JSString *str);
4912 extern JS_PUBLIC_API(const jschar *)
4913 JS_GetFlatStringChars(JSFlatString *str);
4915 static JS_ALWAYS_INLINE JSFlatString *
4916 JSID_TO_FLAT_STRING(jsid id)
4918 JS_ASSERT(JSID_IS_STRING(id));
4919 return (JSFlatString *)(JSID_BITS(id));
4922 static JS_ALWAYS_INLINE JSFlatString *
4923 JS_ASSERT_STRING_IS_FLAT(JSString *str)
4925 JS_ASSERT(JS_GetFlatStringChars((JSFlatString *)str));
4926 return (JSFlatString *)str;
4929 static JS_ALWAYS_INLINE JSString *
4930 JS_FORGET_STRING_FLATNESS(JSFlatString *fstr)
4932 return (JSString *)fstr;
4936 * Additional APIs that avoid fallibility when given a flat string.
4939 extern JS_PUBLIC_API(JSBool)
4940 JS_FlatStringEqualsAscii(JSFlatString *str, const char *asciiBytes);
4942 extern JS_PUBLIC_API(size_t)
4943 JS_PutEscapedFlatString(char *buffer, size_t size, JSFlatString *str, char quote);
4946 * This function is now obsolete and behaves the same as JS_NewUCString. Use
4947 * JS_NewUCString instead.
4949 extern JS_PUBLIC_API(JSString *)
4950 JS_NewGrowableString(JSContext *cx, jschar *chars, size_t length);
4953 * Mutable string support. A string's characters are never mutable in this JS
4954 * implementation, but a dependent string is a substring of another dependent
4955 * or immutable string, and a rope is a lazily concatenated string that creates
4956 * its underlying buffer the first time it is accessed. Even after a rope
4957 * creates its underlying buffer, it still considered mutable. The direct data
4958 * members of the (opaque to API clients) JSString struct may be changed in a
4959 * single-threaded way for dependent strings and ropes.
4961 * Therefore mutable strings (ropes and dependent strings) cannot be used by
4962 * more than one thread at a time. You may call JS_MakeStringImmutable to
4963 * convert the string from a mutable string to an immutable (and therefore
4964 * thread-safe) string. The engine takes care of converting ropes and dependent
4965 * strings to immutable for you if you store strings in multi-threaded objects
4966 * using JS_SetProperty or kindred API entry points.
4968 * If you store a JSString pointer in a native data structure that is (safely)
4969 * accessible to multiple threads, you must call JS_MakeStringImmutable before
4970 * retiring the store.
4974 * Create a dependent string, i.e., a string that owns no character storage,
4975 * but that refers to a slice of another string's chars. Dependent strings
4976 * are mutable by definition, so the thread safety comments above apply.
4978 extern JS_PUBLIC_API(JSString *)
4979 JS_NewDependentString(JSContext *cx, JSString *str, size_t start,
4980 size_t length);
4983 * Concatenate two strings, possibly resulting in a rope.
4984 * See above for thread safety comments.
4986 extern JS_PUBLIC_API(JSString *)
4987 JS_ConcatStrings(JSContext *cx, JSString *left, JSString *right);
4990 * Convert a dependent string into an independent one. This function does not
4991 * change the string's mutability, so the thread safety comments above apply.
4993 extern JS_PUBLIC_API(const jschar *)
4994 JS_UndependString(JSContext *cx, JSString *str);
4997 * Convert a mutable string (either rope or dependent) into an immutable,
4998 * thread-safe one.
5000 extern JS_PUBLIC_API(JSBool)
5001 JS_MakeStringImmutable(JSContext *cx, JSString *str);
5004 * Return JS_TRUE if C (char []) strings passed via the API and internally
5005 * are UTF-8.
5007 JS_PUBLIC_API(JSBool)
5008 JS_CStringsAreUTF8(void);
5011 * Update the value to be returned by JS_CStringsAreUTF8(). Once set, it
5012 * can never be changed. This API must be called before the first call to
5013 * JS_NewRuntime.
5015 JS_PUBLIC_API(void)
5016 JS_SetCStringsAreUTF8(void);
5019 * Character encoding support.
5021 * For both JS_EncodeCharacters and JS_DecodeBytes, set *dstlenp to the size
5022 * of the destination buffer before the call; on return, *dstlenp contains the
5023 * number of bytes (JS_EncodeCharacters) or jschars (JS_DecodeBytes) actually
5024 * stored. To determine the necessary destination buffer size, make a sizing
5025 * call that passes NULL for dst.
5027 * On errors, the functions report the error. In that case, *dstlenp contains
5028 * the number of characters or bytes transferred so far. If cx is NULL, no
5029 * error is reported on failure, and the functions simply return JS_FALSE.
5031 * NB: Neither function stores an additional zero byte or jschar after the
5032 * transcoded string.
5034 * If JS_CStringsAreUTF8() is true then JS_EncodeCharacters encodes to
5035 * UTF-8, and JS_DecodeBytes decodes from UTF-8, which may create additional
5036 * errors if the character sequence is malformed. If UTF-8 support is
5037 * disabled, the functions deflate and inflate, respectively.
5039 * JS_DecodeUTF8() always behaves the same independently of JS_CStringsAreUTF8().
5041 JS_PUBLIC_API(JSBool)
5042 JS_EncodeCharacters(JSContext *cx, const jschar *src, size_t srclen, char *dst,
5043 size_t *dstlenp);
5045 JS_PUBLIC_API(JSBool)
5046 JS_DecodeBytes(JSContext *cx, const char *src, size_t srclen, jschar *dst,
5047 size_t *dstlenp);
5049 JS_PUBLIC_API(JSBool)
5050 JS_DecodeUTF8(JSContext *cx, const char *src, size_t srclen, jschar *dst,
5051 size_t *dstlenp);
5054 * A variation on JS_EncodeCharacters where a null terminated string is
5055 * returned that you are expected to call JS_free on when done.
5057 JS_PUBLIC_API(char *)
5058 JS_EncodeString(JSContext *cx, JSString *str);
5061 * Get number of bytes in the string encoding (without accounting for a
5062 * terminating zero bytes. The function returns (size_t) -1 if the string
5063 * can not be encoded into bytes and reports an error using cx accordingly.
5065 JS_PUBLIC_API(size_t)
5066 JS_GetStringEncodingLength(JSContext *cx, JSString *str);
5069 * Encode string into a buffer. The function does not stores an additional
5070 * zero byte. The function returns (size_t) -1 if the string can not be
5071 * encoded into bytes with no error reported. Otherwise it returns the number
5072 * of bytes that are necessary to encode the string. If that exceeds the
5073 * length parameter, the string will be cut and only length bytes will be
5074 * written into the buffer.
5076 * If JS_CStringsAreUTF8() is true, the string does not fit into the buffer
5077 * and the the first length bytes ends in the middle of utf-8 encoding for
5078 * some character, then such partial utf-8 encoding is replaced by zero bytes.
5079 * This way the result always represents the valid UTF-8 sequence.
5081 JS_PUBLIC_API(size_t)
5082 JS_EncodeStringToBuffer(JSString *str, char *buffer, size_t length);
5084 #ifdef __cplusplus
5086 class JSAutoByteString {
5087 public:
5088 JSAutoByteString(JSContext *cx, JSString *str JS_GUARD_OBJECT_NOTIFIER_PARAM)
5089 : mBytes(JS_EncodeString(cx, str)) {
5090 JS_ASSERT(cx);
5091 JS_GUARD_OBJECT_NOTIFIER_INIT;
5094 JSAutoByteString(JS_GUARD_OBJECT_NOTIFIER_PARAM0)
5095 : mBytes(NULL) {
5096 JS_GUARD_OBJECT_NOTIFIER_INIT;
5099 ~JSAutoByteString() {
5100 js::UnwantedForeground::free_(mBytes);
5103 /* Take ownership of the given byte array. */
5104 void initBytes(char *bytes) {
5105 JS_ASSERT(!mBytes);
5106 mBytes = bytes;
5109 char *encode(JSContext *cx, JSString *str) {
5110 JS_ASSERT(!mBytes);
5111 JS_ASSERT(cx);
5112 mBytes = JS_EncodeString(cx, str);
5113 return mBytes;
5116 void clear() {
5117 js::UnwantedForeground::free_(mBytes);
5118 mBytes = NULL;
5121 char *ptr() const {
5122 return mBytes;
5125 bool operator!() const {
5126 return !mBytes;
5129 private:
5130 char *mBytes;
5131 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
5133 /* Copy and assignment are not supported. */
5134 JSAutoByteString(const JSAutoByteString &another);
5135 JSAutoByteString &operator=(const JSAutoByteString &another);
5138 #endif
5140 /************************************************************************/
5142 * JSON functions
5144 typedef JSBool (* JSONWriteCallback)(const jschar *buf, uint32_t len, void *data);
5147 * JSON.stringify as specified by ES5.
5149 JS_PUBLIC_API(JSBool)
5150 JS_Stringify(JSContext *cx, jsval *vp, JSObject *replacer, jsval space,
5151 JSONWriteCallback callback, void *data);
5154 * JSON.parse as specified by ES5.
5156 JS_PUBLIC_API(JSBool)
5157 JS_ParseJSON(JSContext *cx, const jschar *chars, uint32_t len, jsval *vp);
5159 JS_PUBLIC_API(JSBool)
5160 JS_ParseJSONWithReviver(JSContext *cx, const jschar *chars, uint32_t len, jsval reviver,
5161 jsval *vp);
5163 /************************************************************************/
5165 /* API for the HTML5 internal structured cloning algorithm. */
5167 /* The maximum supported structured-clone serialization format version. */
5168 #define JS_STRUCTURED_CLONE_VERSION 1
5170 struct JSStructuredCloneCallbacks {
5171 ReadStructuredCloneOp read;
5172 WriteStructuredCloneOp write;
5173 StructuredCloneErrorOp reportError;
5176 JS_PUBLIC_API(JSBool)
5177 JS_ReadStructuredClone(JSContext *cx, const uint64_t *data, size_t nbytes,
5178 uint32_t version, jsval *vp,
5179 const JSStructuredCloneCallbacks *optionalCallbacks,
5180 void *closure);
5182 /* Note: On success, the caller is responsible for calling js::Foreground::free(*datap). */
5183 JS_PUBLIC_API(JSBool)
5184 JS_WriteStructuredClone(JSContext *cx, jsval v, uint64_t **datap, size_t *nbytesp,
5185 const JSStructuredCloneCallbacks *optionalCallbacks,
5186 void *closure);
5188 JS_PUBLIC_API(JSBool)
5189 JS_StructuredClone(JSContext *cx, jsval v, jsval *vp,
5190 const JSStructuredCloneCallbacks *optionalCallbacks,
5191 void *closure);
5193 #ifdef __cplusplus
5194 JS_END_EXTERN_C
5196 /* RAII sugar for JS_WriteStructuredClone. */
5197 class JS_PUBLIC_API(JSAutoStructuredCloneBuffer) {
5198 uint64_t *data_;
5199 size_t nbytes_;
5200 uint32_t version_;
5202 public:
5203 JSAutoStructuredCloneBuffer()
5204 : data_(NULL), nbytes_(0), version_(JS_STRUCTURED_CLONE_VERSION) {}
5206 ~JSAutoStructuredCloneBuffer() { clear(); }
5208 uint64_t *data() const { return data_; }
5209 size_t nbytes() const { return nbytes_; }
5211 void clear();
5213 /* Copy some memory. It will be automatically freed by the destructor. */
5214 bool copy(const uint64_t *data, size_t nbytes, uint32_t version=JS_STRUCTURED_CLONE_VERSION);
5217 * Adopt some memory. It will be automatically freed by the destructor.
5218 * data must have been allocated by the JS engine (e.g., extracted via
5219 * JSAutoStructuredCloneBuffer::steal).
5221 void adopt(uint64_t *data, size_t nbytes, uint32_t version=JS_STRUCTURED_CLONE_VERSION);
5224 * Remove the buffer so that it will not be automatically freed.
5225 * After this, the caller is responsible for feeding the memory back to
5226 * JSAutoStructuredCloneBuffer::adopt.
5228 void steal(uint64_t **datap, size_t *nbytesp, uint32_t *versionp=NULL);
5230 bool read(JSContext *cx, jsval *vp,
5231 const JSStructuredCloneCallbacks *optionalCallbacks=NULL,
5232 void *closure=NULL) const;
5234 bool write(JSContext *cx, jsval v,
5235 const JSStructuredCloneCallbacks *optionalCallbacks=NULL,
5236 void *closure=NULL);
5239 * Swap ownership with another JSAutoStructuredCloneBuffer.
5241 void swap(JSAutoStructuredCloneBuffer &other);
5243 private:
5244 /* Copy and assignment are not supported. */
5245 JSAutoStructuredCloneBuffer(const JSAutoStructuredCloneBuffer &other);
5246 JSAutoStructuredCloneBuffer &operator=(const JSAutoStructuredCloneBuffer &other);
5249 JS_BEGIN_EXTERN_C
5250 #endif
5252 /* API for implementing custom serialization behavior (for ImageData, File, etc.) */
5254 /* The range of tag values the application may use for its own custom object types. */
5255 #define JS_SCTAG_USER_MIN ((uint32_t) 0xFFFF8000)
5256 #define JS_SCTAG_USER_MAX ((uint32_t) 0xFFFFFFFF)
5258 #define JS_SCERR_RECURSION 0
5260 JS_PUBLIC_API(void)
5261 JS_SetStructuredCloneCallbacks(JSRuntime *rt, const JSStructuredCloneCallbacks *callbacks);
5263 JS_PUBLIC_API(JSBool)
5264 JS_ReadUint32Pair(JSStructuredCloneReader *r, uint32_t *p1, uint32_t *p2);
5266 JS_PUBLIC_API(JSBool)
5267 JS_ReadBytes(JSStructuredCloneReader *r, void *p, size_t len);
5269 JS_PUBLIC_API(JSBool)
5270 JS_ReadTypedArray(JSStructuredCloneReader *r, jsval *vp);
5272 JS_PUBLIC_API(JSBool)
5273 JS_WriteUint32Pair(JSStructuredCloneWriter *w, uint32_t tag, uint32_t data);
5275 JS_PUBLIC_API(JSBool)
5276 JS_WriteBytes(JSStructuredCloneWriter *w, const void *p, size_t len);
5278 JS_PUBLIC_API(JSBool)
5279 JS_WriteTypedArray(JSStructuredCloneWriter *w, jsval v);
5281 /************************************************************************/
5284 * Locale specific string conversion and error message callbacks.
5286 struct JSLocaleCallbacks {
5287 JSLocaleToUpperCase localeToUpperCase;
5288 JSLocaleToLowerCase localeToLowerCase;
5289 JSLocaleCompare localeCompare;
5290 JSLocaleToUnicode localeToUnicode;
5291 JSErrorCallback localeGetErrorMessage;
5295 * Establish locale callbacks. The pointer must persist as long as the
5296 * JSContext. Passing NULL restores the default behaviour.
5298 extern JS_PUBLIC_API(void)
5299 JS_SetLocaleCallbacks(JSContext *cx, JSLocaleCallbacks *callbacks);
5302 * Return the address of the current locale callbacks struct, which may
5303 * be NULL.
5305 extern JS_PUBLIC_API(JSLocaleCallbacks *)
5306 JS_GetLocaleCallbacks(JSContext *cx);
5308 /************************************************************************/
5311 * Error reporting.
5315 * Report an exception represented by the sprintf-like conversion of format
5316 * and its arguments. This exception message string is passed to a pre-set
5317 * JSErrorReporter function (set by JS_SetErrorReporter).
5319 extern JS_PUBLIC_API(void)
5320 JS_ReportError(JSContext *cx, const char *format, ...);
5323 * Use an errorNumber to retrieve the format string, args are char *
5325 extern JS_PUBLIC_API(void)
5326 JS_ReportErrorNumber(JSContext *cx, JSErrorCallback errorCallback,
5327 void *userRef, const unsigned errorNumber, ...);
5330 * Use an errorNumber to retrieve the format string, args are jschar *
5332 extern JS_PUBLIC_API(void)
5333 JS_ReportErrorNumberUC(JSContext *cx, JSErrorCallback errorCallback,
5334 void *userRef, const unsigned errorNumber, ...);
5337 * As above, but report a warning instead (JSREPORT_IS_WARNING(report.flags)).
5338 * Return true if there was no error trying to issue the warning, and if the
5339 * warning was not converted into an error due to the JSOPTION_WERROR option
5340 * being set, false otherwise.
5342 extern JS_PUBLIC_API(JSBool)
5343 JS_ReportWarning(JSContext *cx, const char *format, ...);
5345 extern JS_PUBLIC_API(JSBool)
5346 JS_ReportErrorFlagsAndNumber(JSContext *cx, unsigned flags,
5347 JSErrorCallback errorCallback, void *userRef,
5348 const unsigned errorNumber, ...);
5350 extern JS_PUBLIC_API(JSBool)
5351 JS_ReportErrorFlagsAndNumberUC(JSContext *cx, unsigned flags,
5352 JSErrorCallback errorCallback, void *userRef,
5353 const unsigned errorNumber, ...);
5356 * Complain when out of memory.
5358 extern JS_PUBLIC_API(void)
5359 JS_ReportOutOfMemory(JSContext *cx);
5362 * Complain when an allocation size overflows the maximum supported limit.
5364 extern JS_PUBLIC_API(void)
5365 JS_ReportAllocationOverflow(JSContext *cx);
5367 struct JSErrorReport {
5368 const char *filename; /* source file name, URL, etc., or null */
5369 JSPrincipals *originPrincipals; /* see 'originPrincipals' comment above */
5370 unsigned lineno; /* source line number */
5371 const char *linebuf; /* offending source line without final \n */
5372 const char *tokenptr; /* pointer to error token in linebuf */
5373 const jschar *uclinebuf; /* unicode (original) line buffer */
5374 const jschar *uctokenptr; /* unicode (original) token pointer */
5375 unsigned flags; /* error/warning, etc. */
5376 unsigned errorNumber; /* the error number, e.g. see js.msg */
5377 const jschar *ucmessage; /* the (default) error message */
5378 const jschar **messageArgs; /* arguments for the error message */
5382 * JSErrorReport flag values. These may be freely composed.
5384 #define JSREPORT_ERROR 0x0 /* pseudo-flag for default case */
5385 #define JSREPORT_WARNING 0x1 /* reported via JS_ReportWarning */
5386 #define JSREPORT_EXCEPTION 0x2 /* exception was thrown */
5387 #define JSREPORT_STRICT 0x4 /* error or warning due to strict option */
5390 * This condition is an error in strict mode code, a warning if
5391 * JS_HAS_STRICT_OPTION(cx), and otherwise should not be reported at
5392 * all. We check the strictness of the context's top frame's script;
5393 * where that isn't appropriate, the caller should do the right checks
5394 * itself instead of using this flag.
5396 #define JSREPORT_STRICT_MODE_ERROR 0x8
5399 * If JSREPORT_EXCEPTION is set, then a JavaScript-catchable exception
5400 * has been thrown for this runtime error, and the host should ignore it.
5401 * Exception-aware hosts should also check for JS_IsExceptionPending if
5402 * JS_ExecuteScript returns failure, and signal or propagate the exception, as
5403 * appropriate.
5405 #define JSREPORT_IS_WARNING(flags) (((flags) & JSREPORT_WARNING) != 0)
5406 #define JSREPORT_IS_EXCEPTION(flags) (((flags) & JSREPORT_EXCEPTION) != 0)
5407 #define JSREPORT_IS_STRICT(flags) (((flags) & JSREPORT_STRICT) != 0)
5408 #define JSREPORT_IS_STRICT_MODE_ERROR(flags) (((flags) & \
5409 JSREPORT_STRICT_MODE_ERROR) != 0)
5410 extern JS_PUBLIC_API(JSErrorReporter)
5411 JS_GetErrorReporter(JSContext *cx);
5413 extern JS_PUBLIC_API(JSErrorReporter)
5414 JS_SetErrorReporter(JSContext *cx, JSErrorReporter er);
5416 /************************************************************************/
5419 * Dates.
5422 extern JS_PUBLIC_API(JSObject *)
5423 JS_NewDateObject(JSContext *cx, int year, int mon, int mday, int hour, int min, int sec);
5425 extern JS_PUBLIC_API(JSObject *)
5426 JS_NewDateObjectMsec(JSContext *cx, double msec);
5429 * Infallible predicate to test whether obj is a date object.
5431 extern JS_PUBLIC_API(JSBool)
5432 JS_ObjectIsDate(JSContext *cx, JSObject *obj);
5434 /************************************************************************/
5437 * Regular Expressions.
5439 #define JSREG_FOLD 0x01 /* fold uppercase to lowercase */
5440 #define JSREG_GLOB 0x02 /* global exec, creates array of matches */
5441 #define JSREG_MULTILINE 0x04 /* treat ^ and $ as begin and end of line */
5442 #define JSREG_STICKY 0x08 /* only match starting at lastIndex */
5444 extern JS_PUBLIC_API(JSObject *)
5445 JS_NewRegExpObject(JSContext *cx, JSObject *obj, char *bytes, size_t length, unsigned flags);
5447 extern JS_PUBLIC_API(JSObject *)
5448 JS_NewUCRegExpObject(JSContext *cx, JSObject *obj, jschar *chars, size_t length, unsigned flags);
5450 extern JS_PUBLIC_API(void)
5451 JS_SetRegExpInput(JSContext *cx, JSObject *obj, JSString *input, JSBool multiline);
5453 extern JS_PUBLIC_API(void)
5454 JS_ClearRegExpStatics(JSContext *cx, JSObject *obj);
5456 extern JS_PUBLIC_API(JSBool)
5457 JS_ExecuteRegExp(JSContext *cx, JSObject *obj, JSObject *reobj, jschar *chars, size_t length,
5458 size_t *indexp, JSBool test, jsval *rval);
5460 /* RegExp interface for clients without a global object. */
5462 extern JS_PUBLIC_API(JSObject *)
5463 JS_NewRegExpObjectNoStatics(JSContext *cx, char *bytes, size_t length, unsigned flags);
5465 extern JS_PUBLIC_API(JSObject *)
5466 JS_NewUCRegExpObjectNoStatics(JSContext *cx, jschar *chars, size_t length, unsigned flags);
5468 extern JS_PUBLIC_API(JSBool)
5469 JS_ExecuteRegExpNoStatics(JSContext *cx, JSObject *reobj, jschar *chars, size_t length,
5470 size_t *indexp, JSBool test, jsval *rval);
5472 extern JS_PUBLIC_API(JSBool)
5473 JS_ObjectIsRegExp(JSContext *cx, JSObject *obj);
5475 extern JS_PUBLIC_API(unsigned)
5476 JS_GetRegExpFlags(JSContext *cx, JSObject *obj);
5478 extern JS_PUBLIC_API(JSString *)
5479 JS_GetRegExpSource(JSContext *cx, JSObject *obj);
5481 /************************************************************************/
5483 extern JS_PUBLIC_API(JSBool)
5484 JS_IsExceptionPending(JSContext *cx);
5486 extern JS_PUBLIC_API(JSBool)
5487 JS_GetPendingException(JSContext *cx, jsval *vp);
5489 extern JS_PUBLIC_API(void)
5490 JS_SetPendingException(JSContext *cx, jsval v);
5492 extern JS_PUBLIC_API(void)
5493 JS_ClearPendingException(JSContext *cx);
5495 extern JS_PUBLIC_API(JSBool)
5496 JS_ReportPendingException(JSContext *cx);
5499 * Save the current exception state. This takes a snapshot of cx's current
5500 * exception state without making any change to that state.
5502 * The returned state pointer MUST be passed later to JS_RestoreExceptionState
5503 * (to restore that saved state, overriding any more recent state) or else to
5504 * JS_DropExceptionState (to free the state struct in case it is not correct
5505 * or desirable to restore it). Both Restore and Drop free the state struct,
5506 * so callers must stop using the pointer returned from Save after calling the
5507 * Release or Drop API.
5509 extern JS_PUBLIC_API(JSExceptionState *)
5510 JS_SaveExceptionState(JSContext *cx);
5512 extern JS_PUBLIC_API(void)
5513 JS_RestoreExceptionState(JSContext *cx, JSExceptionState *state);
5515 extern JS_PUBLIC_API(void)
5516 JS_DropExceptionState(JSContext *cx, JSExceptionState *state);
5519 * If the given value is an exception object that originated from an error,
5520 * the exception will contain an error report struct, and this API will return
5521 * the address of that struct. Otherwise, it returns NULL. The lifetime of
5522 * the error report struct that might be returned is the same as the lifetime
5523 * of the exception object.
5525 extern JS_PUBLIC_API(JSErrorReport *)
5526 JS_ErrorFromException(JSContext *cx, jsval v);
5529 * Given a reported error's message and JSErrorReport struct pointer, throw
5530 * the corresponding exception on cx.
5532 extern JS_PUBLIC_API(JSBool)
5533 JS_ThrowReportedError(JSContext *cx, const char *message,
5534 JSErrorReport *reportp);
5537 * Throws a StopIteration exception on cx.
5539 extern JS_PUBLIC_API(JSBool)
5540 JS_ThrowStopIteration(JSContext *cx);
5542 extern JS_PUBLIC_API(intptr_t)
5543 JS_GetCurrentThread();
5546 * A JS runtime always has an "owner thread". The owner thread is set when the
5547 * runtime is created (to the current thread) and practically all entry points
5548 * into the JS engine check that a runtime (or anything contained in the
5549 * runtime: context, compartment, object, etc) is only touched by its owner
5550 * thread. Embeddings may check this invariant outside the JS engine by calling
5551 * JS_AbortIfWrongThread (which will abort if not on the owner thread, even for
5552 * non-debug builds).
5554 * It is possible to "move" a runtime between threads. This is accomplished by
5555 * calling JS_ClearRuntimeThread on a runtime's owner thread and then calling
5556 * JS_SetRuntimeThread on the new owner thread. The runtime must not be
5557 * accessed between JS_ClearRuntimeThread and JS_SetRuntimeThread. Also, the
5558 * caller is responsible for synchronizing the calls to Set/Clear.
5561 extern JS_PUBLIC_API(void)
5562 JS_AbortIfWrongThread(JSRuntime *rt);
5564 extern JS_PUBLIC_API(void)
5565 JS_ClearRuntimeThread(JSRuntime *rt);
5567 extern JS_PUBLIC_API(void)
5568 JS_SetRuntimeThread(JSRuntime *rt);
5570 #ifdef __cplusplus
5571 JS_END_EXTERN_C
5573 class JSAutoSetRuntimeThread
5575 JSRuntime *runtime;
5577 public:
5578 JSAutoSetRuntimeThread(JSRuntime *runtime) : runtime(runtime) {
5579 JS_SetRuntimeThread(runtime);
5582 ~JSAutoSetRuntimeThread() {
5583 JS_ClearRuntimeThread(runtime);
5587 JS_BEGIN_EXTERN_C
5588 #endif
5590 /************************************************************************/
5593 * JS_IsConstructing must be called from within a native given the
5594 * native's original cx and vp arguments. If JS_IsConstructing is true,
5595 * JS_THIS must not be used; the constructor should construct and return a
5596 * new object. Otherwise, the native is called as an ordinary function and
5597 * JS_THIS may be used.
5599 static JS_ALWAYS_INLINE JSBool
5600 JS_IsConstructing(JSContext *cx, const jsval *vp)
5602 #ifdef DEBUG
5603 JSObject *callee = JSVAL_TO_OBJECT(JS_CALLEE(cx, vp));
5604 if (JS_ObjectIsFunction(cx, callee)) {
5605 JSFunction *fun = JS_ValueToFunction(cx, JS_CALLEE(cx, vp));
5606 JS_ASSERT((JS_GetFunctionFlags(fun) & JSFUN_CONSTRUCTOR) != 0);
5607 } else {
5608 JS_ASSERT(JS_GetClass(callee)->construct != NULL);
5610 #else
5611 (void)cx;
5612 #endif
5614 return JSVAL_IS_MAGIC_IMPL(JSVAL_TO_IMPL(vp[1]));
5618 * A constructor can request that the JS engine create a default new 'this'
5619 * object of the given class, using the callee to determine parentage and
5620 * [[Prototype]].
5622 extern JS_PUBLIC_API(JSObject *)
5623 JS_NewObjectForConstructor(JSContext *cx, JSClass *clasp, const jsval *vp);
5625 /************************************************************************/
5627 #ifdef DEBUG
5628 #define JS_GC_ZEAL 1
5629 #endif
5631 #ifdef JS_GC_ZEAL
5632 #define JS_DEFAULT_ZEAL_FREQ 100
5634 extern JS_PUBLIC_API(void)
5635 JS_SetGCZeal(JSContext *cx, uint8_t zeal, uint32_t frequency);
5637 extern JS_PUBLIC_API(void)
5638 JS_ScheduleGC(JSContext *cx, uint32_t count);
5639 #endif
5642 * Convert a uint32_t index into a jsid.
5644 extern JS_PUBLIC_API(JSBool)
5645 JS_IndexToId(JSContext *cx, uint32_t index, jsid *id);
5648 * Test if the given string is a valid ECMAScript identifier
5650 extern JS_PUBLIC_API(JSBool)
5651 JS_IsIdentifier(JSContext *cx, JSString *str, JSBool *isIdentifier);
5654 * Return the current script and line number of the most currently running
5655 * frame. Returns true if a scripted frame was found, false otherwise.
5657 extern JS_PUBLIC_API(JSBool)
5658 JS_DescribeScriptedCaller(JSContext *cx, JSScript **script, unsigned *lineno);
5662 * Encode/Decode interpreted scripts and functions to/from memory.
5665 extern JS_PUBLIC_API(void *)
5666 JS_EncodeScript(JSContext *cx, JSScript *script, uint32_t *lengthp);
5668 extern JS_PUBLIC_API(void *)
5669 JS_EncodeInterpretedFunction(JSContext *cx, JSObject *funobj, uint32_t *lengthp);
5671 extern JS_PUBLIC_API(JSScript *)
5672 JS_DecodeScript(JSContext *cx, const void *data, uint32_t length,
5673 JSPrincipals *principals, JSPrincipals *originPrincipals);
5675 extern JS_PUBLIC_API(JSObject *)
5676 JS_DecodeInterpretedFunction(JSContext *cx, const void *data, uint32_t length,
5677 JSPrincipals *principals, JSPrincipals *originPrincipals);
5679 JS_END_EXTERN_C
5681 #endif /* jsapi_h___ */