Bumping manifests a=b2g-bump
[gecko.git] / js / src / jsapi.h
blobea5a9b3c051a7cbaa80ce6489f24a019923e0fc5
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sts=4 et sw=4 tw=99:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* JavaScript API. */
9 #ifndef jsapi_h
10 #define jsapi_h
12 #include "mozilla/FloatingPoint.h"
13 #include "mozilla/MemoryReporting.h"
14 #include "mozilla/Range.h"
15 #include "mozilla/RangedPtr.h"
16 #include "mozilla/TypedEnum.h"
18 #include <stdarg.h>
19 #include <stddef.h>
20 #include <stdint.h>
21 #include <stdio.h>
23 #include "jsalloc.h"
24 #include "jspubtd.h"
26 #include "js/CallArgs.h"
27 #include "js/Class.h"
28 #include "js/HashTable.h"
29 #include "js/Id.h"
30 #include "js/Principals.h"
31 #include "js/RootingAPI.h"
32 #include "js/TracingAPI.h"
33 #include "js/Utility.h"
34 #include "js/Value.h"
35 #include "js/Vector.h"
37 /************************************************************************/
39 namespace JS {
41 class Latin1CharsZ;
42 class TwoByteChars;
44 #ifdef JS_DEBUG
46 class JS_PUBLIC_API(AutoCheckRequestDepth)
48 JSContext* cx;
49 public:
50 explicit AutoCheckRequestDepth(JSContext* cx);
51 explicit AutoCheckRequestDepth(js::ContextFriendFields* cx);
52 ~AutoCheckRequestDepth();
55 # define CHECK_REQUEST(cx) \
56 JS::AutoCheckRequestDepth _autoCheckRequestDepth(cx)
58 #else
60 # define CHECK_REQUEST(cx) \
61 ((void) 0)
63 #endif /* JS_DEBUG */
65 #ifdef JS_DEBUG
67 * Assert that we're not doing GC on cx, that we're in a request as
68 * needed, and that the compartments for cx and v are correct.
69 * Also check that GC would be safe at this point.
71 JS_PUBLIC_API(void)
72 AssertArgumentsAreSane(JSContext* cx, JS::HandleValue v);
73 #else
74 inline void AssertArgumentsAreSane(JSContext* cx, JS::HandleValue v) {
75 /* Do nothing */
77 #endif /* JS_DEBUG */
79 /* AutoValueArray roots an internal fixed-size array of Values. */
80 template <size_t N>
81 class AutoValueArray : public AutoGCRooter
83 const size_t length_;
84 Value elements_[N];
86 public:
87 explicit AutoValueArray(JSContext* cx
88 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
89 : AutoGCRooter(cx, VALARRAY), length_(N)
91 /* Always initialize in case we GC before assignment. */
92 mozilla::PodArrayZero(elements_);
93 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
96 unsigned length() const { return length_; }
97 const Value* begin() const { return elements_; }
98 Value* begin() { return elements_; }
100 HandleValue operator[](unsigned i) const {
101 MOZ_ASSERT(i < N);
102 return HandleValue::fromMarkedLocation(&elements_[i]);
104 MutableHandleValue operator[](unsigned i) {
105 MOZ_ASSERT(i < N);
106 return MutableHandleValue::fromMarkedLocation(&elements_[i]);
109 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
112 template<class T>
113 class AutoVectorRooter : protected AutoGCRooter
115 typedef js::Vector<T, 8> VectorImpl;
116 VectorImpl vector;
118 public:
119 explicit AutoVectorRooter(JSContext* cx, ptrdiff_t tag
120 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
121 : AutoGCRooter(cx, tag), vector(cx)
123 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
126 explicit AutoVectorRooter(js::ContextFriendFields* cx, ptrdiff_t tag
127 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
128 : AutoGCRooter(cx, tag), vector(cx)
130 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
133 typedef T ElementType;
134 typedef typename VectorImpl::Range Range;
136 size_t length() const { return vector.length(); }
137 bool empty() const { return vector.empty(); }
139 bool append(const T& v) { return vector.append(v); }
140 bool append(const T* ptr, size_t len) { return vector.append(ptr, len); }
141 bool appendAll(const AutoVectorRooter<T>& other) {
142 return vector.appendAll(other.vector);
145 bool insert(T* p, const T& val) { return vector.insert(p, val); }
147 /* For use when space has already been reserved. */
148 void infallibleAppend(const T& v) { vector.infallibleAppend(v); }
150 void popBack() { vector.popBack(); }
151 T popCopy() { return vector.popCopy(); }
153 bool growBy(size_t inc) {
154 size_t oldLength = vector.length();
155 if (!vector.growByUninitialized(inc))
156 return false;
157 makeRangeGCSafe(oldLength);
158 return true;
161 bool resize(size_t newLength) {
162 size_t oldLength = vector.length();
163 if (newLength <= oldLength) {
164 vector.shrinkBy(oldLength - newLength);
165 return true;
167 if (!vector.growByUninitialized(newLength - oldLength))
168 return false;
169 makeRangeGCSafe(oldLength);
170 return true;
173 void clear() { vector.clear(); }
175 bool reserve(size_t newLength) {
176 return vector.reserve(newLength);
179 JS::MutableHandle<T> operator[](size_t i) {
180 return JS::MutableHandle<T>::fromMarkedLocation(&vector[i]);
182 JS::Handle<T> operator[](size_t i) const {
183 return JS::Handle<T>::fromMarkedLocation(&vector[i]);
186 const T* begin() const { return vector.begin(); }
187 T* begin() { return vector.begin(); }
189 const T* end() const { return vector.end(); }
190 T* end() { return vector.end(); }
192 Range all() { return vector.all(); }
194 const T& back() const { return vector.back(); }
196 friend void AutoGCRooter::trace(JSTracer* trc);
198 private:
199 void makeRangeGCSafe(size_t oldLength) {
200 T* t = vector.begin() + oldLength;
201 for (size_t i = oldLength; i < vector.length(); ++i, ++t)
202 memset(t, 0, sizeof(T));
205 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
208 template<class Key, class Value>
209 class AutoHashMapRooter : protected AutoGCRooter
211 private:
212 typedef js::HashMap<Key, Value> HashMapImpl;
214 public:
215 explicit AutoHashMapRooter(JSContext* cx, ptrdiff_t tag
216 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
217 : AutoGCRooter(cx, tag), map(cx)
219 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
222 typedef Key KeyType;
223 typedef Value ValueType;
224 typedef typename HashMapImpl::Entry Entry;
225 typedef typename HashMapImpl::Lookup Lookup;
226 typedef typename HashMapImpl::Ptr Ptr;
227 typedef typename HashMapImpl::AddPtr AddPtr;
229 bool init(uint32_t len = 16) {
230 return map.init(len);
232 bool initialized() const {
233 return map.initialized();
235 Ptr lookup(const Lookup& l) const {
236 return map.lookup(l);
238 void remove(Ptr p) {
239 map.remove(p);
241 AddPtr lookupForAdd(const Lookup& l) const {
242 return map.lookupForAdd(l);
245 template<typename KeyInput, typename ValueInput>
246 bool add(AddPtr& p, const KeyInput& k, const ValueInput& v) {
247 return map.add(p, k, v);
250 bool add(AddPtr& p, const Key& k) {
251 return map.add(p, k);
254 template<typename KeyInput, typename ValueInput>
255 bool relookupOrAdd(AddPtr& p, const KeyInput& k, const ValueInput& v) {
256 return map.relookupOrAdd(p, k, v);
259 typedef typename HashMapImpl::Range Range;
260 Range all() const {
261 return map.all();
264 typedef typename HashMapImpl::Enum Enum;
266 void clear() {
267 map.clear();
270 void finish() {
271 map.finish();
274 bool empty() const {
275 return map.empty();
278 uint32_t count() const {
279 return map.count();
282 size_t capacity() const {
283 return map.capacity();
286 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
287 return map.sizeOfExcludingThis(mallocSizeOf);
289 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
290 return map.sizeOfIncludingThis(mallocSizeOf);
293 uint32_t generation() const {
294 return map.generation();
297 /************************************************** Shorthand operations */
299 bool has(const Lookup& l) const {
300 return map.has(l);
303 template<typename KeyInput, typename ValueInput>
304 bool put(const KeyInput& k, const ValueInput& v) {
305 return map.put(k, v);
308 template<typename KeyInput, typename ValueInput>
309 bool putNew(const KeyInput& k, const ValueInput& v) {
310 return map.putNew(k, v);
313 Ptr lookupWithDefault(const Key& k, const Value& defaultValue) {
314 return map.lookupWithDefault(k, defaultValue);
317 void remove(const Lookup& l) {
318 map.remove(l);
321 friend void AutoGCRooter::trace(JSTracer* trc);
323 private:
324 AutoHashMapRooter(const AutoHashMapRooter& hmr) = delete;
325 AutoHashMapRooter& operator=(const AutoHashMapRooter& hmr) = delete;
327 HashMapImpl map;
329 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
332 template<class T>
333 class AutoHashSetRooter : protected AutoGCRooter
335 private:
336 typedef js::HashSet<T> HashSetImpl;
338 public:
339 explicit AutoHashSetRooter(JSContext* cx, ptrdiff_t tag
340 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
341 : AutoGCRooter(cx, tag), set(cx)
343 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
346 typedef typename HashSetImpl::Lookup Lookup;
347 typedef typename HashSetImpl::Ptr Ptr;
348 typedef typename HashSetImpl::AddPtr AddPtr;
350 bool init(uint32_t len = 16) {
351 return set.init(len);
353 bool initialized() const {
354 return set.initialized();
356 Ptr lookup(const Lookup& l) const {
357 return set.lookup(l);
359 void remove(Ptr p) {
360 set.remove(p);
362 AddPtr lookupForAdd(const Lookup& l) const {
363 return set.lookupForAdd(l);
366 bool add(AddPtr& p, const T& t) {
367 return set.add(p, t);
370 bool relookupOrAdd(AddPtr& p, const Lookup& l, const T& t) {
371 return set.relookupOrAdd(p, l, t);
374 typedef typename HashSetImpl::Range Range;
375 Range all() const {
376 return set.all();
379 typedef typename HashSetImpl::Enum Enum;
381 void clear() {
382 set.clear();
385 void finish() {
386 set.finish();
389 bool empty() const {
390 return set.empty();
393 uint32_t count() const {
394 return set.count();
397 size_t capacity() const {
398 return set.capacity();
401 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
402 return set.sizeOfExcludingThis(mallocSizeOf);
404 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
405 return set.sizeOfIncludingThis(mallocSizeOf);
408 uint32_t generation() const {
409 return set.generation();
412 /************************************************** Shorthand operations */
414 bool has(const Lookup& l) const {
415 return set.has(l);
418 bool put(const T& t) {
419 return set.put(t);
422 bool putNew(const T& t) {
423 return set.putNew(t);
426 void remove(const Lookup& l) {
427 set.remove(l);
430 friend void AutoGCRooter::trace(JSTracer* trc);
432 private:
433 AutoHashSetRooter(const AutoHashSetRooter& hmr) = delete;
434 AutoHashSetRooter& operator=(const AutoHashSetRooter& hmr) = delete;
436 HashSetImpl set;
438 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
441 class MOZ_STACK_CLASS AutoValueVector : public AutoVectorRooter<Value>
443 public:
444 explicit AutoValueVector(JSContext* cx
445 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
446 : AutoVectorRooter<Value>(cx, VALVECTOR)
448 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
451 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
454 class AutoIdVector : public AutoVectorRooter<jsid>
456 public:
457 explicit AutoIdVector(JSContext* cx
458 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
459 : AutoVectorRooter<jsid>(cx, IDVECTOR)
461 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
464 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
467 class AutoObjectVector : public AutoVectorRooter<JSObject*>
469 public:
470 explicit AutoObjectVector(JSContext* cx
471 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
472 : AutoVectorRooter<JSObject*>(cx, OBJVECTOR)
474 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
477 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
480 class AutoFunctionVector : public AutoVectorRooter<JSFunction*>
482 public:
483 explicit AutoFunctionVector(JSContext* cx
484 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
485 : AutoVectorRooter<JSFunction*>(cx, FUNVECTOR)
487 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
490 explicit AutoFunctionVector(js::ContextFriendFields* cx
491 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
492 : AutoVectorRooter<JSFunction*>(cx, FUNVECTOR)
494 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
497 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
500 class AutoScriptVector : public AutoVectorRooter<JSScript*>
502 public:
503 explicit AutoScriptVector(JSContext* cx
504 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
505 : AutoVectorRooter<JSScript*>(cx, SCRIPTVECTOR)
507 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
510 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
514 * Custom rooting behavior for internal and external clients.
516 class JS_PUBLIC_API(CustomAutoRooter) : private AutoGCRooter
518 public:
519 template <typename CX>
520 explicit CustomAutoRooter(CX* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
521 : AutoGCRooter(cx, CUSTOM)
523 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
526 friend void AutoGCRooter::trace(JSTracer* trc);
528 protected:
529 /* Supplied by derived class to trace roots. */
530 virtual void trace(JSTracer* trc) = 0;
532 private:
533 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
537 * RootedGeneric<T> allows a class to instantiate its own Rooted type by
538 * including the method:
540 * void trace(JSTracer* trc);
542 * The trace() method must trace all of the class's fields.
544 template <class T>
545 class RootedGeneric : private CustomAutoRooter
547 public:
548 template <typename CX>
549 explicit RootedGeneric(CX* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
550 : CustomAutoRooter(cx)
552 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
555 template <typename CX>
556 explicit RootedGeneric(CX* cx, const T& initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
557 : CustomAutoRooter(cx), value(initial)
559 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
562 operator const T&() const { return value; }
563 T operator->() const { return value; }
565 private:
566 virtual void trace(JSTracer* trc) { value->trace(trc); }
568 T value;
570 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
573 /* A handle to an array of rooted values. */
574 class HandleValueArray
576 const size_t length_;
577 const Value * const elements_;
579 HandleValueArray(size_t len, const Value* elements) : length_(len), elements_(elements) {}
581 public:
582 explicit HandleValueArray(const RootedValue& value) : length_(1), elements_(value.address()) {}
584 MOZ_IMPLICIT HandleValueArray(const AutoValueVector& values)
585 : length_(values.length()), elements_(values.begin()) {}
587 template <size_t N>
588 HandleValueArray(const AutoValueArray<N>& values) : length_(N), elements_(values.begin()) {}
590 /* CallArgs must already be rooted somewhere up the stack. */
591 MOZ_IMPLICIT HandleValueArray(const JS::CallArgs& args) : length_(args.length()), elements_(args.array()) {}
593 /* Use with care! Only call this if the data is guaranteed to be marked. */
594 static HandleValueArray fromMarkedLocation(size_t len, const Value* elements) {
595 return HandleValueArray(len, elements);
598 static HandleValueArray subarray(const HandleValueArray& values, size_t startIndex, size_t len) {
599 MOZ_ASSERT(startIndex + len <= values.length());
600 return HandleValueArray(len, values.begin() + startIndex);
603 static HandleValueArray empty() {
604 return HandleValueArray(0, nullptr);
607 size_t length() const { return length_; }
608 const Value* begin() const { return elements_; }
610 HandleValue operator[](size_t i) const {
611 MOZ_ASSERT(i < length_);
612 return HandleValue::fromMarkedLocation(&elements_[i]);
616 // Container for futex methods, used to implement the Atomics primitives.
618 // Client code calls JS_SetContextFutexAPI to install an instance of a
619 // subclass of PerRuntimeFutexAPI on the runtime. Implementations
620 // of the Atomics primitives will use that object, if it is present
621 // (and fail, if not).
623 // The API may differ among clients; for example, the APIs installed by
624 // a worker and by the main window event thread are possibly different.
626 class PerRuntimeFutexAPI
628 public:
629 virtual ~PerRuntimeFutexAPI() {}
631 // Acquire the GLOBAL lock for all futex resources in all domains.
632 virtual void lock() = 0;
634 // Release the GLOBAL lock.
635 virtual void unlock() = 0;
637 // Return true iff the calling thread is a worker thread. This must be
638 // used to guard calls to wait(). The lock need not be held.
639 virtual bool isOnWorkerThread() = 0;
641 enum WakeResult {
642 Woken, // Woken by futexWait
643 Timedout, // Woken by timeout
644 InterruptForTerminate, // Woken by a request to terminate the worker
645 ErrorTooLong // Implementation constraint on the timer (for now)
648 // Block the thread.
650 // The lock must be held around this call, see lock() and unlock().
651 virtual WakeResult wait(double timeout_ns) = 0;
653 // Wake the thread represented by this PerRuntimeFutexAPI.
655 // The lock must be held around this call, see lock() and unlock().
656 // Since the sleeping thread also needs that lock to wake up, the
657 // thread will not actually wake up until the caller of wake()
658 // releases the lock.
659 virtual void wake() = 0;
662 JS_PUBLIC_API(JS::PerRuntimeFutexAPI*)
663 GetRuntimeFutexAPI(JSRuntime* rt);
665 // Transfers ownership of fx to rt; if rt's futexAPI field is not null when rt is
666 // deleted then rt's destructor will delete that value. If fx is null in this
667 // call then ownership of a held nonnull value is transfered away from rt.
668 JS_PUBLIC_API(void)
669 SetRuntimeFutexAPI(JSRuntime* rt, JS::PerRuntimeFutexAPI* fx);
671 } /* namespace JS */
673 /************************************************************************/
675 struct JSFreeOp {
676 private:
677 JSRuntime* runtime_;
679 protected:
680 explicit JSFreeOp(JSRuntime* rt)
681 : runtime_(rt) { }
683 public:
684 JSRuntime* runtime() const {
685 return runtime_;
689 /* Callbacks and their arguments. */
691 /************************************************************************/
693 typedef enum JSContextOp {
694 JSCONTEXT_NEW,
695 JSCONTEXT_DESTROY
696 } JSContextOp;
699 * The possible values for contextOp when the runtime calls the callback are:
700 * JSCONTEXT_NEW JS_NewContext successfully created a new JSContext
701 * instance. The callback can initialize the instance as
702 * required. If the callback returns false, the instance
703 * will be destroyed and JS_NewContext returns null. In
704 * this case the callback is not called again.
705 * JSCONTEXT_DESTROY One of JS_DestroyContext* methods is called. The
706 * callback may perform its own cleanup and must always
707 * return true.
708 * Any other value For future compatibility the callback must do nothing
709 * and return true in this case.
711 typedef bool
712 (* JSContextCallback)(JSContext* cx, unsigned contextOp, void* data);
714 typedef enum JSGCStatus {
715 JSGC_BEGIN,
716 JSGC_END
717 } JSGCStatus;
719 typedef void
720 (* JSGCCallback)(JSRuntime* rt, JSGCStatus status, void* data);
722 typedef enum JSFinalizeStatus {
724 * Called when preparing to sweep a group of compartments, before anything
725 * has been swept. The collector will not yield to the mutator before
726 * calling the callback with JSFINALIZE_GROUP_END status.
728 JSFINALIZE_GROUP_START,
731 * Called when preparing to sweep a group of compartments. Weak references
732 * to unmarked things have been removed and things that are not swept
733 * incrementally have been finalized at this point. The collector may yield
734 * to the mutator after this point.
736 JSFINALIZE_GROUP_END,
739 * Called at the end of collection when everything has been swept.
741 JSFINALIZE_COLLECTION_END
742 } JSFinalizeStatus;
744 typedef void
745 (* JSFinalizeCallback)(JSFreeOp* fop, JSFinalizeStatus status, bool isCompartment, void* data);
747 typedef void
748 (* JSWeakPointerCallback)(JSRuntime* rt, void* data);
750 typedef bool
751 (* JSInterruptCallback)(JSContext* cx);
753 typedef void
754 (* JSErrorReporter)(JSContext* cx, const char* message, JSErrorReport* report);
757 * Possible exception types. These types are part of a JSErrorFormatString
758 * structure. They define which error to throw in case of a runtime error.
759 * JSEXN_NONE marks an unthrowable error.
761 typedef enum JSExnType {
762 JSEXN_NONE = -1,
763 JSEXN_ERR,
764 JSEXN_INTERNALERR,
765 JSEXN_EVALERR,
766 JSEXN_RANGEERR,
767 JSEXN_REFERENCEERR,
768 JSEXN_SYNTAXERR,
769 JSEXN_TYPEERR,
770 JSEXN_URIERR,
771 JSEXN_LIMIT
772 } JSExnType;
774 typedef struct JSErrorFormatString {
775 /* The error format string in ASCII. */
776 const char* format;
778 /* The number of arguments to expand in the formatted error message. */
779 uint16_t argCount;
781 /* One of the JSExnType constants above. */
782 int16_t exnType;
783 } JSErrorFormatString;
785 typedef const JSErrorFormatString*
786 (* JSErrorCallback)(void* userRef, const unsigned errorNumber);
788 typedef bool
789 (* JSLocaleToUpperCase)(JSContext* cx, JS::HandleString src, JS::MutableHandleValue rval);
791 typedef bool
792 (* JSLocaleToLowerCase)(JSContext* cx, JS::HandleString src, JS::MutableHandleValue rval);
794 typedef bool
795 (* JSLocaleCompare)(JSContext* cx, JS::HandleString src1, JS::HandleString src2,
796 JS::MutableHandleValue rval);
798 typedef bool
799 (* JSLocaleToUnicode)(JSContext* cx, const char* src, JS::MutableHandleValue rval);
802 * Callback used to ask the embedding for the cross compartment wrapper handler
803 * that implements the desired prolicy for this kind of object in the
804 * destination compartment. |obj| is the object to be wrapped. If |existing| is
805 * non-nullptr, it will point to an existing wrapper object that should be
806 * re-used if possible. |existing| is guaranteed to be a cross-compartment
807 * wrapper with a lazily-defined prototype and the correct global. It is
808 * guaranteed not to wrap a function.
810 typedef JSObject*
811 (* JSWrapObjectCallback)(JSContext* cx, JS::HandleObject existing, JS::HandleObject obj,
812 JS::HandleObject parent);
815 * Callback used by the wrap hook to ask the embedding to prepare an object
816 * for wrapping in a context. This might include unwrapping other wrappers
817 * or even finding a more suitable object for the new compartment.
819 typedef JSObject*
820 (* JSPreWrapCallback)(JSContext* cx, JS::HandleObject scope, JS::HandleObject obj,
821 JS::HandleObject objectPassedToWrap);
823 struct JSWrapObjectCallbacks
825 JSWrapObjectCallback wrap;
826 JSPreWrapCallback preWrap;
829 typedef void
830 (* JSDestroyCompartmentCallback)(JSFreeOp* fop, JSCompartment* compartment);
832 typedef void
833 (* JSZoneCallback)(JS::Zone* zone);
835 typedef void
836 (* JSCompartmentNameCallback)(JSRuntime* rt, JSCompartment* compartment,
837 char* buf, size_t bufsize);
839 /************************************************************************/
841 static MOZ_ALWAYS_INLINE jsval
842 JS_NumberValue(double d)
844 int32_t i;
845 d = JS::CanonicalizeNaN(d);
846 if (mozilla::NumberIsInt32(d, &i))
847 return INT_TO_JSVAL(i);
848 return DOUBLE_TO_JSVAL(d);
851 /************************************************************************/
853 JS_PUBLIC_API(bool)
854 JS_StringHasBeenInterned(JSContext* cx, JSString* str);
856 namespace JS {
858 // Container class for passing in script source buffers to the JS engine. This
859 // not only groups the buffer and length values, it also provides a way to
860 // optionally pass ownership of the buffer to the JS engine without copying.
861 // Rules for use:
863 // 1) The data array must be allocated with js_malloc() or js_realloc() if
864 // ownership is being granted to the SourceBufferHolder.
865 // 2) If ownership is not given to the SourceBufferHolder, then the memory
866 // must be kept alive until the JS compilation is complete.
867 // 3) Any code calling SourceBufferHolder::take() must guarantee to keep the
868 // memory alive until JS compilation completes. Normally only the JS
869 // engine should be calling take().
871 // Example use:
873 // size_t length = 512;
874 // char16_t* chars = static_cast<char16_t*>(js_malloc(sizeof(char16_t) * length));
875 // JS::SourceBufferHolder srcBuf(chars, length, JS::SourceBufferHolder::GiveOwnership);
876 // JS::Compile(cx, obj, options, srcBuf);
878 class MOZ_STACK_CLASS SourceBufferHolder MOZ_FINAL
880 public:
881 enum Ownership {
882 NoOwnership,
883 GiveOwnership
886 SourceBufferHolder(const char16_t* data, size_t dataLength, Ownership ownership)
887 : data_(data),
888 length_(dataLength),
889 ownsChars_(ownership == GiveOwnership)
891 // Ensure that null buffers properly return an unowned, empty,
892 // null-terminated string.
893 static const char16_t NullChar_ = 0;
894 if (!get()) {
895 data_ = &NullChar_;
896 length_ = 0;
897 ownsChars_ = false;
901 ~SourceBufferHolder() {
902 if (ownsChars_)
903 js_free(const_cast<char16_t*>(data_));
906 // Access the underlying source buffer without affecting ownership.
907 const char16_t* get() const { return data_; }
909 // Length of the source buffer in char16_t code units (not bytes)
910 size_t length() const { return length_; }
912 // Returns true if the SourceBufferHolder owns the buffer and will free
913 // it upon destruction. If true, it is legal to call take().
914 bool ownsChars() const { return ownsChars_; }
916 // Retrieve and take ownership of the underlying data buffer. The caller
917 // is now responsible for calling js_free() on the returned value, *but only
918 // after JS script compilation has completed*.
920 // After the buffer has been taken the SourceBufferHolder functions as if
921 // it had been constructed on an unowned buffer; get() and length() still
922 // work. In order for this to be safe the taken buffer must be kept alive
923 // until after JS script compilation completes as noted above.
925 // Note, it's the caller's responsibility to check ownsChars() before taking
926 // the buffer. Taking and then free'ing an unowned buffer will have dire
927 // consequences.
928 char16_t* take() {
929 MOZ_ASSERT(ownsChars_);
930 ownsChars_ = false;
931 return const_cast<char16_t*>(data_);
934 private:
935 SourceBufferHolder(SourceBufferHolder&) = delete;
936 SourceBufferHolder& operator=(SourceBufferHolder&) = delete;
938 const char16_t* data_;
939 size_t length_;
940 bool ownsChars_;
943 } /* namespace JS */
945 /************************************************************************/
947 /* Property attributes, set in JSPropertySpec and passed to API functions.
949 * NB: The data structure in which some of these values are stored only uses
950 * a uint8_t to store the relevant information. Proceed with caution if
951 * trying to reorder or change the the first byte worth of flags.
953 #define JSPROP_ENUMERATE 0x01 /* property is visible to for/in loop */
954 #define JSPROP_READONLY 0x02 /* not settable: assignment is no-op.
955 This flag is only valid when neither
956 JSPROP_GETTER nor JSPROP_SETTER is
957 set. */
958 #define JSPROP_PERMANENT 0x04 /* property cannot be deleted */
959 #define JSPROP_PROPOP_ACCESSORS 0x08 /* Passed to JS_Define(UC)Property* and
960 JS_DefineElement if getters/setters
961 are JSPropertyOp/JSStrictPropertyOp */
962 #define JSPROP_GETTER 0x10 /* property holds getter function */
963 #define JSPROP_SETTER 0x20 /* property holds setter function */
964 #define JSPROP_SHARED 0x40 /* don't allocate a value slot for this
965 property; don't copy the property on
966 set of the same-named property in an
967 object that delegates to a prototype
968 containing this property */
969 #define JSPROP_INDEX 0x80 /* name is actually (int) index */
970 #define JSPROP_DEFINE_LATE 0x100 /* Don't define property when initially creating
971 the constructor. Some objects like Function/Object
972 have self-hosted functions that can only be defined
973 after the initialization is already finished. */
974 #define JSFUN_STUB_GSOPS 0x200 /* use JS_PropertyStub getter/setter
975 instead of defaulting to class gsops
976 for property holding function */
978 #define JSFUN_CONSTRUCTOR 0x400 /* native that can be called as a ctor */
980 #define JSPROP_REDEFINE_NONCONFIGURABLE 0x800 /* If set, will allow redefining a
981 non-configurable property, but
982 only on a non-DOM global. This
983 is a temporary hack that will
984 need to go away in bug
985 1105518 */
987 #define JSPROP_IGNORE_ENUMERATE 0x1000 /* ignore the value in JSPROP_ENUMERATE.
988 This flag only valid when defining over
989 an existing property. */
990 #define JSPROP_IGNORE_READONLY 0x2000 /* ignore the value in JSPROP_READONLY.
991 This flag only valid when defining over
992 an existing property. */
993 #define JSPROP_IGNORE_PERMANENT 0x4000 /* ignore the value in JSPROP_PERMANENT.
994 This flag only valid when defining over
995 an existing property. */
996 #define JSPROP_IGNORE_VALUE 0x8000 /* ignore the Value in the descriptor. Nothing was
997 specified when passed to Object.defineProperty
998 from script. */
1001 * Specify a generic native prototype methods, i.e., methods of a class
1002 * prototype that are exposed as static methods taking an extra leading
1003 * argument: the generic |this| parameter.
1005 * If you set this flag in a JSFunctionSpec struct's flags initializer, then
1006 * that struct must live at least as long as the native static method object
1007 * created due to this flag by JS_DefineFunctions or JS_InitClass. Typically
1008 * JSFunctionSpec structs are allocated in static arrays.
1010 #define JSFUN_GENERIC_NATIVE 0x800
1012 #define JSFUN_FLAGS_MASK 0xe00 /* | of all the JSFUN_* flags */
1015 * The first call to JS_CallOnce by any thread in a process will call 'func'.
1016 * Later calls to JS_CallOnce with the same JSCallOnceType object will be
1017 * suppressed.
1019 * Equivalently: each distinct JSCallOnceType object will allow one JS_CallOnce
1020 * to invoke its JSInitCallback.
1022 extern JS_PUBLIC_API(bool)
1023 JS_CallOnce(JSCallOnceType* once, JSInitCallback func);
1025 /* Microseconds since the epoch, midnight, January 1, 1970 UTC. */
1026 extern JS_PUBLIC_API(int64_t)
1027 JS_Now(void);
1029 /* Don't want to export data, so provide accessors for non-inline jsvals. */
1030 extern JS_PUBLIC_API(jsval)
1031 JS_GetNaNValue(JSContext* cx);
1033 extern JS_PUBLIC_API(jsval)
1034 JS_GetNegativeInfinityValue(JSContext* cx);
1036 extern JS_PUBLIC_API(jsval)
1037 JS_GetPositiveInfinityValue(JSContext* cx);
1039 extern JS_PUBLIC_API(jsval)
1040 JS_GetEmptyStringValue(JSContext* cx);
1042 extern JS_PUBLIC_API(JSString*)
1043 JS_GetEmptyString(JSRuntime* rt);
1046 * Format is a string of the following characters (spaces are insignificant),
1047 * specifying the tabulated type conversions:
1049 * b bool Boolean
1050 * c char16_t ECMA uint16_t, Unicode character
1051 * i int32_t ECMA int32_t
1052 * j int32_t ECMA int32_t (used to be different)
1053 * u uint32_t ECMA uint32_t
1054 * d double IEEE double
1055 * I double Integral IEEE double
1056 * S JSString * Unicode string, accessed by a JSString pointer
1057 * W char16_t * Unicode character vector, 0-terminated (W for wide)
1058 * o JSObject * Object reference
1059 * f JSFunction * Function private
1060 * v jsval Argument value (no conversion)
1061 * * N/A Skip this argument (no vararg)
1062 * / N/A End of required arguments
1064 * The variable argument list after format must consist of &b, &c, &s, e.g.,
1065 * where those variables have the types given above. For the pointer types
1066 * char*, JSString*, and JSObject*, the pointed-at memory returned belongs
1067 * to the JS runtime, not to the calling native code. The runtime promises
1068 * to keep this memory valid so long as argv refers to allocated stack space
1069 * (so long as the native function is active).
1071 * Fewer arguments than format specifies may be passed only if there is a /
1072 * in format after the last required argument specifier and argc is at least
1073 * the number of required arguments. More arguments than format specifies
1074 * may be passed without error; it is up to the caller to deal with trailing
1075 * unconverted arguments.
1077 extern JS_PUBLIC_API(bool)
1078 JS_ConvertArguments(JSContext* cx, const JS::CallArgs& args, const char* format, ...);
1080 #ifdef va_start
1081 extern JS_PUBLIC_API(bool)
1082 JS_ConvertArgumentsVA(JSContext* cx, const JS::CallArgs& args, const char* format,
1083 va_list ap);
1084 #endif
1086 extern JS_PUBLIC_API(bool)
1087 JS_ConvertValue(JSContext* cx, JS::HandleValue v, JSType type, JS::MutableHandleValue vp);
1089 extern JS_PUBLIC_API(bool)
1090 JS_ValueToObject(JSContext* cx, JS::HandleValue v, JS::MutableHandleObject objp);
1092 extern JS_PUBLIC_API(JSFunction*)
1093 JS_ValueToFunction(JSContext* cx, JS::HandleValue v);
1095 extern JS_PUBLIC_API(JSFunction*)
1096 JS_ValueToConstructor(JSContext* cx, JS::HandleValue v);
1098 extern JS_PUBLIC_API(JSString*)
1099 JS_ValueToSource(JSContext* cx, JS::Handle<JS::Value> v);
1101 namespace js {
1103 * DO NOT CALL THIS. Use JS::ToNumber
1105 extern JS_PUBLIC_API(bool)
1106 ToNumberSlow(JSContext* cx, JS::Value v, double* dp);
1109 * DO NOT CALL THIS. Use JS::ToBoolean
1111 extern JS_PUBLIC_API(bool)
1112 ToBooleanSlow(JS::HandleValue v);
1115 * DO NOT CALL THIS. Use JS::ToString
1117 extern JS_PUBLIC_API(JSString*)
1118 ToStringSlow(JSContext* cx, JS::HandleValue v);
1121 * DO NOT CALL THIS. Use JS::ToObject.
1123 extern JS_PUBLIC_API(JSObject*)
1124 ToObjectSlow(JSContext* cx, JS::HandleValue vp, bool reportScanStack);
1126 } /* namespace js */
1128 namespace JS {
1130 /* ES5 9.3 ToNumber. */
1131 MOZ_ALWAYS_INLINE bool
1132 ToNumber(JSContext* cx, HandleValue v, double* out)
1134 AssertArgumentsAreSane(cx, v);
1136 if (v.isNumber()) {
1137 *out = v.toNumber();
1138 return true;
1140 return js::ToNumberSlow(cx, v, out);
1143 MOZ_ALWAYS_INLINE bool
1144 ToBoolean(HandleValue v)
1146 if (v.isBoolean())
1147 return v.toBoolean();
1148 if (v.isInt32())
1149 return v.toInt32() != 0;
1150 if (v.isNullOrUndefined())
1151 return false;
1152 if (v.isDouble()) {
1153 double d = v.toDouble();
1154 return !mozilla::IsNaN(d) && d != 0;
1156 if (v.isSymbol())
1157 return true;
1159 /* The slow path handles strings and objects. */
1160 return js::ToBooleanSlow(v);
1163 MOZ_ALWAYS_INLINE JSString*
1164 ToString(JSContext* cx, HandleValue v)
1166 if (v.isString())
1167 return v.toString();
1168 return js::ToStringSlow(cx, v);
1171 /* ES5 9.9 ToObject. */
1172 MOZ_ALWAYS_INLINE JSObject*
1173 ToObject(JSContext* cx, HandleValue vp)
1175 if (vp.isObject())
1176 return &vp.toObject();
1177 return js::ToObjectSlow(cx, vp, false);
1181 * Implements ES6 draft rev 28 (2014 Oct 14) 7.1.1, second algorithm.
1183 * Most users should not call this -- use JS::ToNumber, ToBoolean, or ToString
1184 * instead. This should only be called from custom convert hooks. It implements
1185 * the default conversion behavior shared by most objects in JS, so it's useful
1186 * as a fallback.
1188 extern JS_PUBLIC_API(bool)
1189 OrdinaryToPrimitive(JSContext* cx, HandleObject obj, JSType type, MutableHandleValue vp);
1191 } /* namespace JS */
1193 extern JS_PUBLIC_API(bool)
1194 JS_DoubleIsInt32(double d, int32_t* ip);
1196 extern JS_PUBLIC_API(int32_t)
1197 JS_DoubleToInt32(double d);
1199 extern JS_PUBLIC_API(uint32_t)
1200 JS_DoubleToUint32(double d);
1203 namespace js {
1204 /* DO NOT CALL THIS. Use JS::ToUint16. */
1205 extern JS_PUBLIC_API(bool)
1206 ToUint16Slow(JSContext* cx, JS::HandleValue v, uint16_t* out);
1208 /* DO NOT CALL THIS. Use JS::ToInt32. */
1209 extern JS_PUBLIC_API(bool)
1210 ToInt32Slow(JSContext* cx, JS::HandleValue v, int32_t* out);
1212 /* DO NOT CALL THIS. Use JS::ToUint32. */
1213 extern JS_PUBLIC_API(bool)
1214 ToUint32Slow(JSContext* cx, JS::HandleValue v, uint32_t* out);
1216 /* DO NOT CALL THIS. Use JS::ToInt64. */
1217 extern JS_PUBLIC_API(bool)
1218 ToInt64Slow(JSContext* cx, JS::HandleValue v, int64_t* out);
1220 /* DO NOT CALL THIS. Use JS::ToUint64. */
1221 extern JS_PUBLIC_API(bool)
1222 ToUint64Slow(JSContext* cx, JS::HandleValue v, uint64_t* out);
1223 } /* namespace js */
1225 namespace JS {
1227 MOZ_ALWAYS_INLINE bool
1228 ToUint16(JSContext* cx, JS::HandleValue v, uint16_t* out)
1230 AssertArgumentsAreSane(cx, v);
1232 if (v.isInt32()) {
1233 *out = uint16_t(v.toInt32());
1234 return true;
1236 return js::ToUint16Slow(cx, v, out);
1239 MOZ_ALWAYS_INLINE bool
1240 ToInt32(JSContext* cx, JS::HandleValue v, int32_t* out)
1242 AssertArgumentsAreSane(cx, v);
1244 if (v.isInt32()) {
1245 *out = v.toInt32();
1246 return true;
1248 return js::ToInt32Slow(cx, v, out);
1251 MOZ_ALWAYS_INLINE bool
1252 ToUint32(JSContext* cx, JS::HandleValue v, uint32_t* out)
1254 AssertArgumentsAreSane(cx, v);
1256 if (v.isInt32()) {
1257 *out = uint32_t(v.toInt32());
1258 return true;
1260 return js::ToUint32Slow(cx, v, out);
1263 MOZ_ALWAYS_INLINE bool
1264 ToInt64(JSContext* cx, JS::HandleValue v, int64_t* out)
1266 AssertArgumentsAreSane(cx, v);
1268 if (v.isInt32()) {
1269 *out = int64_t(v.toInt32());
1270 return true;
1272 return js::ToInt64Slow(cx, v, out);
1275 MOZ_ALWAYS_INLINE bool
1276 ToUint64(JSContext* cx, JS::HandleValue v, uint64_t* out)
1278 AssertArgumentsAreSane(cx, v);
1280 if (v.isInt32()) {
1281 /* Account for sign extension of negatives into the longer 64bit space. */
1282 *out = uint64_t(int64_t(v.toInt32()));
1283 return true;
1285 return js::ToUint64Slow(cx, v, out);
1289 } /* namespace JS */
1291 extern JS_PUBLIC_API(JSType)
1292 JS_TypeOfValue(JSContext* cx, JS::Handle<JS::Value> v);
1294 extern JS_PUBLIC_API(bool)
1295 JS_StrictlyEqual(JSContext* cx, jsval v1, jsval v2, bool* equal);
1297 extern JS_PUBLIC_API(bool)
1298 JS_LooselyEqual(JSContext* cx, JS::Handle<JS::Value> v1, JS::Handle<JS::Value> v2, bool* equal);
1300 extern JS_PUBLIC_API(bool)
1301 JS_SameValue(JSContext* cx, jsval v1, jsval v2, bool* same);
1303 /* True iff fun is the global eval function. */
1304 extern JS_PUBLIC_API(bool)
1305 JS_IsBuiltinEvalFunction(JSFunction* fun);
1307 /* True iff fun is the Function constructor. */
1308 extern JS_PUBLIC_API(bool)
1309 JS_IsBuiltinFunctionConstructor(JSFunction* fun);
1311 /************************************************************************/
1314 * Initialization, locking, contexts, and memory allocation.
1316 * It is important that the first runtime and first context be created in a
1317 * single-threaded fashion, otherwise the behavior of the library is undefined.
1318 * See: http://developer.mozilla.org/en/docs/Category:JSAPI_Reference
1322 * Initialize SpiderMonkey, returning true only if initialization succeeded.
1323 * Once this method has succeeded, it is safe to call JS_NewRuntime and other
1324 * JSAPI methods.
1326 * This method must be called before any other JSAPI method is used on any
1327 * thread. Once it has been used, it is safe to call any JSAPI method, and it
1328 * remains safe to do so until JS_ShutDown is correctly called.
1330 * It is currently not possible to initialize SpiderMonkey multiple times (that
1331 * is, calling JS_Init/JSAPI methods/JS_ShutDown in that order, then doing so
1332 * again). This restriction may eventually be lifted.
1334 extern JS_PUBLIC_API(bool)
1335 JS_Init(void);
1338 * Destroy free-standing resources allocated by SpiderMonkey, not associated
1339 * with any runtime, context, or other structure.
1341 * This method should be called after all other JSAPI data has been properly
1342 * cleaned up: every new runtime must have been destroyed, every new context
1343 * must have been destroyed, and so on. Calling this method before all other
1344 * resources have been destroyed has undefined behavior.
1346 * Failure to call this method, at present, has no adverse effects other than
1347 * leaking memory. This may not always be the case; it's recommended that all
1348 * embedders call this method when all other JSAPI operations have completed.
1350 * It is currently not possible to initialize SpiderMonkey multiple times (that
1351 * is, calling JS_Init/JSAPI methods/JS_ShutDown in that order, then doing so
1352 * again). This restriction may eventually be lifted.
1354 extern JS_PUBLIC_API(void)
1355 JS_ShutDown(void);
1357 extern JS_PUBLIC_API(JSRuntime*)
1358 JS_NewRuntime(uint32_t maxbytes,
1359 uint32_t maxNurseryBytes = JS::DefaultNurseryBytes,
1360 JSRuntime* parentRuntime = nullptr);
1362 extern JS_PUBLIC_API(void)
1363 JS_DestroyRuntime(JSRuntime* rt);
1365 // These are equivalent to ICU's |UMemAllocFn|, |UMemReallocFn|, and
1366 // |UMemFreeFn| types. The first argument (called |context| in the ICU docs)
1367 // will always be nullptr, and should be ignored.
1368 typedef void* (*JS_ICUAllocFn)(const void*, size_t size);
1369 typedef void* (*JS_ICUReallocFn)(const void*, void* p, size_t size);
1370 typedef void (*JS_ICUFreeFn)(const void*, void* p);
1372 // This function can be used to track memory used by ICU.
1373 // Do not use it unless you know what you are doing!
1374 extern JS_PUBLIC_API(bool)
1375 JS_SetICUMemoryFunctions(JS_ICUAllocFn allocFn, JS_ICUReallocFn reallocFn, JS_ICUFreeFn freeFn);
1377 JS_PUBLIC_API(void*)
1378 JS_GetRuntimePrivate(JSRuntime* rt);
1380 extern JS_PUBLIC_API(JSRuntime*)
1381 JS_GetRuntime(JSContext* cx);
1383 extern JS_PUBLIC_API(JSRuntime*)
1384 JS_GetParentRuntime(JSContext* cx);
1386 JS_PUBLIC_API(void)
1387 JS_SetRuntimePrivate(JSRuntime* rt, void* data);
1389 extern JS_PUBLIC_API(void)
1390 JS_BeginRequest(JSContext* cx);
1392 extern JS_PUBLIC_API(void)
1393 JS_EndRequest(JSContext* cx);
1395 namespace js {
1397 void
1398 AssertHeapIsIdle(JSRuntime* rt);
1400 void
1401 AssertHeapIsIdle(JSContext* cx);
1403 } /* namespace js */
1405 class JSAutoRequest
1407 public:
1408 explicit JSAutoRequest(JSContext* cx
1409 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
1410 : mContext(cx)
1412 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
1413 JS_BeginRequest(mContext);
1415 ~JSAutoRequest() {
1416 JS_EndRequest(mContext);
1419 protected:
1420 JSContext* mContext;
1421 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
1423 #if 0
1424 private:
1425 static void* operator new(size_t) CPP_THROW_NEW { return 0; }
1426 static void operator delete(void*, size_t) { }
1427 #endif
1430 extern JS_PUBLIC_API(void)
1431 JS_SetContextCallback(JSRuntime* rt, JSContextCallback cxCallback, void* data);
1433 extern JS_PUBLIC_API(JSContext*)
1434 JS_NewContext(JSRuntime* rt, size_t stackChunkSize);
1436 extern JS_PUBLIC_API(void)
1437 JS_DestroyContext(JSContext* cx);
1439 extern JS_PUBLIC_API(void)
1440 JS_DestroyContextNoGC(JSContext* cx);
1442 extern JS_PUBLIC_API(void*)
1443 JS_GetContextPrivate(JSContext* cx);
1445 extern JS_PUBLIC_API(void)
1446 JS_SetContextPrivate(JSContext* cx, void* data);
1448 extern JS_PUBLIC_API(void*)
1449 JS_GetSecondContextPrivate(JSContext* cx);
1451 extern JS_PUBLIC_API(void)
1452 JS_SetSecondContextPrivate(JSContext* cx, void* data);
1454 extern JS_PUBLIC_API(JSRuntime*)
1455 JS_GetRuntime(JSContext* cx);
1457 extern JS_PUBLIC_API(JSContext*)
1458 JS_ContextIterator(JSRuntime* rt, JSContext** iterp);
1460 extern JS_PUBLIC_API(JSVersion)
1461 JS_GetVersion(JSContext* cx);
1463 // Mutate the version on the compartment. This is generally discouraged, but
1464 // necessary to support the version mutation in the js and xpc shell command
1465 // set.
1467 // It would be nice to put this in jsfriendapi, but the linkage requirements
1468 // of the shells make that impossible.
1469 JS_PUBLIC_API(void)
1470 JS_SetVersionForCompartment(JSCompartment* compartment, JSVersion version);
1472 extern JS_PUBLIC_API(const char*)
1473 JS_VersionToString(JSVersion version);
1475 extern JS_PUBLIC_API(JSVersion)
1476 JS_StringToVersion(const char* string);
1478 namespace JS {
1480 class JS_PUBLIC_API(RuntimeOptions) {
1481 public:
1482 RuntimeOptions()
1483 : baseline_(false),
1484 ion_(false),
1485 asmJS_(false),
1486 nativeRegExp_(false),
1487 werror_(false),
1488 strictMode_(false),
1489 extraWarnings_(false),
1490 varObjFix_(false)
1494 bool baseline() const { return baseline_; }
1495 RuntimeOptions& setBaseline(bool flag) {
1496 baseline_ = flag;
1497 return *this;
1499 RuntimeOptions& toggleBaseline() {
1500 baseline_ = !baseline_;
1501 return *this;
1504 bool ion() const { return ion_; }
1505 RuntimeOptions& setIon(bool flag) {
1506 ion_ = flag;
1507 return *this;
1509 RuntimeOptions& toggleIon() {
1510 ion_ = !ion_;
1511 return *this;
1514 bool asmJS() const { return asmJS_; }
1515 RuntimeOptions& setAsmJS(bool flag) {
1516 asmJS_ = flag;
1517 return *this;
1519 RuntimeOptions& toggleAsmJS() {
1520 asmJS_ = !asmJS_;
1521 return *this;
1524 bool nativeRegExp() const { return nativeRegExp_; }
1525 RuntimeOptions& setNativeRegExp(bool flag) {
1526 nativeRegExp_ = flag;
1527 return *this;
1530 bool werror() const { return werror_; }
1531 RuntimeOptions& setWerror(bool flag) {
1532 werror_ = flag;
1533 return *this;
1535 RuntimeOptions& toggleWerror() {
1536 werror_ = !werror_;
1537 return *this;
1540 bool strictMode() const { return strictMode_; }
1541 RuntimeOptions& setStrictMode(bool flag) {
1542 strictMode_ = flag;
1543 return *this;
1545 RuntimeOptions& toggleStrictMode() {
1546 strictMode_ = !strictMode_;
1547 return *this;
1550 bool extraWarnings() const { return extraWarnings_; }
1551 RuntimeOptions& setExtraWarnings(bool flag) {
1552 extraWarnings_ = flag;
1553 return *this;
1555 RuntimeOptions& toggleExtraWarnings() {
1556 extraWarnings_ = !extraWarnings_;
1557 return *this;
1560 bool varObjFix() const { return varObjFix_; }
1561 RuntimeOptions& setVarObjFix(bool flag) {
1562 varObjFix_ = flag;
1563 return *this;
1565 RuntimeOptions& toggleVarObjFix() {
1566 varObjFix_ = !varObjFix_;
1567 return *this;
1570 private:
1571 bool baseline_ : 1;
1572 bool ion_ : 1;
1573 bool asmJS_ : 1;
1574 bool nativeRegExp_ : 1;
1575 bool werror_ : 1;
1576 bool strictMode_ : 1;
1577 bool extraWarnings_ : 1;
1578 bool varObjFix_ : 1;
1581 JS_PUBLIC_API(RuntimeOptions&)
1582 RuntimeOptionsRef(JSRuntime* rt);
1584 JS_PUBLIC_API(RuntimeOptions&)
1585 RuntimeOptionsRef(JSContext* cx);
1587 class JS_PUBLIC_API(ContextOptions) {
1588 public:
1589 ContextOptions()
1590 : privateIsNSISupports_(false),
1591 dontReportUncaught_(false),
1592 autoJSAPIOwnsErrorReporting_(false)
1596 bool privateIsNSISupports() const { return privateIsNSISupports_; }
1597 ContextOptions& setPrivateIsNSISupports(bool flag) {
1598 privateIsNSISupports_ = flag;
1599 return *this;
1601 ContextOptions& togglePrivateIsNSISupports() {
1602 privateIsNSISupports_ = !privateIsNSISupports_;
1603 return *this;
1606 bool dontReportUncaught() const { return dontReportUncaught_; }
1607 ContextOptions& setDontReportUncaught(bool flag) {
1608 dontReportUncaught_ = flag;
1609 return *this;
1611 ContextOptions& toggleDontReportUncaught() {
1612 dontReportUncaught_ = !dontReportUncaught_;
1613 return *this;
1616 bool autoJSAPIOwnsErrorReporting() const { return autoJSAPIOwnsErrorReporting_; }
1617 ContextOptions& setAutoJSAPIOwnsErrorReporting(bool flag) {
1618 autoJSAPIOwnsErrorReporting_ = flag;
1619 return *this;
1621 ContextOptions& toggleAutoJSAPIOwnsErrorReporting() {
1622 autoJSAPIOwnsErrorReporting_ = !autoJSAPIOwnsErrorReporting_;
1623 return *this;
1627 private:
1628 bool privateIsNSISupports_ : 1;
1629 bool dontReportUncaught_ : 1;
1630 // dontReportUncaught isn't respected by all JSAPI codepaths, particularly the
1631 // JS_ReportError* functions that eventually report the error even when dontReportUncaught is
1632 // set, if script is not running. We want a way to indicate that the embedder will always
1633 // handle any exceptions, and that SpiderMonkey should just leave them on the context. This is
1634 // the way we want to do all future error handling in Gecko - stealing the exception explicitly
1635 // from the context and handling it as per the situation. This will eventually become the
1636 // default and these 2 flags should go away.
1637 bool autoJSAPIOwnsErrorReporting_ : 1;
1640 JS_PUBLIC_API(ContextOptions&)
1641 ContextOptionsRef(JSContext* cx);
1643 class JS_PUBLIC_API(AutoSaveContextOptions) {
1644 public:
1645 explicit AutoSaveContextOptions(JSContext* cx)
1646 : cx_(cx),
1647 oldOptions_(ContextOptionsRef(cx_))
1651 ~AutoSaveContextOptions()
1653 ContextOptionsRef(cx_) = oldOptions_;
1656 private:
1657 JSContext* cx_;
1658 JS::ContextOptions oldOptions_;
1661 } /* namespace JS */
1663 extern JS_PUBLIC_API(const char*)
1664 JS_GetImplementationVersion(void);
1666 extern JS_PUBLIC_API(void)
1667 JS_SetDestroyCompartmentCallback(JSRuntime* rt, JSDestroyCompartmentCallback callback);
1669 extern JS_PUBLIC_API(void)
1670 JS_SetDestroyZoneCallback(JSRuntime* rt, JSZoneCallback callback);
1672 extern JS_PUBLIC_API(void)
1673 JS_SetSweepZoneCallback(JSRuntime* rt, JSZoneCallback callback);
1675 extern JS_PUBLIC_API(void)
1676 JS_SetCompartmentNameCallback(JSRuntime* rt, JSCompartmentNameCallback callback);
1678 extern JS_PUBLIC_API(void)
1679 JS_SetWrapObjectCallbacks(JSRuntime* rt, const JSWrapObjectCallbacks* callbacks);
1681 extern JS_PUBLIC_API(void)
1682 JS_SetCompartmentPrivate(JSCompartment* compartment, void* data);
1684 extern JS_PUBLIC_API(void*)
1685 JS_GetCompartmentPrivate(JSCompartment* compartment);
1687 extern JS_PUBLIC_API(void)
1688 JS_SetZoneUserData(JS::Zone* zone, void* data);
1690 extern JS_PUBLIC_API(void*)
1691 JS_GetZoneUserData(JS::Zone* zone);
1693 extern JS_PUBLIC_API(bool)
1694 JS_WrapObject(JSContext* cx, JS::MutableHandleObject objp);
1696 extern JS_PUBLIC_API(bool)
1697 JS_WrapValue(JSContext* cx, JS::MutableHandleValue vp);
1699 extern JS_PUBLIC_API(JSObject*)
1700 JS_TransplantObject(JSContext* cx, JS::HandleObject origobj, JS::HandleObject target);
1702 extern JS_PUBLIC_API(bool)
1703 JS_RefreshCrossCompartmentWrappers(JSContext* cx, JS::Handle<JSObject*> obj);
1706 * At any time, a JSContext has a current (possibly-nullptr) compartment.
1707 * Compartments are described in:
1709 * developer.mozilla.org/en-US/docs/SpiderMonkey/SpiderMonkey_compartments
1711 * The current compartment of a context may be changed. The preferred way to do
1712 * this is with JSAutoCompartment:
1714 * void foo(JSContext* cx, JSObject* obj) {
1715 * // in some compartment 'c'
1717 * JSAutoCompartment ac(cx, obj); // constructor enters
1718 * // in the compartment of 'obj'
1719 * } // destructor leaves
1720 * // back in compartment 'c'
1723 * For more complicated uses that don't neatly fit in a C++ stack frame, the
1724 * compartment can entered and left using separate function calls:
1726 * void foo(JSContext* cx, JSObject* obj) {
1727 * // in 'oldCompartment'
1728 * JSCompartment* oldCompartment = JS_EnterCompartment(cx, obj);
1729 * // in the compartment of 'obj'
1730 * JS_LeaveCompartment(cx, oldCompartment);
1731 * // back in 'oldCompartment'
1734 * Note: these calls must still execute in a LIFO manner w.r.t all other
1735 * enter/leave calls on the context. Furthermore, only the return value of a
1736 * JS_EnterCompartment call may be passed as the 'oldCompartment' argument of
1737 * the corresponding JS_LeaveCompartment call.
1740 class JS_PUBLIC_API(JSAutoCompartment)
1742 JSContext* cx_;
1743 JSCompartment* oldCompartment_;
1744 public:
1745 JSAutoCompartment(JSContext* cx, JSObject* target);
1746 JSAutoCompartment(JSContext* cx, JSScript* target);
1747 ~JSAutoCompartment();
1750 class JS_PUBLIC_API(JSAutoNullableCompartment)
1752 JSContext* cx_;
1753 JSCompartment* oldCompartment_;
1754 public:
1755 explicit JSAutoNullableCompartment(JSContext* cx, JSObject* targetOrNull);
1756 ~JSAutoNullableCompartment();
1759 /* NB: This API is infallible; a nullptr return value does not indicate error. */
1760 extern JS_PUBLIC_API(JSCompartment*)
1761 JS_EnterCompartment(JSContext* cx, JSObject* target);
1763 extern JS_PUBLIC_API(void)
1764 JS_LeaveCompartment(JSContext* cx, JSCompartment* oldCompartment);
1766 typedef void (*JSIterateCompartmentCallback)(JSRuntime* rt, void* data, JSCompartment* compartment);
1769 * This function calls |compartmentCallback| on every compartment. Beware that
1770 * there is no guarantee that the compartment will survive after the callback
1771 * returns. Also, if the callback can GC, there is no guarantee that every
1772 * compartment will be visited.
1774 extern JS_PUBLIC_API(void)
1775 JS_IterateCompartments(JSRuntime* rt, void* data,
1776 JSIterateCompartmentCallback compartmentCallback);
1779 * Initialize standard JS class constructors, prototypes, and any top-level
1780 * functions and constants associated with the standard classes (e.g. isNaN
1781 * for Number).
1783 * NB: This sets cx's global object to obj if it was null.
1785 extern JS_PUBLIC_API(bool)
1786 JS_InitStandardClasses(JSContext* cx, JS::Handle<JSObject*> obj);
1789 * Resolve id, which must contain either a string or an int, to a standard
1790 * class name in obj if possible, defining the class's constructor and/or
1791 * prototype and storing true in *resolved. If id does not name a standard
1792 * class or a top-level property induced by initializing a standard class,
1793 * store false in *resolved and just return true. Return false on error,
1794 * as usual for bool result-typed API entry points.
1796 * This API can be called directly from a global object class's resolve op,
1797 * to define standard classes lazily. The class's enumerate op should call
1798 * JS_EnumerateStandardClasses(cx, obj), to define eagerly during for..in
1799 * loops any classes not yet resolved lazily.
1801 extern JS_PUBLIC_API(bool)
1802 JS_ResolveStandardClass(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* resolved);
1804 extern JS_PUBLIC_API(bool)
1805 JS_EnumerateStandardClasses(JSContext* cx, JS::HandleObject obj);
1807 extern JS_PUBLIC_API(bool)
1808 JS_GetClassObject(JSContext* cx, JSProtoKey key, JS::MutableHandle<JSObject*> objp);
1810 extern JS_PUBLIC_API(bool)
1811 JS_GetClassPrototype(JSContext* cx, JSProtoKey key, JS::MutableHandle<JSObject*> objp);
1813 namespace JS {
1816 * Determine if the given object is an instance/prototype/constructor for a standard
1817 * class. If so, return the associated JSProtoKey. If not, return JSProto_Null.
1820 extern JS_PUBLIC_API(JSProtoKey)
1821 IdentifyStandardInstance(JSObject* obj);
1823 extern JS_PUBLIC_API(JSProtoKey)
1824 IdentifyStandardPrototype(JSObject* obj);
1826 extern JS_PUBLIC_API(JSProtoKey)
1827 IdentifyStandardInstanceOrPrototype(JSObject* obj);
1829 extern JS_PUBLIC_API(JSProtoKey)
1830 IdentifyStandardConstructor(JSObject* obj);
1832 extern JS_PUBLIC_API(void)
1833 ProtoKeyToId(JSContext* cx, JSProtoKey key, JS::MutableHandleId idp);
1835 } /* namespace JS */
1837 extern JS_PUBLIC_API(JSProtoKey)
1838 JS_IdToProtoKey(JSContext* cx, JS::HandleId id);
1841 * Returns the original value of |Function.prototype| from the global object in
1842 * which |forObj| was created.
1844 extern JS_PUBLIC_API(JSObject*)
1845 JS_GetFunctionPrototype(JSContext* cx, JS::HandleObject forObj);
1848 * Returns the original value of |Object.prototype| from the global object in
1849 * which |forObj| was created.
1851 extern JS_PUBLIC_API(JSObject*)
1852 JS_GetObjectPrototype(JSContext* cx, JS::HandleObject forObj);
1855 * Returns the original value of |Array.prototype| from the global object in
1856 * which |forObj| was created.
1858 extern JS_PUBLIC_API(JSObject*)
1859 JS_GetArrayPrototype(JSContext* cx, JS::HandleObject forObj);
1862 * Returns the original value of |Error.prototype| from the global
1863 * object of the current compartment of cx.
1865 extern JS_PUBLIC_API(JSObject*)
1866 JS_GetErrorPrototype(JSContext* cx);
1868 extern JS_PUBLIC_API(JSObject*)
1869 JS_GetGlobalForObject(JSContext* cx, JSObject* obj);
1871 extern JS_PUBLIC_API(bool)
1872 JS_IsGlobalObject(JSObject* obj);
1875 * May return nullptr, if |c| never had a global (e.g. the atoms compartment),
1876 * or if |c|'s global has been collected.
1878 extern JS_PUBLIC_API(JSObject*)
1879 JS_GetGlobalForCompartmentOrNull(JSContext* cx, JSCompartment* c);
1881 namespace JS {
1883 extern JS_PUBLIC_API(JSObject*)
1884 CurrentGlobalOrNull(JSContext* cx);
1889 * Initialize the 'Reflect' object on a global object.
1891 extern JS_PUBLIC_API(JSObject*)
1892 JS_InitReflect(JSContext* cx, JS::HandleObject global);
1895 * Add various profiling-related functions as properties of the given object.
1896 * Defined in builtin/Profilers.cpp.
1898 extern JS_PUBLIC_API(bool)
1899 JS_DefineProfilingFunctions(JSContext* cx, JS::HandleObject obj);
1901 /* Defined in vm/Debugger.cpp. */
1902 extern JS_PUBLIC_API(bool)
1903 JS_DefineDebuggerObject(JSContext* cx, JS::HandleObject obj);
1905 #ifdef JS_HAS_CTYPES
1907 * Initialize the 'ctypes' object on a global variable 'obj'. The 'ctypes'
1908 * object will be sealed.
1910 extern JS_PUBLIC_API(bool)
1911 JS_InitCTypesClass(JSContext* cx, JS::HandleObject global);
1914 * Convert a unicode string 'source' of length 'slen' to the platform native
1915 * charset, returning a null-terminated string allocated with JS_malloc. On
1916 * failure, this function should report an error.
1918 typedef char*
1919 (* JSCTypesUnicodeToNativeFun)(JSContext* cx, const char16_t* source, size_t slen);
1922 * Set of function pointers that ctypes can use for various internal functions.
1923 * See JS_SetCTypesCallbacks below. Providing nullptr for a function is safe,
1924 * and will result in the applicable ctypes functionality not being available.
1926 struct JSCTypesCallbacks {
1927 JSCTypesUnicodeToNativeFun unicodeToNative;
1930 typedef struct JSCTypesCallbacks JSCTypesCallbacks;
1933 * Set the callbacks on the provided 'ctypesObj' object. 'callbacks' should be a
1934 * pointer to static data that exists for the lifetime of 'ctypesObj', but it
1935 * may safely be altered after calling this function and without having
1936 * to call this function again.
1938 extern JS_PUBLIC_API(void)
1939 JS_SetCTypesCallbacks(JSObject* ctypesObj, const JSCTypesCallbacks* callbacks);
1940 #endif
1942 typedef bool
1943 (* JSEnumerateDiagnosticMemoryCallback)(void* ptr, size_t length);
1946 * Enumerate memory regions that contain diagnostic information
1947 * intended to be included in crash report minidumps.
1949 extern JS_PUBLIC_API(void)
1950 JS_EnumerateDiagnosticMemoryRegions(JSEnumerateDiagnosticMemoryCallback callback);
1952 extern JS_PUBLIC_API(void*)
1953 JS_malloc(JSContext* cx, size_t nbytes);
1955 extern JS_PUBLIC_API(void*)
1956 JS_realloc(JSContext* cx, void* p, size_t oldBytes, size_t newBytes);
1959 * A wrapper for js_free(p) that may delay js_free(p) invocation as a
1960 * performance optimization.
1961 * cx may be nullptr.
1963 extern JS_PUBLIC_API(void)
1964 JS_free(JSContext* cx, void* p);
1967 * A wrapper for js_free(p) that may delay js_free(p) invocation as a
1968 * performance optimization as specified by the given JSFreeOp instance.
1970 extern JS_PUBLIC_API(void)
1971 JS_freeop(JSFreeOp* fop, void* p);
1973 extern JS_PUBLIC_API(JSFreeOp*)
1974 JS_GetDefaultFreeOp(JSRuntime* rt);
1976 extern JS_PUBLIC_API(void)
1977 JS_updateMallocCounter(JSContext* cx, size_t nbytes);
1979 extern JS_PUBLIC_API(char*)
1980 JS_strdup(JSContext* cx, const char* s);
1982 /* Duplicate a string. Does not report an error on failure. */
1983 extern JS_PUBLIC_API(char*)
1984 JS_strdup(JSRuntime* rt, const char* s);
1986 namespace JS {
1989 * A GC root is a pointer to a jsval, JSObject * or JSString * that itself
1990 * points into the GC heap. JS_AddValueRoot takes a pointer to a jsval and
1991 * JS_AddGCThingRoot takes a pointer to a JSObject * or JString*.
1993 * Note that, since JS_Add*Root stores the address of a variable (of type
1994 * jsval, JSString*, or JSObject*), that variable must live until
1995 * JS_Remove*Root is called to remove that variable. For example, after:
1997 * void some_function() {
1998 * jsval v;
1999 * JS_AddNamedValueRoot(cx, &v, "name");
2001 * the caller must perform
2003 * JS_RemoveValueRoot(cx, &v);
2005 * before some_function() returns.
2007 * Also, use JS_AddNamed*Root(cx, &structPtr->memberObj, "structPtr->memberObj")
2008 * in preference to JS_Add*Root(cx, &structPtr->memberObj), in order to identify
2009 * roots by their source callsites. This way, you can find the callsite while
2010 * debugging if you should fail to do JS_Remove*Root(cx, &structPtr->memberObj)
2011 * before freeing structPtr's memory.
2013 extern JS_PUBLIC_API(bool)
2014 AddValueRoot(JSContext* cx, JS::Heap<JS::Value>* vp);
2016 extern JS_PUBLIC_API(bool)
2017 AddStringRoot(JSContext* cx, JS::Heap<JSString*>* rp);
2019 extern JS_PUBLIC_API(bool)
2020 AddObjectRoot(JSContext* cx, JS::Heap<JSObject*>* rp);
2022 extern JS_PUBLIC_API(bool)
2023 AddNamedValueRoot(JSContext* cx, JS::Heap<JS::Value>* vp, const char* name);
2025 extern JS_PUBLIC_API(bool)
2026 AddNamedValueRootRT(JSRuntime* rt, JS::Heap<JS::Value>* vp, const char* name);
2028 extern JS_PUBLIC_API(bool)
2029 AddNamedStringRoot(JSContext* cx, JS::Heap<JSString*>* rp, const char* name);
2031 extern JS_PUBLIC_API(bool)
2032 AddNamedObjectRoot(JSContext* cx, JS::Heap<JSObject*>* rp, const char* name);
2034 extern JS_PUBLIC_API(bool)
2035 AddNamedScriptRoot(JSContext* cx, JS::Heap<JSScript*>* rp, const char* name);
2037 extern JS_PUBLIC_API(void)
2038 RemoveValueRoot(JSContext* cx, JS::Heap<JS::Value>* vp);
2040 extern JS_PUBLIC_API(void)
2041 RemoveStringRoot(JSContext* cx, JS::Heap<JSString*>* rp);
2043 extern JS_PUBLIC_API(void)
2044 RemoveObjectRoot(JSContext* cx, JS::Heap<JSObject*>* rp);
2046 extern JS_PUBLIC_API(void)
2047 RemoveScriptRoot(JSContext* cx, JS::Heap<JSScript*>* rp);
2049 extern JS_PUBLIC_API(void)
2050 RemoveValueRootRT(JSRuntime* rt, JS::Heap<JS::Value>* vp);
2052 extern JS_PUBLIC_API(void)
2053 RemoveStringRootRT(JSRuntime* rt, JS::Heap<JSString*>* rp);
2055 extern JS_PUBLIC_API(void)
2056 RemoveObjectRootRT(JSRuntime* rt, JS::Heap<JSObject*>* rp);
2058 extern JS_PUBLIC_API(void)
2059 RemoveScriptRootRT(JSRuntime* rt, JS::Heap<JSScript*>* rp);
2061 } /* namespace JS */
2064 * Register externally maintained GC roots.
2066 * traceOp: the trace operation. For each root the implementation should call
2067 * JS_CallTracer whenever the root contains a traceable thing.
2068 * data: the data argument to pass to each invocation of traceOp.
2070 extern JS_PUBLIC_API(bool)
2071 JS_AddExtraGCRootsTracer(JSRuntime* rt, JSTraceDataOp traceOp, void* data);
2073 /* Undo a call to JS_AddExtraGCRootsTracer. */
2074 extern JS_PUBLIC_API(void)
2075 JS_RemoveExtraGCRootsTracer(JSRuntime* rt, JSTraceDataOp traceOp, void* data);
2077 #ifdef JS_DEBUG
2080 * Debug-only method to dump the object graph of heap-allocated things.
2082 * fp: file for the dump output.
2083 * start: when non-null, dump only things reachable from start
2084 * thing. Otherwise dump all things reachable from the
2085 * runtime roots.
2086 * startKind: trace kind of start if start is not null. Must be
2087 * JSTRACE_OBJECT when start is null.
2088 * thingToFind: dump only paths in the object graph leading to thingToFind
2089 * when non-null.
2090 * maxDepth: the upper bound on the number of edges to descend from the
2091 * graph roots.
2092 * thingToIgnore: thing to ignore during the graph traversal when non-null.
2094 extern JS_PUBLIC_API(bool)
2095 JS_DumpHeap(JSRuntime* rt, FILE* fp, void* startThing, JSGCTraceKind kind,
2096 void* thingToFind, size_t maxDepth, void* thingToIgnore);
2098 #endif
2101 * Garbage collector API.
2103 extern JS_PUBLIC_API(void)
2104 JS_GC(JSRuntime* rt);
2106 extern JS_PUBLIC_API(void)
2107 JS_MaybeGC(JSContext* cx);
2109 extern JS_PUBLIC_API(void)
2110 JS_SetGCCallback(JSRuntime* rt, JSGCCallback cb, void* data);
2112 extern JS_PUBLIC_API(bool)
2113 JS_AddFinalizeCallback(JSRuntime* rt, JSFinalizeCallback cb, void* data);
2115 extern JS_PUBLIC_API(void)
2116 JS_RemoveFinalizeCallback(JSRuntime* rt, JSFinalizeCallback cb);
2118 extern JS_PUBLIC_API(bool)
2119 JS_IsGCMarkingTracer(JSTracer* trc);
2121 /* For assertions only. */
2122 #ifdef JS_DEBUG
2123 extern JS_PUBLIC_API(bool)
2124 JS_IsMarkingGray(JSTracer* trc);
2125 #endif
2128 * Weak pointers and garbage collection
2130 * Weak pointers are by their nature not marked as part of garbage collection,
2131 * but they may need to be updated in two cases after a GC:
2133 * 1) Their referent was found not to be live and is about to be finalized
2134 * 2) Their referent has been moved by a compacting GC
2136 * To handle this, any part of the system that maintain weak pointers to
2137 * JavaScript GC things must register a callback with
2138 * JS_(Add,Remove)WeakPointerCallback(). This callback must then call
2139 * JS_UpdateWeakPointerAfterGC() on all weak pointers it knows about.
2141 * The argument to JS_UpdateWeakPointerAfterGC() is an in-out param. If the
2142 * referent is about to be finalized the pointer will be set to null. If the
2143 * referent has been moved then the pointer will be updated to point to the new
2144 * location.
2146 * Callers of this method are responsible for updating any state that is
2147 * dependent on the object's address. For example, if the object's address is
2148 * used as a key in a hashtable, then the object must be removed and
2149 * re-inserted with the correct hash.
2152 extern JS_PUBLIC_API(bool)
2153 JS_AddWeakPointerCallback(JSRuntime* rt, JSWeakPointerCallback cb, void* data);
2155 extern JS_PUBLIC_API(void)
2156 JS_RemoveWeakPointerCallback(JSRuntime* rt, JSWeakPointerCallback cb);
2158 extern JS_PUBLIC_API(void)
2159 JS_UpdateWeakPointerAfterGC(JS::Heap<JSObject*>* objp);
2161 extern JS_PUBLIC_API(void)
2162 JS_UpdateWeakPointerAfterGCUnbarriered(JSObject** objp);
2164 typedef enum JSGCParamKey {
2165 /* Maximum nominal heap before last ditch GC. */
2166 JSGC_MAX_BYTES = 0,
2168 /* Number of JS_malloc bytes before last ditch GC. */
2169 JSGC_MAX_MALLOC_BYTES = 1,
2171 /* Amount of bytes allocated by the GC. */
2172 JSGC_BYTES = 3,
2174 /* Number of times GC has been invoked. Includes both major and minor GC. */
2175 JSGC_NUMBER = 4,
2177 /* Max size of the code cache in bytes. */
2178 JSGC_MAX_CODE_CACHE_BYTES = 5,
2180 /* Select GC mode. */
2181 JSGC_MODE = 6,
2183 /* Number of cached empty GC chunks. */
2184 JSGC_UNUSED_CHUNKS = 7,
2186 /* Total number of allocated GC chunks. */
2187 JSGC_TOTAL_CHUNKS = 8,
2189 /* Max milliseconds to spend in an incremental GC slice. */
2190 JSGC_SLICE_TIME_BUDGET = 9,
2192 /* Maximum size the GC mark stack can grow to. */
2193 JSGC_MARK_STACK_LIMIT = 10,
2196 * GCs less than this far apart in time will be considered 'high-frequency GCs'.
2197 * See setGCLastBytes in jsgc.cpp.
2199 JSGC_HIGH_FREQUENCY_TIME_LIMIT = 11,
2201 /* Start of dynamic heap growth. */
2202 JSGC_HIGH_FREQUENCY_LOW_LIMIT = 12,
2204 /* End of dynamic heap growth. */
2205 JSGC_HIGH_FREQUENCY_HIGH_LIMIT = 13,
2207 /* Upper bound of heap growth. */
2208 JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX = 14,
2210 /* Lower bound of heap growth. */
2211 JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN = 15,
2213 /* Heap growth for low frequency GCs. */
2214 JSGC_LOW_FREQUENCY_HEAP_GROWTH = 16,
2217 * If false, the heap growth factor is fixed at 3. If true, it is determined
2218 * based on whether GCs are high- or low- frequency.
2220 JSGC_DYNAMIC_HEAP_GROWTH = 17,
2222 /* If true, high-frequency GCs will use a longer mark slice. */
2223 JSGC_DYNAMIC_MARK_SLICE = 18,
2225 /* Lower limit after which we limit the heap growth. */
2226 JSGC_ALLOCATION_THRESHOLD = 19,
2229 * We decommit memory lazily. If more than this number of megabytes is
2230 * available to be decommitted, then JS_MaybeGC will trigger a shrinking GC
2231 * to decommit it.
2233 JSGC_DECOMMIT_THRESHOLD = 20,
2236 * We try to keep at least this many unused chunks in the free chunk pool at
2237 * all times, even after a shrinking GC.
2239 JSGC_MIN_EMPTY_CHUNK_COUNT = 21,
2241 /* We never keep more than this many unused chunks in the free chunk pool. */
2242 JSGC_MAX_EMPTY_CHUNK_COUNT = 22
2243 } JSGCParamKey;
2245 extern JS_PUBLIC_API(void)
2246 JS_SetGCParameter(JSRuntime* rt, JSGCParamKey key, uint32_t value);
2248 extern JS_PUBLIC_API(uint32_t)
2249 JS_GetGCParameter(JSRuntime* rt, JSGCParamKey key);
2251 extern JS_PUBLIC_API(void)
2252 JS_SetGCParameterForThread(JSContext* cx, JSGCParamKey key, uint32_t value);
2254 extern JS_PUBLIC_API(uint32_t)
2255 JS_GetGCParameterForThread(JSContext* cx, JSGCParamKey key);
2257 extern JS_PUBLIC_API(void)
2258 JS_SetGCParametersBasedOnAvailableMemory(JSRuntime* rt, uint32_t availMem);
2261 * Create a new JSString whose chars member refers to external memory, i.e.,
2262 * memory requiring application-specific finalization.
2264 extern JS_PUBLIC_API(JSString*)
2265 JS_NewExternalString(JSContext* cx, const char16_t* chars, size_t length,
2266 const JSStringFinalizer* fin);
2269 * Return whether 'str' was created with JS_NewExternalString or
2270 * JS_NewExternalStringWithClosure.
2272 extern JS_PUBLIC_API(bool)
2273 JS_IsExternalString(JSString* str);
2276 * Return the 'fin' arg passed to JS_NewExternalString.
2278 extern JS_PUBLIC_API(const JSStringFinalizer*)
2279 JS_GetExternalStringFinalizer(JSString* str);
2282 * Set the size of the native stack that should not be exceed. To disable
2283 * stack size checking pass 0.
2285 * SpiderMonkey allows for a distinction between system code (such as GCs, which
2286 * may incidentally be triggered by script but are not strictly performed on
2287 * behalf of such script), trusted script (as determined by JS_SetTrustedPrincipals),
2288 * and untrusted script. Each kind of code may have a different stack quota,
2289 * allowing embedders to keep higher-priority machinery running in the face of
2290 * scripted stack exhaustion by something else.
2292 * The stack quotas for each kind of code should be monotonically descending,
2293 * and may be specified with this function. If 0 is passed for a given kind
2294 * of code, it defaults to the value of the next-highest-priority kind.
2296 * This function may only be called immediately after the runtime is initialized
2297 * and before any code is executed and/or interrupts requested.
2299 extern JS_PUBLIC_API(void)
2300 JS_SetNativeStackQuota(JSRuntime* cx, size_t systemCodeStackSize,
2301 size_t trustedScriptStackSize = 0,
2302 size_t untrustedScriptStackSize = 0);
2304 /************************************************************************/
2306 extern JS_PUBLIC_API(int)
2307 JS_IdArrayLength(JSContext* cx, JSIdArray* ida);
2309 extern JS_PUBLIC_API(jsid)
2310 JS_IdArrayGet(JSContext* cx, JSIdArray* ida, unsigned index);
2312 extern JS_PUBLIC_API(void)
2313 JS_DestroyIdArray(JSContext* cx, JSIdArray* ida);
2315 namespace JS {
2317 class AutoIdArray : private AutoGCRooter
2319 public:
2320 AutoIdArray(JSContext* cx, JSIdArray* ida
2321 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
2322 : AutoGCRooter(cx, IDARRAY), context(cx), idArray(ida)
2324 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
2326 ~AutoIdArray() {
2327 if (idArray)
2328 JS_DestroyIdArray(context, idArray);
2330 bool operator!() const {
2331 return !idArray;
2333 jsid operator[](size_t i) const {
2334 MOZ_ASSERT(idArray);
2335 return JS_IdArrayGet(context, idArray, unsigned(i));
2337 size_t length() const {
2338 return JS_IdArrayLength(context, idArray);
2341 friend void AutoGCRooter::trace(JSTracer* trc);
2343 JSIdArray* steal() {
2344 JSIdArray* copy = idArray;
2345 idArray = nullptr;
2346 return copy;
2349 protected:
2350 inline void trace(JSTracer* trc);
2352 private:
2353 JSContext* context;
2354 JSIdArray* idArray;
2355 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
2357 /* No copy or assignment semantics. */
2358 AutoIdArray(AutoIdArray& ida) = delete;
2359 void operator=(AutoIdArray& ida) = delete;
2362 } /* namespace JS */
2364 extern JS_PUBLIC_API(bool)
2365 JS_ValueToId(JSContext* cx, JS::HandleValue v, JS::MutableHandleId idp);
2367 extern JS_PUBLIC_API(bool)
2368 JS_StringToId(JSContext* cx, JS::HandleString s, JS::MutableHandleId idp);
2370 extern JS_PUBLIC_API(bool)
2371 JS_IdToValue(JSContext* cx, jsid id, JS::MutableHandle<JS::Value> vp);
2374 * Invoke the [[DefaultValue]] hook (see ES5 8.6.2) with the provided hint on
2375 * the specified object, computing a primitive default value for the object.
2376 * The hint must be JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_VOID (no hint). On
2377 * success the resulting value is stored in *vp.
2379 extern JS_PUBLIC_API(bool)
2380 JS_DefaultValue(JSContext* cx, JS::Handle<JSObject*> obj, JSType hint,
2381 JS::MutableHandle<JS::Value> vp);
2383 extern JS_PUBLIC_API(bool)
2384 JS_PropertyStub(JSContext* cx, JS::HandleObject obj, JS::HandleId id,
2385 JS::MutableHandleValue vp);
2387 extern JS_PUBLIC_API(bool)
2388 JS_StrictPropertyStub(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool strict,
2389 JS::MutableHandleValue vp);
2391 #if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 4
2393 * This is here because GCC 4.4 for Android ICS can't compile the JS engine
2394 * without it. The function is unused, but if you delete it, we'll trigger a
2395 * compiler bug. When we no longer support ICS, this can be deleted.
2396 * See bug 1103152.
2398 extern JS_PUBLIC_API(bool)
2399 JS_ResolveStub(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* resolvedp);
2400 #endif /* GCC 4.4 */
2402 template<typename T>
2403 struct JSConstScalarSpec {
2404 const char* name;
2405 T val;
2408 typedef JSConstScalarSpec<double> JSConstDoubleSpec;
2409 typedef JSConstScalarSpec<int32_t> JSConstIntegerSpec;
2411 struct JSJitInfo;
2414 * Wrapper to relace JSNative for JSPropertySpecs and JSFunctionSpecs. This will
2415 * allow us to pass one JSJitInfo per function with the property/function spec,
2416 * without additional field overhead.
2418 typedef struct JSNativeWrapper {
2419 JSNative op;
2420 const JSJitInfo* info;
2421 } JSNativeWrapper;
2424 * Macro static initializers which make it easy to pass no JSJitInfo as part of a
2425 * JSPropertySpec or JSFunctionSpec.
2427 #define JSNATIVE_WRAPPER(native) { {native, nullptr} }
2430 * To define an array element rather than a named property member, cast the
2431 * element's index to (const char*) and initialize name with it, and set the
2432 * JSPROP_INDEX bit in flags.
2434 struct JSPropertySpec {
2435 struct SelfHostedWrapper {
2436 void* unused;
2437 const char* funname;
2440 const char* name;
2441 uint8_t flags;
2442 union {
2443 JSNativeWrapper native;
2444 SelfHostedWrapper selfHosted;
2445 } getter;
2446 union {
2447 JSNativeWrapper native;
2448 SelfHostedWrapper selfHosted;
2449 } setter;
2451 bool isSelfHosted() const {
2452 #ifdef DEBUG
2453 // Verify that our accessors match our JSPROP_GETTER flag.
2454 if (flags & JSPROP_GETTER)
2455 checkAccessorsAreSelfHosted();
2456 else
2457 checkAccessorsAreNative();
2458 #endif
2459 return (flags & JSPROP_GETTER);
2462 static_assert(sizeof(SelfHostedWrapper) == sizeof(JSNativeWrapper),
2463 "JSPropertySpec::getter/setter must be compact");
2464 static_assert(offsetof(SelfHostedWrapper, funname) == offsetof(JSNativeWrapper, info),
2465 "JS_SELF_HOSTED* macros below require that "
2466 "SelfHostedWrapper::funname overlay "
2467 "JSNativeWrapper::info");
2468 private:
2469 void checkAccessorsAreNative() const {
2470 MOZ_ASSERT(getter.native.op);
2471 // We may not have a setter at all. So all we can assert here, for the
2472 // native case is that if we have a jitinfo for the setter then we have
2473 // a setter op too. This is good enough to make sure we don't have a
2474 // SelfHostedWrapper for the setter.
2475 MOZ_ASSERT_IF(setter.native.info, setter.native.op);
2478 void checkAccessorsAreSelfHosted() const {
2479 MOZ_ASSERT(!getter.selfHosted.unused);
2480 MOZ_ASSERT(!setter.selfHosted.unused);
2484 namespace JS {
2485 namespace detail {
2487 /* NEVER DEFINED, DON'T USE. For use by JS_CAST_NATIVE_TO only. */
2488 inline int CheckIsNative(JSNative native);
2490 /* NEVER DEFINED, DON'T USE. For use by JS_CAST_STRING_TO only. */
2491 template<size_t N>
2492 inline int
2493 CheckIsCharacterLiteral(const char (&arr)[N]);
2495 /* NEVER DEFINED, DON'T USE. For use by JS_PROPERTYOP_GETTER only. */
2496 inline int CheckIsPropertyOp(JSPropertyOp op);
2498 /* NEVER DEFINED, DON'T USE. For use by JS_PROPERTYOP_SETTER only. */
2499 inline int CheckIsStrictPropertyOp(JSStrictPropertyOp op);
2502 } // namespace detail
2503 } // namespace JS
2505 #define JS_CAST_NATIVE_TO(v, To) \
2506 (static_cast<void>(sizeof(JS::detail::CheckIsNative(v))), \
2507 reinterpret_cast<To>(v))
2509 #define JS_CAST_STRING_TO(s, To) \
2510 (static_cast<void>(sizeof(JS::detail::CheckIsCharacterLiteral(s))), \
2511 reinterpret_cast<To>(s))
2513 #define JS_CHECK_ACCESSOR_FLAGS(flags) \
2514 (static_cast<mozilla::EnableIf<!((flags) & (JSPROP_READONLY | JSPROP_SHARED | JSPROP_PROPOP_ACCESSORS))>::Type>(0), \
2515 (flags))
2517 #define JS_PROPERTYOP_GETTER(v) \
2518 (static_cast<void>(sizeof(JS::detail::CheckIsPropertyOp(v))), \
2519 reinterpret_cast<JSNative>(v))
2521 #define JS_PROPERTYOP_SETTER(v) \
2522 (static_cast<void>(sizeof(JS::detail::CheckIsStrictPropertyOp(v))), \
2523 reinterpret_cast<JSNative>(v))
2525 #define JS_STUBGETTER JS_PROPERTYOP_GETTER(JS_PropertyStub)
2527 #define JS_STUBSETTER JS_PROPERTYOP_SETTER(JS_StrictPropertyStub)
2530 * JSPropertySpec uses JSNativeWrapper. These macros encapsulate the definition
2531 * of JSNative-backed JSPropertySpecs, by defining the JSNativeWrappers for
2532 * them.
2534 #define JS_PSG(name, getter, flags) \
2535 {name, \
2536 uint8_t(JS_CHECK_ACCESSOR_FLAGS(flags) | JSPROP_SHARED), \
2537 JSNATIVE_WRAPPER(getter), \
2538 JSNATIVE_WRAPPER(nullptr)}
2539 #define JS_PSGS(name, getter, setter, flags) \
2540 {name, \
2541 uint8_t(JS_CHECK_ACCESSOR_FLAGS(flags) | JSPROP_SHARED), \
2542 JSNATIVE_WRAPPER(getter), \
2543 JSNATIVE_WRAPPER(setter)}
2544 #define JS_SELF_HOSTED_GET(name, getterName, flags) \
2545 {name, \
2546 uint8_t(JS_CHECK_ACCESSOR_FLAGS(flags) | JSPROP_SHARED | JSPROP_GETTER), \
2547 { nullptr, JS_CAST_STRING_TO(getterName, const JSJitInfo*) }, \
2548 JSNATIVE_WRAPPER(nullptr) }
2549 #define JS_SELF_HOSTED_GETSET(name, getterName, setterName, flags) \
2550 {name, \
2551 uint8_t(JS_CHECK_ACCESSOR_FLAGS(flags) | JSPROP_SHARED | JSPROP_GETTER | JSPROP_SETTER), \
2552 { nullptr, JS_CAST_STRING_TO(getterName, const JSJitInfo*) }, \
2553 { nullptr, JS_CAST_STRING_TO(setterName, const JSJitInfo*) } }
2554 #define JS_PS_END { nullptr, 0, JSNATIVE_WRAPPER(nullptr), JSNATIVE_WRAPPER(nullptr) }
2557 * To define a native function, set call to a JSNativeWrapper. To define a
2558 * self-hosted function, set selfHostedName to the name of a function
2559 * compiled during JSRuntime::initSelfHosting.
2561 struct JSFunctionSpec {
2562 const char* name;
2563 JSNativeWrapper call;
2564 uint16_t nargs;
2565 uint16_t flags;
2566 const char* selfHostedName;
2570 * Terminating sentinel initializer to put at the end of a JSFunctionSpec array
2571 * that's passed to JS_DefineFunctions or JS_InitClass.
2573 #define JS_FS_END JS_FS(nullptr,nullptr,0,0)
2576 * Initializer macros for a JSFunctionSpec array element. JS_FN (whose name pays
2577 * homage to the old JSNative/JSFastNative split) simply adds the flag
2578 * JSFUN_STUB_GSOPS. JS_FNINFO allows the simple adding of
2579 * JSJitInfos. JS_SELF_HOSTED_FN declares a self-hosted function. Finally
2580 * JS_FNSPEC has slots for all the fields.
2582 * The _SYM variants allow defining a function with a symbol key rather than a
2583 * string key. For example, use JS_SYM_FN(iterator, ...) to define an
2584 * @@iterator method. (In builds without ES6 symbols, it defines a method with
2585 * the string id "@@iterator".)
2587 #define JS_FS(name,call,nargs,flags) \
2588 JS_FNSPEC(name, call, nullptr, nargs, flags, nullptr)
2589 #define JS_FN(name,call,nargs,flags) \
2590 JS_FNSPEC(name, call, nullptr, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr)
2591 #define JS_SYM_FN(name,call,nargs,flags) \
2592 JS_SYM_FNSPEC(symbol, call, nullptr, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr)
2593 #define JS_FNINFO(name,call,info,nargs,flags) \
2594 JS_FNSPEC(name, call, info, nargs, flags, nullptr)
2595 #define JS_SELF_HOSTED_FN(name,selfHostedName,nargs,flags) \
2596 JS_FNSPEC(name, nullptr, nullptr, nargs, flags, selfHostedName)
2597 #define JS_SELF_HOSTED_SYM_FN(symbol, selfHostedName, nargs, flags) \
2598 JS_SYM_FNSPEC(symbol, nullptr, nullptr, nargs, flags, selfHostedName)
2600 #ifdef JS_HAS_SYMBOLS
2601 #define JS_SYM_FNSPEC(symbol, call, info, nargs, flags, selfHostedName) \
2602 JS_FNSPEC(reinterpret_cast<const char*>( \
2603 uint32_t(::JS::SymbolCode::symbol) + 1), \
2604 call, info, nargs, flags, selfHostedName)
2605 #else
2606 #define JS_SYM_FNSPEC(symbol, call, info, nargs, flags, selfHostedName) \
2607 JS_FNSPEC("@@" #symbol, call, info, nargs, flags, selfHostedName)
2608 #endif
2610 #define JS_FNSPEC(name,call,info,nargs,flags,selfHostedName) \
2611 {name, {call, info}, nargs, flags, selfHostedName}
2613 extern JS_PUBLIC_API(JSObject*)
2614 JS_InitClass(JSContext* cx, JS::HandleObject obj, JS::HandleObject parent_proto,
2615 const JSClass* clasp, JSNative constructor, unsigned nargs,
2616 const JSPropertySpec* ps, const JSFunctionSpec* fs,
2617 const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs);
2620 * Set up ctor.prototype = proto and proto.constructor = ctor with the
2621 * right property flags.
2623 extern JS_PUBLIC_API(bool)
2624 JS_LinkConstructorAndPrototype(JSContext* cx, JS::Handle<JSObject*> ctor,
2625 JS::Handle<JSObject*> proto);
2627 extern JS_PUBLIC_API(const JSClass*)
2628 JS_GetClass(JSObject* obj);
2630 extern JS_PUBLIC_API(bool)
2631 JS_InstanceOf(JSContext* cx, JS::Handle<JSObject*> obj, const JSClass* clasp, JS::CallArgs* args);
2633 extern JS_PUBLIC_API(bool)
2634 JS_HasInstance(JSContext* cx, JS::Handle<JSObject*> obj, JS::Handle<JS::Value> v, bool* bp);
2636 extern JS_PUBLIC_API(void*)
2637 JS_GetPrivate(JSObject* obj);
2639 extern JS_PUBLIC_API(void)
2640 JS_SetPrivate(JSObject* obj, void* data);
2642 extern JS_PUBLIC_API(void*)
2643 JS_GetInstancePrivate(JSContext* cx, JS::Handle<JSObject*> obj, const JSClass* clasp,
2644 JS::CallArgs* args);
2646 extern JS_PUBLIC_API(bool)
2647 JS_GetPrototype(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject protop);
2649 extern JS_PUBLIC_API(bool)
2650 JS_SetPrototype(JSContext* cx, JS::HandleObject obj, JS::HandleObject proto);
2652 extern JS_PUBLIC_API(JSObject*)
2653 JS_GetParent(JSObject* obj);
2655 extern JS_PUBLIC_API(bool)
2656 JS_SetParent(JSContext* cx, JS::HandleObject obj, JS::HandleObject parent);
2658 extern JS_PUBLIC_API(JSObject*)
2659 JS_GetConstructor(JSContext* cx, JS::Handle<JSObject*> proto);
2661 namespace JS {
2663 enum ZoneSpecifier {
2664 FreshZone = 0,
2665 SystemZone = 1
2668 class JS_PUBLIC_API(CompartmentOptions)
2670 public:
2671 class Override {
2672 public:
2673 Override() : mode_(Default) {}
2675 bool get(bool defaultValue) const {
2676 if (mode_ == Default)
2677 return defaultValue;
2678 return mode_ == ForceTrue;
2681 void set(bool overrideValue) {
2682 mode_ = overrideValue ? ForceTrue : ForceFalse;
2685 void reset() {
2686 mode_ = Default;
2689 private:
2690 enum Mode {
2691 Default,
2692 ForceTrue,
2693 ForceFalse
2696 Mode mode_;
2699 explicit CompartmentOptions()
2700 : version_(JSVERSION_UNKNOWN)
2701 , invisibleToDebugger_(false)
2702 , mergeable_(false)
2703 , discardSource_(false)
2704 , cloneSingletons_(false)
2705 , traceGlobal_(nullptr)
2706 , singletonsAsTemplates_(true)
2707 , addonId_(nullptr)
2708 , preserveJitCode_(false)
2710 zone_.spec = JS::FreshZone;
2713 JSVersion version() const { return version_; }
2714 CompartmentOptions& setVersion(JSVersion aVersion) {
2715 MOZ_ASSERT(aVersion != JSVERSION_UNKNOWN);
2716 version_ = aVersion;
2717 return *this;
2720 // Certain scopes (i.e. XBL compilation scopes) are implementation details
2721 // of the embedding, and references to them should never leak out to script.
2722 // This flag causes the this compartment to skip firing onNewGlobalObject
2723 // and makes addDebuggee a no-op for this global.
2724 bool invisibleToDebugger() const { return invisibleToDebugger_; }
2725 CompartmentOptions& setInvisibleToDebugger(bool flag) {
2726 invisibleToDebugger_ = flag;
2727 return *this;
2730 // Compartments used for off-thread compilation have their contents merged
2731 // into a target compartment when the compilation is finished. This is only
2732 // allowed if this flag is set. The invisibleToDebugger flag must also be
2733 // set for such compartments.
2734 bool mergeable() const { return mergeable_; }
2735 CompartmentOptions& setMergeable(bool flag) {
2736 mergeable_ = flag;
2737 return *this;
2740 // For certain globals, we know enough about the code that will run in them
2741 // that we can discard script source entirely.
2742 bool discardSource() const { return discardSource_; }
2743 CompartmentOptions& setDiscardSource(bool flag) {
2744 discardSource_ = flag;
2745 return *this;
2748 bool cloneSingletons() const { return cloneSingletons_; }
2749 CompartmentOptions& setCloneSingletons(bool flag) {
2750 cloneSingletons_ = flag;
2751 return *this;
2754 bool extraWarnings(JSRuntime* rt) const;
2755 bool extraWarnings(JSContext* cx) const;
2756 Override& extraWarningsOverride() { return extraWarningsOverride_; }
2758 void* zonePointer() const {
2759 MOZ_ASSERT(uintptr_t(zone_.pointer) > uintptr_t(JS::SystemZone));
2760 return zone_.pointer;
2762 ZoneSpecifier zoneSpecifier() const { return zone_.spec; }
2763 CompartmentOptions& setZone(ZoneSpecifier spec);
2764 CompartmentOptions& setSameZoneAs(JSObject* obj);
2766 void setSingletonsAsValues() {
2767 singletonsAsTemplates_ = false;
2769 bool getSingletonsAsTemplates() const {
2770 return singletonsAsTemplates_;
2773 // A null add-on ID means that the compartment is not associated with an
2774 // add-on.
2775 JSAddonId* addonIdOrNull() const { return addonId_; }
2776 CompartmentOptions& setAddonId(JSAddonId* id) {
2777 addonId_ = id;
2778 return *this;
2781 CompartmentOptions& setTrace(JSTraceOp op) {
2782 traceGlobal_ = op;
2783 return *this;
2785 JSTraceOp getTrace() const {
2786 return traceGlobal_;
2789 bool preserveJitCode() const { return preserveJitCode_; }
2790 CompartmentOptions& setPreserveJitCode(bool flag) {
2791 preserveJitCode_ = flag;
2792 return *this;
2795 private:
2796 JSVersion version_;
2797 bool invisibleToDebugger_;
2798 bool mergeable_;
2799 bool discardSource_;
2800 bool cloneSingletons_;
2801 Override extraWarningsOverride_;
2802 union {
2803 ZoneSpecifier spec;
2804 void* pointer; // js::Zone* is not exposed in the API.
2805 } zone_;
2806 JSTraceOp traceGlobal_;
2808 // To XDR singletons, we need to ensure that all singletons are all used as
2809 // templates, by making JSOP_OBJECT return a clone of the JSScript
2810 // singleton, instead of returning the value which is baked in the JSScript.
2811 bool singletonsAsTemplates_;
2813 JSAddonId* addonId_;
2814 bool preserveJitCode_;
2817 JS_PUBLIC_API(CompartmentOptions&)
2818 CompartmentOptionsRef(JSCompartment* compartment);
2820 JS_PUBLIC_API(CompartmentOptions&)
2821 CompartmentOptionsRef(JSObject* obj);
2823 JS_PUBLIC_API(CompartmentOptions&)
2824 CompartmentOptionsRef(JSContext* cx);
2826 // During global creation, we fire notifications to callbacks registered
2827 // via the Debugger API. These callbacks are arbitrary script, and can touch
2828 // the global in arbitrary ways. When that happens, the global should not be
2829 // in a half-baked state. But this creates a problem for consumers that need
2830 // to set slots on the global to put it in a consistent state.
2832 // This API provides a way for consumers to set slots atomically (immediately
2833 // after the global is created), before any debugger hooks are fired. It's
2834 // unfortunately on the clunky side, but that's the way the cookie crumbles.
2836 // If callers have no additional state on the global to set up, they may pass
2837 // |FireOnNewGlobalHook| to JS_NewGlobalObject, which causes that function to
2838 // fire the hook as its final act before returning. Otherwise, callers should
2839 // pass |DontFireOnNewGlobalHook|, which means that they are responsible for
2840 // invoking JS_FireOnNewGlobalObject upon successfully creating the global. If
2841 // an error occurs and the operation aborts, callers should skip firing the
2842 // hook. But otherwise, callers must take care to fire the hook exactly once
2843 // before compiling any script in the global's scope (we have assertions in
2844 // place to enforce this). This lets us be sure that debugger clients never miss
2845 // breakpoints.
2846 enum OnNewGlobalHookOption {
2847 FireOnNewGlobalHook,
2848 DontFireOnNewGlobalHook
2851 } /* namespace JS */
2853 extern JS_PUBLIC_API(JSObject*)
2854 JS_NewGlobalObject(JSContext* cx, const JSClass* clasp, JSPrincipals* principals,
2855 JS::OnNewGlobalHookOption hookOption,
2856 const JS::CompartmentOptions& options = JS::CompartmentOptions());
2858 * Spidermonkey does not have a good way of keeping track of what compartments should be marked on
2859 * their own. We can mark the roots unconditionally, but marking GC things only relevant in live
2860 * compartments is hard. To mitigate this, we create a static trace hook, installed on each global
2861 * object, from which we can be sure the compartment is relevant, and mark it.
2863 * It is still possible to specify custom trace hooks for global object classes. They can be
2864 * provided via the CompartmentOptions passed to JS_NewGlobalObject.
2866 extern JS_PUBLIC_API(void)
2867 JS_GlobalObjectTraceHook(JSTracer* trc, JSObject* global);
2869 extern JS_PUBLIC_API(void)
2870 JS_FireOnNewGlobalObject(JSContext* cx, JS::HandleObject global);
2872 extern JS_PUBLIC_API(JSObject*)
2873 JS_NewObject(JSContext* cx, const JSClass* clasp, JS::Handle<JSObject*> proto,
2874 JS::Handle<JSObject*> parent);
2876 /* Queries the [[Extensible]] property of the object. */
2877 extern JS_PUBLIC_API(bool)
2878 JS_IsExtensible(JSContext* cx, JS::HandleObject obj, bool* extensible);
2880 extern JS_PUBLIC_API(bool)
2881 JS_IsNative(JSObject* obj);
2883 extern JS_PUBLIC_API(JSRuntime*)
2884 JS_GetObjectRuntime(JSObject* obj);
2887 * Unlike JS_NewObject, JS_NewObjectWithGivenProto does not compute a default
2888 * proto if proto's actual parameter value is null.
2890 extern JS_PUBLIC_API(JSObject*)
2891 JS_NewObjectWithGivenProto(JSContext* cx, const JSClass* clasp, JS::Handle<JSObject*> proto,
2892 JS::Handle<JSObject*> parent);
2895 * Freeze obj, and all objects it refers to, recursively. This will not recurse
2896 * through non-extensible objects, on the assumption that those are already
2897 * deep-frozen.
2899 extern JS_PUBLIC_API(bool)
2900 JS_DeepFreezeObject(JSContext* cx, JS::Handle<JSObject*> obj);
2903 * Freezes an object; see ES5's Object.freeze(obj) method.
2905 extern JS_PUBLIC_API(bool)
2906 JS_FreezeObject(JSContext* cx, JS::Handle<JSObject*> obj);
2909 * Attempt to make |obj| non-extensible. If an error occurs while making the
2910 * attempt, return false (with a pending exception set, depending upon the
2911 * nature of the error). If no error occurs, return true with |*succeeded| set
2912 * to indicate whether the attempt successfully set the [[Extensible]] property
2913 * to false.
2915 extern JS_PUBLIC_API(bool)
2916 JS_PreventExtensions(JSContext* cx, JS::HandleObject obj, bool* succeeded);
2918 extern JS_PUBLIC_API(JSObject*)
2919 JS_New(JSContext* cx, JS::HandleObject ctor, const JS::HandleValueArray& args);
2921 extern JS_PUBLIC_API(JSObject*)
2922 JS_DefineObject(JSContext* cx, JS::HandleObject obj, const char* name,
2923 const JSClass* clasp = nullptr, JS::HandleObject proto = JS::NullPtr(),
2924 unsigned attrs = 0);
2926 extern JS_PUBLIC_API(bool)
2927 JS_DefineConstDoubles(JSContext* cx, JS::HandleObject obj, const JSConstDoubleSpec* cds);
2929 extern JS_PUBLIC_API(bool)
2930 JS_DefineConstIntegers(JSContext* cx, JS::HandleObject obj, const JSConstIntegerSpec* cis);
2932 extern JS_PUBLIC_API(bool)
2933 JS_DefineProperties(JSContext* cx, JS::HandleObject obj, const JSPropertySpec* ps);
2935 extern JS_PUBLIC_API(bool)
2936 JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleValue value,
2937 unsigned attrs,
2938 JSNative getter = nullptr, JSNative setter = nullptr);
2940 extern JS_PUBLIC_API(bool)
2941 JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleObject value,
2942 unsigned attrs,
2943 JSNative getter = nullptr, JSNative setter = nullptr);
2945 extern JS_PUBLIC_API(bool)
2946 JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleString value,
2947 unsigned attrs,
2948 JSNative getter = nullptr, JSNative setter = nullptr);
2950 extern JS_PUBLIC_API(bool)
2951 JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, int32_t value,
2952 unsigned attrs,
2953 JSNative getter = nullptr, JSNative setter = nullptr);
2955 extern JS_PUBLIC_API(bool)
2956 JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, uint32_t value,
2957 unsigned attrs,
2958 JSNative getter = nullptr, JSNative setter = nullptr);
2960 extern JS_PUBLIC_API(bool)
2961 JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, double value,
2962 unsigned attrs,
2963 JSNative getter = nullptr, JSNative setter = nullptr);
2965 extern JS_PUBLIC_API(bool)
2966 JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value,
2967 unsigned attrs,
2968 JSNative getter = nullptr, JSNative setter = nullptr);
2970 extern JS_PUBLIC_API(bool)
2971 JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject value,
2972 unsigned attrs,
2973 JSNative getter = nullptr, JSNative setter = nullptr);
2975 extern JS_PUBLIC_API(bool)
2976 JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleString value,
2977 unsigned attrs,
2978 JSNative getter = nullptr, JSNative setter = nullptr);
2980 extern JS_PUBLIC_API(bool)
2981 JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, int32_t value,
2982 unsigned attrs,
2983 JSNative getter = nullptr, JSNative setter = nullptr);
2985 extern JS_PUBLIC_API(bool)
2986 JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, uint32_t value,
2987 unsigned attrs,
2988 JSNative getter = nullptr, JSNative setter = nullptr);
2990 extern JS_PUBLIC_API(bool)
2991 JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, double value,
2992 unsigned attrs,
2993 JSNative getter = nullptr, JSNative setter = nullptr);
2995 extern JS_PUBLIC_API(bool)
2996 JS_AlreadyHasOwnProperty(JSContext* cx, JS::HandleObject obj, const char* name,
2997 bool* foundp);
2999 extern JS_PUBLIC_API(bool)
3000 JS_AlreadyHasOwnPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id,
3001 bool* foundp);
3003 extern JS_PUBLIC_API(bool)
3004 JS_HasProperty(JSContext* cx, JS::HandleObject obj, const char* name, bool* foundp);
3006 extern JS_PUBLIC_API(bool)
3007 JS_HasPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp);
3009 struct JSPropertyDescriptor {
3010 JSObject* obj;
3011 unsigned attrs;
3012 JSPropertyOp getter;
3013 JSStrictPropertyOp setter;
3014 JS::Value value;
3016 JSPropertyDescriptor()
3017 : obj(nullptr), attrs(0), getter(nullptr), setter(nullptr), value(JSVAL_VOID)
3020 void trace(JSTracer* trc);
3022 static js::ThingRootKind rootKind() { return js::THING_ROOT_PROPERTY_DESCRIPTOR; }
3025 namespace JS {
3027 template <typename Outer>
3028 class PropertyDescriptorOperations
3030 const JSPropertyDescriptor * desc() const { return static_cast<const Outer*>(this)->extract(); }
3032 public:
3033 bool isEnumerable() const { return desc()->attrs & JSPROP_ENUMERATE; }
3034 bool isReadonly() const { return desc()->attrs & JSPROP_READONLY; }
3035 bool isPermanent() const { return desc()->attrs & JSPROP_PERMANENT; }
3036 bool hasGetterObject() const { return desc()->attrs & JSPROP_GETTER; }
3037 bool hasSetterObject() const { return desc()->attrs & JSPROP_SETTER; }
3038 bool hasGetterOrSetterObject() const { return desc()->attrs & (JSPROP_GETTER | JSPROP_SETTER); }
3039 bool hasGetterOrSetter() const { return desc()->getter || desc()->setter; }
3040 bool isShared() const { return desc()->attrs & JSPROP_SHARED; }
3041 bool isIndex() const { return desc()->attrs & JSPROP_INDEX; }
3042 bool hasAttributes(unsigned attrs) const { return desc()->attrs & attrs; }
3044 // Descriptors with JSPropertyOps are considered data descriptors. It's
3045 // complicated.
3046 bool isAccessorDescriptor() const { return hasGetterOrSetterObject(); }
3047 bool isDataDescriptor() const { return !isAccessorDescriptor(); }
3049 bool isWritable() const { MOZ_ASSERT(isDataDescriptor()); return !isReadonly(); }
3051 JS::HandleObject object() const {
3052 return JS::HandleObject::fromMarkedLocation(&desc()->obj);
3054 unsigned attributes() const { return desc()->attrs; }
3055 JSPropertyOp getter() const { return desc()->getter; }
3056 JSStrictPropertyOp setter() const { return desc()->setter; }
3057 JS::HandleObject getterObject() const {
3058 MOZ_ASSERT(hasGetterObject());
3059 return JS::HandleObject::fromMarkedLocation(
3060 reinterpret_cast<JSObject* const*>(&desc()->getter));
3062 JS::HandleObject setterObject() const {
3063 MOZ_ASSERT(hasSetterObject());
3064 return JS::HandleObject::fromMarkedLocation(
3065 reinterpret_cast<JSObject* const*>(&desc()->setter));
3067 JS::HandleValue value() const {
3068 return JS::HandleValue::fromMarkedLocation(&desc()->value);
3072 template <typename Outer>
3073 class MutablePropertyDescriptorOperations : public PropertyDescriptorOperations<Outer>
3075 JSPropertyDescriptor * desc() { return static_cast<Outer*>(this)->extractMutable(); }
3077 public:
3079 void clear() {
3080 object().set(nullptr);
3081 setAttributes(0);
3082 setGetter(nullptr);
3083 setSetter(nullptr);
3084 value().setUndefined();
3087 void assign(JSPropertyDescriptor& other) {
3088 object().set(other.obj);
3089 setAttributes(other.attrs);
3090 setGetter(other.getter);
3091 setSetter(other.setter);
3092 value().set(other.value);
3095 JS::MutableHandleObject object() {
3096 return JS::MutableHandleObject::fromMarkedLocation(&desc()->obj);
3098 unsigned& attributesRef() { return desc()->attrs; }
3099 JSPropertyOp& getter() { return desc()->getter; }
3100 JSStrictPropertyOp& setter() { return desc()->setter; }
3101 JS::MutableHandleValue value() {
3102 return JS::MutableHandleValue::fromMarkedLocation(&desc()->value);
3105 void setEnumerable() { desc()->attrs |= JSPROP_ENUMERATE; }
3106 void setAttributes(unsigned attrs) { desc()->attrs = attrs; }
3108 void setGetter(JSPropertyOp op) {
3109 MOZ_ASSERT(op != JS_PropertyStub);
3110 desc()->getter = op;
3112 void setSetter(JSStrictPropertyOp op) {
3113 MOZ_ASSERT(op != JS_StrictPropertyStub);
3114 desc()->setter = op;
3116 void setGetterObject(JSObject* obj) { desc()->getter = reinterpret_cast<JSPropertyOp>(obj); }
3117 void setSetterObject(JSObject* obj) { desc()->setter = reinterpret_cast<JSStrictPropertyOp>(obj); }
3119 JS::MutableHandleObject getterObject() {
3120 MOZ_ASSERT(this->hasGetterObject());
3121 return JS::MutableHandleObject::fromMarkedLocation(
3122 reinterpret_cast<JSObject**>(&desc()->getter));
3124 JS::MutableHandleObject setterObject() {
3125 MOZ_ASSERT(this->hasSetterObject());
3126 return JS::MutableHandleObject::fromMarkedLocation(
3127 reinterpret_cast<JSObject**>(&desc()->setter));
3131 } /* namespace JS */
3133 namespace js {
3135 template <>
3136 struct GCMethods<JSPropertyDescriptor> {
3137 static JSPropertyDescriptor initial() { return JSPropertyDescriptor(); }
3138 static bool poisoned(const JSPropertyDescriptor& desc) {
3139 return (desc.obj && JS::IsPoisonedPtr(desc.obj)) ||
3140 (desc.attrs & JSPROP_GETTER && desc.getter && JS::IsPoisonedPtr(desc.getter)) ||
3141 (desc.attrs & JSPROP_SETTER && desc.setter && JS::IsPoisonedPtr(desc.setter)) ||
3142 (desc.value.isGCThing() && JS::IsPoisonedPtr(desc.value.toGCThing()));
3146 template <>
3147 class RootedBase<JSPropertyDescriptor>
3148 : public JS::MutablePropertyDescriptorOperations<JS::Rooted<JSPropertyDescriptor> >
3150 friend class JS::PropertyDescriptorOperations<JS::Rooted<JSPropertyDescriptor> >;
3151 friend class JS::MutablePropertyDescriptorOperations<JS::Rooted<JSPropertyDescriptor> >;
3152 const JSPropertyDescriptor* extract() const {
3153 return static_cast<const JS::Rooted<JSPropertyDescriptor>*>(this)->address();
3155 JSPropertyDescriptor* extractMutable() {
3156 return static_cast<JS::Rooted<JSPropertyDescriptor>*>(this)->address();
3160 template <>
3161 class HandleBase<JSPropertyDescriptor>
3162 : public JS::PropertyDescriptorOperations<JS::Handle<JSPropertyDescriptor> >
3164 friend class JS::PropertyDescriptorOperations<JS::Handle<JSPropertyDescriptor> >;
3165 const JSPropertyDescriptor* extract() const {
3166 return static_cast<const JS::Handle<JSPropertyDescriptor>*>(this)->address();
3170 template <>
3171 class MutableHandleBase<JSPropertyDescriptor>
3172 : public JS::MutablePropertyDescriptorOperations<JS::MutableHandle<JSPropertyDescriptor> >
3174 friend class JS::PropertyDescriptorOperations<JS::MutableHandle<JSPropertyDescriptor> >;
3175 friend class JS::MutablePropertyDescriptorOperations<JS::MutableHandle<JSPropertyDescriptor> >;
3176 const JSPropertyDescriptor* extract() const {
3177 return static_cast<const JS::MutableHandle<JSPropertyDescriptor>*>(this)->address();
3179 JSPropertyDescriptor* extractMutable() {
3180 return static_cast<JS::MutableHandle<JSPropertyDescriptor>*>(this)->address();
3184 } /* namespace js */
3186 namespace JS {
3188 extern JS_PUBLIC_API(bool)
3189 ParsePropertyDescriptorObject(JSContext* cx,
3190 JS::HandleObject obj,
3191 JS::HandleValue descriptor,
3192 JS::MutableHandle<JSPropertyDescriptor> desc);
3194 } // namespace JS
3196 extern JS_PUBLIC_API(bool)
3197 JS_GetOwnPropertyDescriptorById(JSContext* cx, JS::HandleObject obj, JS::HandleId id,
3198 JS::MutableHandle<JSPropertyDescriptor> desc);
3200 extern JS_PUBLIC_API(bool)
3201 JS_GetOwnPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char* name,
3202 JS::MutableHandle<JSPropertyDescriptor> desc);
3205 * Like JS_GetOwnPropertyDescriptorById but will return a property on
3206 * an object on the prototype chain (returned in desc->obj). If desc->obj is null,
3207 * then this property was not found on the prototype chain.
3209 extern JS_PUBLIC_API(bool)
3210 JS_GetPropertyDescriptorById(JSContext* cx, JS::HandleObject obj, JS::HandleId id,
3211 JS::MutableHandle<JSPropertyDescriptor> desc);
3213 extern JS_PUBLIC_API(bool)
3214 JS_GetPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char* name,
3215 JS::MutableHandle<JSPropertyDescriptor> desc);
3217 extern JS_PUBLIC_API(bool)
3218 JS_GetProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::MutableHandleValue vp);
3220 extern JS_PUBLIC_API(bool)
3221 JS_GetPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp);
3223 extern JS_PUBLIC_API(bool)
3224 JS_ForwardGetPropertyTo(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject onBehalfOf,
3225 JS::MutableHandleValue vp);
3227 extern JS_PUBLIC_API(bool)
3228 JS_SetProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleValue v);
3230 extern JS_PUBLIC_API(bool)
3231 JS_SetPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v);
3233 extern JS_PUBLIC_API(bool)
3234 JS_ForwardSetPropertyTo(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue onBehalfOf,
3235 bool strict, JS::HandleValue vp);
3237 extern JS_PUBLIC_API(bool)
3238 JS_DeleteProperty(JSContext* cx, JS::HandleObject obj, const char* name);
3240 extern JS_PUBLIC_API(bool)
3241 JS_DeleteProperty2(JSContext* cx, JS::HandleObject obj, const char* name, bool* succeeded);
3243 extern JS_PUBLIC_API(bool)
3244 JS_DeletePropertyById(JSContext* cx, JS::HandleObject obj, jsid id);
3246 extern JS_PUBLIC_API(bool)
3247 JS_DeletePropertyById2(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* succeeded);
3249 extern JS_PUBLIC_API(bool)
3250 JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
3251 JS::HandleValue value, unsigned attrs,
3252 JSNative getter = nullptr, JSNative setter = nullptr);
3254 extern JS_PUBLIC_API(bool)
3255 JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
3256 JS::HandleObject value, unsigned attrs,
3257 JSNative getter = nullptr, JSNative setter = nullptr);
3259 extern JS_PUBLIC_API(bool)
3260 JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
3261 JS::HandleString value, unsigned attrs,
3262 JSNative getter = nullptr, JSNative setter = nullptr);
3264 extern JS_PUBLIC_API(bool)
3265 JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
3266 int32_t value, unsigned attrs,
3267 JSNative getter = nullptr, JSNative setter = nullptr);
3269 extern JS_PUBLIC_API(bool)
3270 JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
3271 uint32_t value, unsigned attrs,
3272 JSNative getter = nullptr, JSNative setter = nullptr);
3274 extern JS_PUBLIC_API(bool)
3275 JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
3276 double value, unsigned attrs,
3277 JSNative getter = nullptr, JSNative setter = nullptr);
3279 extern JS_PUBLIC_API(bool)
3280 JS_AlreadyHasOwnUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name,
3281 size_t namelen, bool* foundp);
3283 extern JS_PUBLIC_API(bool)
3284 JS_HasUCProperty(JSContext* cx, JS::HandleObject obj,
3285 const char16_t* name, size_t namelen,
3286 bool* vp);
3288 extern JS_PUBLIC_API(bool)
3289 JS_GetUCProperty(JSContext* cx, JS::HandleObject obj,
3290 const char16_t* name, size_t namelen,
3291 JS::MutableHandleValue vp);
3293 extern JS_PUBLIC_API(bool)
3294 JS_SetUCProperty(JSContext* cx, JS::HandleObject obj,
3295 const char16_t* name, size_t namelen,
3296 JS::HandleValue v);
3298 extern JS_PUBLIC_API(bool)
3299 JS_DeleteUCProperty2(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
3300 bool* succeeded);
3302 extern JS_PUBLIC_API(JSObject*)
3303 JS_NewArrayObject(JSContext* cx, const JS::HandleValueArray& contents);
3305 extern JS_PUBLIC_API(JSObject*)
3306 JS_NewArrayObject(JSContext* cx, size_t length);
3308 extern JS_PUBLIC_API(bool)
3309 JS_IsArrayObject(JSContext* cx, JS::HandleValue value);
3311 extern JS_PUBLIC_API(bool)
3312 JS_IsArrayObject(JSContext* cx, JS::HandleObject obj);
3314 extern JS_PUBLIC_API(bool)
3315 JS_GetArrayLength(JSContext* cx, JS::Handle<JSObject*> obj, uint32_t* lengthp);
3317 extern JS_PUBLIC_API(bool)
3318 JS_SetArrayLength(JSContext* cx, JS::Handle<JSObject*> obj, uint32_t length);
3320 extern JS_PUBLIC_API(bool)
3321 JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleValue value,
3322 unsigned attrs,
3323 JSNative getter = nullptr, JSNative setter = nullptr);
3325 extern JS_PUBLIC_API(bool)
3326 JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleObject value,
3327 unsigned attrs,
3328 JSNative getter = nullptr, JSNative setter = nullptr);
3330 extern JS_PUBLIC_API(bool)
3331 JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleString value,
3332 unsigned attrs,
3333 JSNative getter = nullptr, JSNative setter = nullptr);
3335 extern JS_PUBLIC_API(bool)
3336 JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, int32_t value,
3337 unsigned attrs,
3338 JSNative getter = nullptr, JSNative setter = nullptr);
3340 extern JS_PUBLIC_API(bool)
3341 JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, uint32_t value,
3342 unsigned attrs,
3343 JSNative getter = nullptr, JSNative setter = nullptr);
3345 extern JS_PUBLIC_API(bool)
3346 JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, double value,
3347 unsigned attrs,
3348 JSNative getter = nullptr, JSNative setter = nullptr);
3350 extern JS_PUBLIC_API(bool)
3351 JS_AlreadyHasOwnElement(JSContext* cx, JS::HandleObject obj, uint32_t index, bool* foundp);
3353 extern JS_PUBLIC_API(bool)
3354 JS_HasElement(JSContext* cx, JS::HandleObject obj, uint32_t index, bool* foundp);
3356 extern JS_PUBLIC_API(bool)
3357 JS_GetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::MutableHandleValue vp);
3359 extern JS_PUBLIC_API(bool)
3360 JS_ForwardGetElementTo(JSContext* cx, JS::HandleObject obj, uint32_t index,
3361 JS::HandleObject onBehalfOf, JS::MutableHandleValue vp);
3363 extern JS_PUBLIC_API(bool)
3364 JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleValue v);
3366 extern JS_PUBLIC_API(bool)
3367 JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleObject v);
3369 extern JS_PUBLIC_API(bool)
3370 JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleString v);
3372 extern JS_PUBLIC_API(bool)
3373 JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, int32_t v);
3375 extern JS_PUBLIC_API(bool)
3376 JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, uint32_t v);
3378 extern JS_PUBLIC_API(bool)
3379 JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, double v);
3381 extern JS_PUBLIC_API(bool)
3382 JS_DeleteElement(JSContext* cx, JS::HandleObject obj, uint32_t index);
3384 extern JS_PUBLIC_API(bool)
3385 JS_DeleteElement2(JSContext* cx, JS::HandleObject obj, uint32_t index, bool* succeeded);
3388 * Assign 'undefined' to all of the object's non-reserved slots. Note: this is
3389 * done for all slots, regardless of the associated property descriptor.
3391 JS_PUBLIC_API(void)
3392 JS_SetAllNonReservedSlotsToUndefined(JSContext* cx, JSObject* objArg);
3395 * Create a new array buffer with the given contents. It must be legal to pass
3396 * these contents to free(). On success, the ownership is transferred to the
3397 * new array buffer.
3399 extern JS_PUBLIC_API(JSObject*)
3400 JS_NewArrayBufferWithContents(JSContext* cx, size_t nbytes, void* contents);
3403 * Steal the contents of the given array buffer. The array buffer has its
3404 * length set to 0 and its contents array cleared. The caller takes ownership
3405 * of the return value and must free it or transfer ownership via
3406 * JS_NewArrayBufferWithContents when done using it.
3408 extern JS_PUBLIC_API(void*)
3409 JS_StealArrayBufferContents(JSContext* cx, JS::HandleObject obj);
3412 * Create a new mapped array buffer with the given memory mapped contents. It
3413 * must be legal to free the contents pointer by unmapping it. On success,
3414 * ownership is transferred to the new mapped array buffer.
3416 extern JS_PUBLIC_API(JSObject*)
3417 JS_NewMappedArrayBufferWithContents(JSContext* cx, size_t nbytes, void* contents);
3420 * Create memory mapped array buffer contents.
3421 * Caller must take care of closing fd after calling this function.
3423 extern JS_PUBLIC_API(void*)
3424 JS_CreateMappedArrayBufferContents(int fd, size_t offset, size_t length);
3427 * Release the allocated resource of mapped array buffer contents before the
3428 * object is created.
3429 * If a new object has been created by JS_NewMappedArrayBufferWithContents()
3430 * with this content, then JS_NeuterArrayBuffer() should be used instead to
3431 * release the resource used by the object.
3433 extern JS_PUBLIC_API(void)
3434 JS_ReleaseMappedArrayBufferContents(void* contents, size_t length);
3436 extern JS_PUBLIC_API(JSIdArray*)
3437 JS_Enumerate(JSContext* cx, JS::HandleObject obj);
3439 extern JS_PUBLIC_API(jsval)
3440 JS_GetReservedSlot(JSObject* obj, uint32_t index);
3442 extern JS_PUBLIC_API(void)
3443 JS_SetReservedSlot(JSObject* obj, uint32_t index, jsval v);
3445 /************************************************************************/
3448 * Functions and scripts.
3450 extern JS_PUBLIC_API(JSFunction*)
3451 JS_NewFunction(JSContext* cx, JSNative call, unsigned nargs, unsigned flags,
3452 JS::Handle<JSObject*> parent, const char* name);
3455 * Create the function with the name given by the id. JSID_IS_STRING(id) must
3456 * be true.
3458 extern JS_PUBLIC_API(JSFunction*)
3459 JS_NewFunctionById(JSContext* cx, JSNative call, unsigned nargs, unsigned flags,
3460 JS::Handle<JSObject*> parent, JS::Handle<jsid> id);
3462 namespace JS {
3464 extern JS_PUBLIC_API(JSFunction*)
3465 GetSelfHostedFunction(JSContext* cx, const char* selfHostedName, JS::Handle<jsid> id,
3466 unsigned nargs);
3468 } /* namespace JS */
3470 extern JS_PUBLIC_API(JSObject*)
3471 JS_GetFunctionObject(JSFunction* fun);
3474 * Return the function's identifier as a JSString, or null if fun is unnamed.
3475 * The returned string lives as long as fun, so you don't need to root a saved
3476 * reference to it if fun is well-connected or rooted, and provided you bound
3477 * the use of the saved reference by fun's lifetime.
3479 extern JS_PUBLIC_API(JSString*)
3480 JS_GetFunctionId(JSFunction* fun);
3483 * Return a function's display name. This is the defined name if one was given
3484 * where the function was defined, or it could be an inferred name by the JS
3485 * engine in the case that the function was defined to be anonymous. This can
3486 * still return nullptr if a useful display name could not be inferred. The
3487 * same restrictions on rooting as those in JS_GetFunctionId apply.
3489 extern JS_PUBLIC_API(JSString*)
3490 JS_GetFunctionDisplayId(JSFunction* fun);
3493 * Return the arity (length) of fun.
3495 extern JS_PUBLIC_API(uint16_t)
3496 JS_GetFunctionArity(JSFunction* fun);
3499 * API for determining callability and constructability. This does the right
3500 * thing for proxies.
3502 namespace JS {
3504 extern JS_PUBLIC_API(bool)
3505 IsCallable(JSObject* obj);
3507 extern JS_PUBLIC_API(bool)
3508 IsConstructor(JSObject* obj);
3510 } /* namespace JS */
3513 * Infallible predicate to test whether obj is a function object (faster than
3514 * comparing obj's class name to "Function", but equivalent unless someone has
3515 * overwritten the "Function" identifier with a different constructor and then
3516 * created instances using that constructor that might be passed in as obj).
3518 extern JS_PUBLIC_API(bool)
3519 JS_ObjectIsFunction(JSContext* cx, JSObject* obj);
3521 extern JS_PUBLIC_API(bool)
3522 JS_IsNativeFunction(JSObject* funobj, JSNative call);
3524 /* Return whether the given function is a valid constructor. */
3525 extern JS_PUBLIC_API(bool)
3526 JS_IsConstructor(JSFunction* fun);
3529 * Bind the given callable to use the given object as "this".
3531 * If |callable| is not callable, will throw and return nullptr.
3533 extern JS_PUBLIC_API(JSObject*)
3534 JS_BindCallable(JSContext* cx, JS::Handle<JSObject*> callable, JS::Handle<JSObject*> newThis);
3536 // This enum is used to select if properties with JSPROP_DEFINE_LATE flag
3537 // should be defined on the object.
3538 // Normal JSAPI consumers probably always want DefineAllProperties here.
3539 enum PropertyDefinitionBehavior {
3540 DefineAllProperties,
3541 OnlyDefineLateProperties,
3542 DontDefineLateProperties
3545 extern JS_PUBLIC_API(bool)
3546 JS_DefineFunctions(JSContext* cx, JS::Handle<JSObject*> obj, const JSFunctionSpec* fs,
3547 PropertyDefinitionBehavior behavior = DefineAllProperties);
3549 extern JS_PUBLIC_API(JSFunction*)
3550 JS_DefineFunction(JSContext* cx, JS::Handle<JSObject*> obj, const char* name, JSNative call,
3551 unsigned nargs, unsigned attrs);
3553 extern JS_PUBLIC_API(JSFunction*)
3554 JS_DefineUCFunction(JSContext* cx, JS::Handle<JSObject*> obj,
3555 const char16_t* name, size_t namelen, JSNative call,
3556 unsigned nargs, unsigned attrs);
3558 extern JS_PUBLIC_API(JSFunction*)
3559 JS_DefineFunctionById(JSContext* cx, JS::Handle<JSObject*> obj, JS::Handle<jsid> id, JSNative call,
3560 unsigned nargs, unsigned attrs);
3562 namespace JS {
3565 * Clone a top-level function into cx's global. This function will dynamically
3566 * fail if funobj was lexically nested inside some other function.
3568 extern JS_PUBLIC_API(JSObject*)
3569 CloneFunctionObject(JSContext* cx, HandleObject funobj);
3572 * As above, but providing an explicit scope chain. scopeChain must not include
3573 * the global object on it; that's implicit. It needs to contain the other
3574 * objects that should end up on the clone's scope chain.
3576 extern JS_PUBLIC_API(JSObject*)
3577 CloneFunctionObject(JSContext* cx, HandleObject funobj, AutoObjectVector& scopeChain);
3579 } // namespace JS
3582 * Given a buffer, return false if the buffer might become a valid
3583 * javascript statement with the addition of more lines. Otherwise return
3584 * true. The intent is to support interactive compilation - accumulate
3585 * lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to
3586 * the compiler.
3588 extern JS_PUBLIC_API(bool)
3589 JS_BufferIsCompilableUnit(JSContext* cx, JS::Handle<JSObject*> obj, const char* utf8,
3590 size_t length);
3593 * |script| will always be set. On failure, it will be set to nullptr.
3595 extern JS_PUBLIC_API(bool)
3596 JS_CompileScript(JSContext* cx, JS::HandleObject obj,
3597 const char* ascii, size_t length,
3598 const JS::CompileOptions& options,
3599 JS::MutableHandleScript script);
3602 * |script| will always be set. On failure, it will be set to nullptr.
3604 extern JS_PUBLIC_API(bool)
3605 JS_CompileUCScript(JSContext* cx, JS::HandleObject obj,
3606 const char16_t* chars, size_t length,
3607 const JS::CompileOptions& options,
3608 JS::MutableHandleScript script);
3610 extern JS_PUBLIC_API(JSObject*)
3611 JS_GetGlobalFromScript(JSScript* script);
3613 extern JS_PUBLIC_API(const char*)
3614 JS_GetScriptFilename(JSScript* script);
3616 extern JS_PUBLIC_API(unsigned)
3617 JS_GetScriptBaseLineNumber(JSContext* cx, JSScript* script);
3619 extern JS_PUBLIC_API(JSScript*)
3620 JS_GetFunctionScript(JSContext* cx, JS::HandleFunction fun);
3622 namespace JS {
3624 /* Options for JavaScript compilation. */
3627 * In the most common use case, a CompileOptions instance is allocated on the
3628 * stack, and holds non-owning references to non-POD option values: strings;
3629 * principals; objects; and so on. The code declaring the instance guarantees
3630 * that such option values will outlive the CompileOptions itself: objects are
3631 * otherwise rooted; principals have had their reference counts bumped; strings
3632 * will not be freed until the CompileOptions goes out of scope. In this
3633 * situation, CompileOptions only refers to things others own, so it can be
3634 * lightweight.
3636 * In some cases, however, we need to hold compilation options with a
3637 * non-stack-like lifetime. For example, JS::CompileOffThread needs to save
3638 * compilation options where a worker thread can find them, and then return
3639 * immediately. The worker thread will come along at some later point, and use
3640 * the options.
3642 * The compiler itself just needs to be able to access a collection of options;
3643 * it doesn't care who owns them, or what's keeping them alive. It does its own
3644 * addrefs/copies/tracing/etc.
3646 * So, we have a class hierarchy that reflects these three use cases:
3648 * - ReadOnlyCompileOptions is the common base class. It can be used by code
3649 * that simply needs to access options set elsewhere, like the compiler.
3651 * - The usual CompileOptions class must be stack-allocated, and holds
3652 * non-owning references to the filename, element, and so on. It's derived
3653 * from ReadOnlyCompileOptions, so the compiler can use it.
3655 * - OwningCompileOptions roots / copies / reference counts of all its values,
3656 * and unroots / frees / releases them when it is destructed. It too is
3657 * derived from ReadOnlyCompileOptions, so the compiler accepts it.
3661 * The common base class for the CompileOptions hierarchy.
3663 * Use this in code that only needs to access compilation options created
3664 * elsewhere, like the compiler. Don't instantiate this class (the constructor
3665 * is protected anyway); instead, create instances only of the derived classes:
3666 * CompileOptions and OwningCompileOptions.
3668 class JS_FRIEND_API(ReadOnlyCompileOptions)
3670 friend class CompileOptions;
3672 protected:
3673 // The Web Platform allows scripts to be loaded from arbitrary cross-origin
3674 // sources. This allows an attack by which a malicious website loads a
3675 // sensitive file (say, a bank statement) cross-origin (using the user's
3676 // cookies), and sniffs the generated syntax errors (via a window.onerror
3677 // handler) for juicy morsels of its contents.
3679 // To counter this attack, HTML5 specifies that script errors should be
3680 // sanitized ("muted") when the script is not same-origin with the global
3681 // for which it is loaded. Callers should set this flag for cross-origin
3682 // scripts, and it will be propagated appropriately to child scripts and
3683 // passed back in JSErrorReports.
3684 bool mutedErrors_;
3685 const char* filename_;
3686 const char* introducerFilename_;
3687 const char16_t* sourceMapURL_;
3689 // This constructor leaves 'version' set to JSVERSION_UNKNOWN. The structure
3690 // is unusable until that's set to something more specific; the derived
3691 // classes' constructors take care of that, in ways appropriate to their
3692 // purpose.
3693 ReadOnlyCompileOptions()
3694 : mutedErrors_(false),
3695 filename_(nullptr),
3696 introducerFilename_(nullptr),
3697 sourceMapURL_(nullptr),
3698 version(JSVERSION_UNKNOWN),
3699 versionSet(false),
3700 utf8(false),
3701 lineno(1),
3702 column(0),
3703 compileAndGo(false),
3704 forEval(false),
3705 noScriptRval(false),
3706 selfHostingMode(false),
3707 canLazilyParse(true),
3708 strictOption(false),
3709 extraWarningsOption(false),
3710 werrorOption(false),
3711 asmJSOption(false),
3712 forceAsync(false),
3713 installedFile(false),
3714 sourceIsLazy(false),
3715 introductionType(nullptr),
3716 introductionLineno(0),
3717 introductionOffset(0),
3718 hasIntroductionInfo(false)
3721 // Set all POD options (those not requiring reference counts, copies,
3722 // rooting, or other hand-holding) to their values in |rhs|.
3723 void copyPODOptions(const ReadOnlyCompileOptions& rhs);
3725 public:
3726 // Read-only accessors for non-POD options. The proper way to set these
3727 // depends on the derived type.
3728 bool mutedErrors() const { return mutedErrors_; }
3729 const char* filename() const { return filename_; }
3730 const char* introducerFilename() const { return introducerFilename_; }
3731 const char16_t* sourceMapURL() const { return sourceMapURL_; }
3732 virtual JSObject* element() const = 0;
3733 virtual JSString* elementAttributeName() const = 0;
3734 virtual JSScript* introductionScript() const = 0;
3736 // POD options.
3737 JSVersion version;
3738 bool versionSet;
3739 bool utf8;
3740 unsigned lineno;
3741 unsigned column;
3742 bool compileAndGo;
3743 bool forEval;
3744 bool noScriptRval;
3745 bool selfHostingMode;
3746 bool canLazilyParse;
3747 bool strictOption;
3748 bool extraWarningsOption;
3749 bool werrorOption;
3750 bool asmJSOption;
3751 bool forceAsync;
3752 bool installedFile; // 'true' iff pre-compiling js file in packaged app
3753 bool sourceIsLazy;
3755 // |introductionType| is a statically allocated C string:
3756 // one of "eval", "Function", or "GeneratorFunction".
3757 const char* introductionType;
3758 unsigned introductionLineno;
3759 uint32_t introductionOffset;
3760 bool hasIntroductionInfo;
3762 private:
3763 static JSObject * const nullObjectPtr;
3764 void operator=(const ReadOnlyCompileOptions&) = delete;
3768 * Compilation options, with dynamic lifetime. An instance of this type
3769 * makes a copy of / holds / roots all dynamically allocated resources
3770 * (principals; elements; strings) that it refers to. Its destructor frees
3771 * / drops / unroots them. This is heavier than CompileOptions, below, but
3772 * unlike CompileOptions, it can outlive any given stack frame.
3774 * Note that this *roots* any JS values it refers to - they're live
3775 * unconditionally. Thus, instances of this type can't be owned, directly
3776 * or indirectly, by a JavaScript object: if any value that this roots ever
3777 * comes to refer to the object that owns this, then the whole cycle, and
3778 * anything else it entrains, will never be freed.
3780 class JS_FRIEND_API(OwningCompileOptions) : public ReadOnlyCompileOptions
3782 JSRuntime* runtime;
3783 PersistentRootedObject elementRoot;
3784 PersistentRootedString elementAttributeNameRoot;
3785 PersistentRootedScript introductionScriptRoot;
3787 public:
3788 // A minimal constructor, for use with OwningCompileOptions::copy. This
3789 // leaves |this.version| set to JSVERSION_UNKNOWN; the instance
3790 // shouldn't be used until we've set that to something real (as |copy|
3791 // will).
3792 explicit OwningCompileOptions(JSContext* cx);
3793 ~OwningCompileOptions();
3795 JSObject* element() const MOZ_OVERRIDE { return elementRoot; }
3796 JSString* elementAttributeName() const MOZ_OVERRIDE { return elementAttributeNameRoot; }
3797 JSScript* introductionScript() const MOZ_OVERRIDE { return introductionScriptRoot; }
3799 // Set this to a copy of |rhs|. Return false on OOM.
3800 bool copy(JSContext* cx, const ReadOnlyCompileOptions& rhs);
3802 /* These setters make copies of their string arguments, and are fallible. */
3803 bool setFile(JSContext* cx, const char* f);
3804 bool setFileAndLine(JSContext* cx, const char* f, unsigned l);
3805 bool setSourceMapURL(JSContext* cx, const char16_t* s);
3806 bool setIntroducerFilename(JSContext* cx, const char* s);
3808 /* These setters are infallible, and can be chained. */
3809 OwningCompileOptions& setLine(unsigned l) { lineno = l; return *this; }
3810 OwningCompileOptions& setElement(JSObject* e) {
3811 elementRoot = e;
3812 return *this;
3814 OwningCompileOptions& setElementAttributeName(JSString* p) {
3815 elementAttributeNameRoot = p;
3816 return *this;
3818 OwningCompileOptions& setIntroductionScript(JSScript* s) {
3819 introductionScriptRoot = s;
3820 return *this;
3822 OwningCompileOptions& setMutedErrors(bool mute) {
3823 mutedErrors_ = mute;
3824 return *this;
3826 OwningCompileOptions& setVersion(JSVersion v) {
3827 version = v;
3828 versionSet = true;
3829 return *this;
3831 OwningCompileOptions& setUTF8(bool u) { utf8 = u; return *this; }
3832 OwningCompileOptions& setColumn(unsigned c) { column = c; return *this; }
3833 OwningCompileOptions& setCompileAndGo(bool cng) { compileAndGo = cng; return *this; }
3834 OwningCompileOptions& setForEval(bool eval) { forEval = eval; return *this; }
3835 OwningCompileOptions& setNoScriptRval(bool nsr) { noScriptRval = nsr; return *this; }
3836 OwningCompileOptions& setSelfHostingMode(bool shm) { selfHostingMode = shm; return *this; }
3837 OwningCompileOptions& setCanLazilyParse(bool clp) { canLazilyParse = clp; return *this; }
3838 OwningCompileOptions& setSourceIsLazy(bool l) { sourceIsLazy = l; return *this; }
3839 OwningCompileOptions& setIntroductionType(const char* t) { introductionType = t; return *this; }
3840 bool setIntroductionInfo(JSContext* cx, const char* introducerFn, const char* intro,
3841 unsigned line, JSScript* script, uint32_t offset)
3843 if (!setIntroducerFilename(cx, introducerFn))
3844 return false;
3845 introductionType = intro;
3846 introductionLineno = line;
3847 introductionScriptRoot = script;
3848 introductionOffset = offset;
3849 hasIntroductionInfo = true;
3850 return true;
3853 private:
3854 void operator=(const CompileOptions& rhs) = delete;
3858 * Compilation options stored on the stack. An instance of this type
3859 * simply holds references to dynamically allocated resources (element;
3860 * filename; source map URL) that are owned by something else. If you
3861 * create an instance of this type, it's up to you to guarantee that
3862 * everything you store in it will outlive it.
3864 class MOZ_STACK_CLASS JS_FRIEND_API(CompileOptions) : public ReadOnlyCompileOptions
3866 RootedObject elementRoot;
3867 RootedString elementAttributeNameRoot;
3868 RootedScript introductionScriptRoot;
3870 public:
3871 explicit CompileOptions(JSContext* cx, JSVersion version = JSVERSION_UNKNOWN);
3872 CompileOptions(js::ContextFriendFields* cx, const ReadOnlyCompileOptions& rhs)
3873 : ReadOnlyCompileOptions(), elementRoot(cx), elementAttributeNameRoot(cx),
3874 introductionScriptRoot(cx)
3876 copyPODOptions(rhs);
3878 mutedErrors_ = rhs.mutedErrors_;
3879 filename_ = rhs.filename();
3880 sourceMapURL_ = rhs.sourceMapURL();
3881 elementRoot = rhs.element();
3882 elementAttributeNameRoot = rhs.elementAttributeName();
3883 introductionScriptRoot = rhs.introductionScript();
3886 JSObject* element() const MOZ_OVERRIDE { return elementRoot; }
3887 JSString* elementAttributeName() const MOZ_OVERRIDE { return elementAttributeNameRoot; }
3888 JSScript* introductionScript() const MOZ_OVERRIDE { return introductionScriptRoot; }
3890 CompileOptions& setFile(const char* f) { filename_ = f; return *this; }
3891 CompileOptions& setLine(unsigned l) { lineno = l; return *this; }
3892 CompileOptions& setFileAndLine(const char* f, unsigned l) {
3893 filename_ = f; lineno = l; return *this;
3895 CompileOptions& setSourceMapURL(const char16_t* s) { sourceMapURL_ = s; return *this; }
3896 CompileOptions& setElement(JSObject* e) { elementRoot = e; return *this; }
3897 CompileOptions& setElementAttributeName(JSString* p) {
3898 elementAttributeNameRoot = p;
3899 return *this;
3901 CompileOptions& setIntroductionScript(JSScript* s) {
3902 introductionScriptRoot = s;
3903 return *this;
3905 CompileOptions& setMutedErrors(bool mute) {
3906 mutedErrors_ = mute;
3907 return *this;
3909 CompileOptions& setVersion(JSVersion v) {
3910 version = v;
3911 versionSet = true;
3912 return *this;
3914 CompileOptions& setUTF8(bool u) { utf8 = u; return *this; }
3915 CompileOptions& setColumn(unsigned c) { column = c; return *this; }
3916 CompileOptions& setCompileAndGo(bool cng) { compileAndGo = cng; return *this; }
3917 CompileOptions& setForEval(bool eval) { forEval = eval; return *this; }
3918 CompileOptions& setNoScriptRval(bool nsr) { noScriptRval = nsr; return *this; }
3919 CompileOptions& setSelfHostingMode(bool shm) { selfHostingMode = shm; return *this; }
3920 CompileOptions& setCanLazilyParse(bool clp) { canLazilyParse = clp; return *this; }
3921 CompileOptions& setSourceIsLazy(bool l) { sourceIsLazy = l; return *this; }
3922 CompileOptions& setIntroductionType(const char* t) { introductionType = t; return *this; }
3923 CompileOptions& setIntroductionInfo(const char* introducerFn, const char* intro,
3924 unsigned line, JSScript* script, uint32_t offset)
3926 introducerFilename_ = introducerFn;
3927 introductionType = intro;
3928 introductionLineno = line;
3929 introductionScriptRoot = script;
3930 introductionOffset = offset;
3931 hasIntroductionInfo = true;
3932 return *this;
3934 CompileOptions& maybeMakeStrictMode(bool strict) {
3935 strictOption = strictOption || strict;
3936 return *this;
3939 private:
3940 void operator=(const CompileOptions& rhs) = delete;
3944 * |script| will always be set. On failure, it will be set to nullptr.
3946 extern JS_PUBLIC_API(bool)
3947 Compile(JSContext* cx, JS::HandleObject obj, const ReadOnlyCompileOptions& options,
3948 SourceBufferHolder& srcBuf, JS::MutableHandleScript script);
3950 extern JS_PUBLIC_API(bool)
3951 Compile(JSContext* cx, JS::HandleObject obj, const ReadOnlyCompileOptions& options,
3952 const char* bytes, size_t length, JS::MutableHandleScript script);
3954 extern JS_PUBLIC_API(bool)
3955 Compile(JSContext* cx, JS::HandleObject obj, const ReadOnlyCompileOptions& options,
3956 const char16_t* chars, size_t length, JS::MutableHandleScript script);
3958 extern JS_PUBLIC_API(bool)
3959 Compile(JSContext* cx, JS::HandleObject obj, const ReadOnlyCompileOptions& options, FILE* file,
3960 JS::MutableHandleScript script);
3962 extern JS_PUBLIC_API(bool)
3963 Compile(JSContext* cx, JS::HandleObject obj, const ReadOnlyCompileOptions& options, const char* filename,
3964 JS::MutableHandleScript script);
3966 extern JS_PUBLIC_API(bool)
3967 CanCompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options, size_t length);
3970 * Off thread compilation control flow.
3972 * After successfully triggering an off thread compile of a script, the
3973 * callback will eventually be invoked with the specified data and a token
3974 * for the compilation. The callback will be invoked while off the main thread,
3975 * so must ensure that its operations are thread safe. Afterwards,
3976 * FinishOffThreadScript must be invoked on the main thread to get the result
3977 * script or nullptr. If maybecx is not specified, the resources will be freed,
3978 * but no script will be returned.
3980 * The characters passed in to CompileOffThread must remain live until the
3981 * callback is invoked, and the resulting script will be rooted until the call
3982 * to FinishOffThreadScript.
3985 extern JS_PUBLIC_API(bool)
3986 CompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options,
3987 const char16_t* chars, size_t length,
3988 OffThreadCompileCallback callback, void* callbackData);
3990 extern JS_PUBLIC_API(JSScript*)
3991 FinishOffThreadScript(JSContext* maybecx, JSRuntime* rt, void* token);
3994 * Compile a function with scopeChain plus the global as its scope chain.
3995 * scopeChain must contain objects in the current compartment of cx. The actual
3996 * scope chain used for the function will consist of With wrappers for those
3997 * objects, followed by the current global of the compartment cx is in. This
3998 * global must not be explicitly included in the scope chain.
4000 extern JS_PUBLIC_API(bool)
4001 CompileFunction(JSContext* cx, AutoObjectVector& scopeChain,
4002 const ReadOnlyCompileOptions& options,
4003 const char* name, unsigned nargs, const char* const* argnames,
4004 const char16_t* chars, size_t length, JS::MutableHandleFunction fun);
4007 * Same as above, but taking a SourceBufferHolder for the function body.
4009 extern JS_PUBLIC_API(bool)
4010 CompileFunction(JSContext* cx, AutoObjectVector& scopeChain,
4011 const ReadOnlyCompileOptions& options,
4012 const char* name, unsigned nargs, const char* const* argnames,
4013 SourceBufferHolder& srcBuf, JS::MutableHandleFunction fun);
4016 * Same as above, but taking a const char * for the function body.
4018 extern JS_PUBLIC_API(bool)
4019 CompileFunction(JSContext* cx, AutoObjectVector& scopeChain,
4020 const ReadOnlyCompileOptions& options,
4021 const char* name, unsigned nargs, const char* const* argnames,
4022 const char* bytes, size_t length, JS::MutableHandleFunction fun);
4024 } /* namespace JS */
4026 extern JS_PUBLIC_API(JSString*)
4027 JS_DecompileScript(JSContext* cx, JS::Handle<JSScript*> script, const char* name, unsigned indent);
4030 * API extension: OR this into indent to avoid pretty-printing the decompiled
4031 * source resulting from JS_DecompileFunction{,Body}.
4033 #define JS_DONT_PRETTY_PRINT ((unsigned)0x8000)
4035 extern JS_PUBLIC_API(JSString*)
4036 JS_DecompileFunction(JSContext* cx, JS::Handle<JSFunction*> fun, unsigned indent);
4038 extern JS_PUBLIC_API(JSString*)
4039 JS_DecompileFunctionBody(JSContext* cx, JS::Handle<JSFunction*> fun, unsigned indent);
4042 * NB: JS_ExecuteScript and the JS::Evaluate APIs use the obj
4043 * parameter as the initial scope chain header, the 'this' keyword value, and
4044 * the variables object (ECMA parlance for where 'var' and 'function' bind
4045 * names) of the execution context for script.
4047 * Using obj as the variables object is problematic if obj's parent (which is
4048 * the scope chain link; see JS_SetParent and JS_NewObject) is not null: in
4049 * this case, variables created by 'var x = 0', e.g., go in obj, but variables
4050 * created by assignment to an unbound id, 'x = 0', go in the last object on
4051 * the scope chain linked by parent.
4053 * ECMA calls that last scoping object the "global object", but note that many
4054 * embeddings have several such objects. ECMA requires that "global code" be
4055 * executed with the variables object equal to this global object. But these
4056 * JS API entry points provide freedom to execute code against a "sub-global",
4057 * i.e., a parented or scoped object, in which case the variables object will
4058 * differ from the last object on the scope chain, resulting in confusing and
4059 * non-ECMA explicit vs. implicit variable creation.
4061 * Caveat embedders: unless you already depend on this buggy variables object
4062 * binding behavior, you should call RuntimeOptionsRef(rt).setVarObjFix(true)
4063 * for each context in the application, if you pass parented objects as the obj
4064 * parameter, or may ever pass such objects in the future.
4066 * Why a runtime option? The alternative is to add APIs duplicating those below
4067 * for the other value of varobjfix, and that doesn't seem worth the code bloat
4068 * cost. Such new entry points would probably have less obvious names, too, so
4069 * would not tend to be used. The RuntimeOptionsRef adjustment, OTOH, can be
4070 * more easily hacked into existing code that does not depend on the bug; such
4071 * code can continue to use the familiar JS::Evaluate, etc., entry points.
4073 extern JS_PUBLIC_API(bool)
4074 JS_ExecuteScript(JSContext* cx, JS::HandleObject obj, JS::HandleScript script, JS::MutableHandleValue rval);
4076 extern JS_PUBLIC_API(bool)
4077 JS_ExecuteScript(JSContext* cx, JS::HandleObject obj, JS::HandleScript script);
4080 * As above, but providing an explicit scope chain. scopeChain must not include
4081 * the global object on it; that's implicit. It needs to contain the other
4082 * objects that should end up on the scripts's scope chain.
4084 extern JS_PUBLIC_API(bool)
4085 JS_ExecuteScript(JSContext* cx, JS::AutoObjectVector& scopeChain,
4086 JS::HandleScript script, JS::MutableHandleValue rval);
4088 extern JS_PUBLIC_API(bool)
4089 JS_ExecuteScript(JSContext* cx, JS::AutoObjectVector& scopeChain, JS::HandleScript script);
4091 namespace JS {
4094 * Like the above, but handles a cross-compartment script. If the script is
4095 * cross-compartment, it is cloned into the current compartment before executing.
4097 extern JS_PUBLIC_API(bool)
4098 CloneAndExecuteScript(JSContext* cx, JS::Handle<JSObject*> obj, JS::Handle<JSScript*> script);
4100 } /* namespace JS */
4102 namespace JS {
4104 extern JS_PUBLIC_API(bool)
4105 Evaluate(JSContext* cx, JS::HandleObject obj, const ReadOnlyCompileOptions& options,
4106 SourceBufferHolder& srcBuf, JS::MutableHandleValue rval);
4108 extern JS_PUBLIC_API(bool)
4109 Evaluate(JSContext* cx, AutoObjectVector& scopeChain, const ReadOnlyCompileOptions& options,
4110 SourceBufferHolder& srcBuf, JS::MutableHandleValue rval);
4112 extern JS_PUBLIC_API(bool)
4113 Evaluate(JSContext* cx, JS::HandleObject obj, const ReadOnlyCompileOptions& options,
4114 const char16_t* chars, size_t length, JS::MutableHandleValue rval);
4116 extern JS_PUBLIC_API(bool)
4117 Evaluate(JSContext* cx, JS::HandleObject obj, const ReadOnlyCompileOptions& options,
4118 const char* bytes, size_t length, JS::MutableHandleValue rval);
4120 extern JS_PUBLIC_API(bool)
4121 Evaluate(JSContext* cx, JS::HandleObject obj, const ReadOnlyCompileOptions& options,
4122 const char* filename, JS::MutableHandleValue rval);
4124 } /* namespace JS */
4126 extern JS_PUBLIC_API(bool)
4127 JS_CallFunction(JSContext* cx, JS::HandleObject obj, JS::HandleFunction fun,
4128 const JS::HandleValueArray& args, JS::MutableHandleValue rval);
4130 extern JS_PUBLIC_API(bool)
4131 JS_CallFunctionName(JSContext* cx, JS::HandleObject obj, const char* name,
4132 const JS::HandleValueArray& args, JS::MutableHandleValue rval);
4134 extern JS_PUBLIC_API(bool)
4135 JS_CallFunctionValue(JSContext* cx, JS::HandleObject obj, JS::HandleValue fval,
4136 const JS::HandleValueArray& args, JS::MutableHandleValue rval);
4138 namespace JS {
4140 static inline bool
4141 Call(JSContext* cx, JS::HandleObject thisObj, JS::HandleFunction fun,
4142 const JS::HandleValueArray& args, MutableHandleValue rval)
4144 return !!JS_CallFunction(cx, thisObj, fun, args, rval);
4147 static inline bool
4148 Call(JSContext* cx, JS::HandleObject thisObj, const char* name, const JS::HandleValueArray& args,
4149 MutableHandleValue rval)
4151 return !!JS_CallFunctionName(cx, thisObj, name, args, rval);
4154 static inline bool
4155 Call(JSContext* cx, JS::HandleObject thisObj, JS::HandleValue fun, const JS::HandleValueArray& args,
4156 MutableHandleValue rval)
4158 return !!JS_CallFunctionValue(cx, thisObj, fun, args, rval);
4161 extern JS_PUBLIC_API(bool)
4162 Call(JSContext* cx, JS::HandleValue thisv, JS::HandleValue fun, const JS::HandleValueArray& args,
4163 MutableHandleValue rval);
4165 static inline bool
4166 Call(JSContext* cx, JS::HandleValue thisv, JS::HandleObject funObj, const JS::HandleValueArray& args,
4167 MutableHandleValue rval)
4169 MOZ_ASSERT(funObj);
4170 JS::RootedValue fun(cx, JS::ObjectValue(*funObj));
4171 return Call(cx, thisv, fun, args, rval);
4174 extern JS_PUBLIC_API(bool)
4175 Construct(JSContext* cx, JS::HandleValue fun,
4176 const JS::HandleValueArray& args,
4177 MutableHandleValue rval);
4179 } /* namespace JS */
4182 * These functions allow setting an interrupt callback that will be called
4183 * from the JS thread some time after any thread triggered the callback using
4184 * JS_RequestInterruptCallback(rt).
4186 * To schedule the GC and for other activities the engine internally triggers
4187 * interrupt callbacks. The embedding should thus not rely on callbacks being
4188 * triggered through the external API only.
4190 * Important note: Additional callbacks can occur inside the callback handler
4191 * if it re-enters the JS engine. The embedding must ensure that the callback
4192 * is disconnected before attempting such re-entry.
4194 extern JS_PUBLIC_API(JSInterruptCallback)
4195 JS_SetInterruptCallback(JSRuntime* rt, JSInterruptCallback callback);
4197 extern JS_PUBLIC_API(JSInterruptCallback)
4198 JS_GetInterruptCallback(JSRuntime* rt);
4200 extern JS_PUBLIC_API(void)
4201 JS_RequestInterruptCallback(JSRuntime* rt);
4203 extern JS_PUBLIC_API(bool)
4204 JS_IsRunning(JSContext* cx);
4207 * Saving and restoring frame chains.
4209 * These two functions are used to set aside cx's call stack while that stack
4210 * is inactive. After a call to JS_SaveFrameChain, it looks as if there is no
4211 * code running on cx. Before calling JS_RestoreFrameChain, cx's call stack
4212 * must be balanced and all nested calls to JS_SaveFrameChain must have had
4213 * matching JS_RestoreFrameChain calls.
4215 * JS_SaveFrameChain deals with cx not having any code running on it.
4217 extern JS_PUBLIC_API(bool)
4218 JS_SaveFrameChain(JSContext* cx);
4220 extern JS_PUBLIC_API(void)
4221 JS_RestoreFrameChain(JSContext* cx);
4223 /************************************************************************/
4226 * Strings.
4228 * NB: JS_NewUCString takes ownership of bytes on success, avoiding a copy;
4229 * but on error (signified by null return), it leaves chars owned by the
4230 * caller. So the caller must free bytes in the error case, if it has no use
4231 * for them. In contrast, all the JS_New*StringCopy* functions do not take
4232 * ownership of the character memory passed to them -- they copy it.
4234 extern JS_PUBLIC_API(JSString*)
4235 JS_NewStringCopyN(JSContext* cx, const char* s, size_t n);
4237 extern JS_PUBLIC_API(JSString*)
4238 JS_NewStringCopyZ(JSContext* cx, const char* s);
4240 extern JS_PUBLIC_API(JSString*)
4241 JS_InternJSString(JSContext* cx, JS::HandleString str);
4243 extern JS_PUBLIC_API(JSString*)
4244 JS_InternStringN(JSContext* cx, const char* s, size_t length);
4246 extern JS_PUBLIC_API(JSString*)
4247 JS_InternString(JSContext* cx, const char* s);
4249 extern JS_PUBLIC_API(JSString*)
4250 JS_NewUCString(JSContext* cx, char16_t* chars, size_t length);
4252 extern JS_PUBLIC_API(JSString*)
4253 JS_NewUCStringCopyN(JSContext* cx, const char16_t* s, size_t n);
4255 extern JS_PUBLIC_API(JSString*)
4256 JS_NewUCStringCopyZ(JSContext* cx, const char16_t* s);
4258 extern JS_PUBLIC_API(JSString*)
4259 JS_InternUCStringN(JSContext* cx, const char16_t* s, size_t length);
4261 extern JS_PUBLIC_API(JSString*)
4262 JS_InternUCString(JSContext* cx, const char16_t* s);
4264 extern JS_PUBLIC_API(bool)
4265 JS_CompareStrings(JSContext* cx, JSString* str1, JSString* str2, int32_t* result);
4267 extern JS_PUBLIC_API(bool)
4268 JS_StringEqualsAscii(JSContext* cx, JSString* str, const char* asciiBytes, bool* match);
4270 extern JS_PUBLIC_API(size_t)
4271 JS_PutEscapedString(JSContext* cx, char* buffer, size_t size, JSString* str, char quote);
4273 extern JS_PUBLIC_API(bool)
4274 JS_FileEscapedString(FILE* fp, JSString* str, char quote);
4277 * Extracting string characters and length.
4279 * While getting the length of a string is infallible, getting the chars can
4280 * fail. As indicated by the lack of a JSContext parameter, there are two
4281 * special cases where getting the chars is infallible:
4283 * The first case is interned strings, i.e., strings from JS_InternString or
4284 * JSID_TO_STRING(id), using JS_GetLatin1InternedStringChars or
4285 * JS_GetTwoByteInternedStringChars.
4287 * The second case is "flat" strings that have been explicitly prepared in a
4288 * fallible context by JS_FlattenString. To catch errors, a separate opaque
4289 * JSFlatString type is returned by JS_FlattenString and expected by
4290 * JS_GetFlatStringChars. Note, though, that this is purely a syntactic
4291 * distinction: the input and output of JS_FlattenString are the same actual
4292 * GC-thing. If a JSString is known to be flat, JS_ASSERT_STRING_IS_FLAT can be
4293 * used to make a debug-checked cast. Example:
4295 * // in a fallible context
4296 * JSFlatString* fstr = JS_FlattenString(cx, str);
4297 * if (!fstr)
4298 * return false;
4299 * MOZ_ASSERT(fstr == JS_ASSERT_STRING_IS_FLAT(str));
4301 * // in an infallible context, for the same 'str'
4302 * AutoCheckCannotGC nogc;
4303 * const char16_t* chars = JS_GetTwoByteFlatStringChars(nogc, fstr)
4304 * MOZ_ASSERT(chars);
4306 * Flat strings and interned strings are always null-terminated, so
4307 * JS_FlattenString can be used to get a null-terminated string.
4309 * Additionally, string characters are stored as either Latin1Char (8-bit)
4310 * or char16_t (16-bit). Clients can use JS_StringHasLatin1Chars and can then
4311 * call either the Latin1* or TwoByte* functions. Some functions like
4312 * JS_CopyStringChars and JS_GetStringCharAt accept both Latin1 and TwoByte
4313 * strings.
4316 extern JS_PUBLIC_API(size_t)
4317 JS_GetStringLength(JSString* str);
4319 extern JS_PUBLIC_API(bool)
4320 JS_StringIsFlat(JSString* str);
4322 /* Returns true iff the string's characters are stored as Latin1. */
4323 extern JS_PUBLIC_API(bool)
4324 JS_StringHasLatin1Chars(JSString* str);
4326 extern JS_PUBLIC_API(const JS::Latin1Char*)
4327 JS_GetLatin1StringCharsAndLength(JSContext* cx, const JS::AutoCheckCannotGC& nogc, JSString* str,
4328 size_t* length);
4330 extern JS_PUBLIC_API(const char16_t*)
4331 JS_GetTwoByteStringCharsAndLength(JSContext* cx, const JS::AutoCheckCannotGC& nogc, JSString* str,
4332 size_t* length);
4334 extern JS_PUBLIC_API(bool)
4335 JS_GetStringCharAt(JSContext* cx, JSString* str, size_t index, char16_t* res);
4337 extern JS_PUBLIC_API(char16_t)
4338 JS_GetFlatStringCharAt(JSFlatString* str, size_t index);
4340 extern JS_PUBLIC_API(const char16_t*)
4341 JS_GetTwoByteExternalStringChars(JSString* str);
4343 extern JS_PUBLIC_API(bool)
4344 JS_CopyStringChars(JSContext* cx, mozilla::Range<char16_t> dest, JSString* str);
4346 extern JS_PUBLIC_API(const JS::Latin1Char*)
4347 JS_GetLatin1InternedStringChars(const JS::AutoCheckCannotGC& nogc, JSString* str);
4349 extern JS_PUBLIC_API(const char16_t*)
4350 JS_GetTwoByteInternedStringChars(const JS::AutoCheckCannotGC& nogc, JSString* str);
4352 extern JS_PUBLIC_API(JSFlatString*)
4353 JS_FlattenString(JSContext* cx, JSString* str);
4355 extern JS_PUBLIC_API(const JS::Latin1Char*)
4356 JS_GetLatin1FlatStringChars(const JS::AutoCheckCannotGC& nogc, JSFlatString* str);
4358 extern JS_PUBLIC_API(const char16_t*)
4359 JS_GetTwoByteFlatStringChars(const JS::AutoCheckCannotGC& nogc, JSFlatString* str);
4361 static MOZ_ALWAYS_INLINE JSFlatString*
4362 JSID_TO_FLAT_STRING(jsid id)
4364 MOZ_ASSERT(JSID_IS_STRING(id));
4365 return (JSFlatString*)(JSID_BITS(id));
4368 static MOZ_ALWAYS_INLINE JSFlatString*
4369 JS_ASSERT_STRING_IS_FLAT(JSString* str)
4371 MOZ_ASSERT(JS_StringIsFlat(str));
4372 return (JSFlatString*)str;
4375 static MOZ_ALWAYS_INLINE JSString*
4376 JS_FORGET_STRING_FLATNESS(JSFlatString* fstr)
4378 return (JSString*)fstr;
4382 * Additional APIs that avoid fallibility when given a flat string.
4385 extern JS_PUBLIC_API(bool)
4386 JS_FlatStringEqualsAscii(JSFlatString* str, const char* asciiBytes);
4388 extern JS_PUBLIC_API(size_t)
4389 JS_PutEscapedFlatString(char* buffer, size_t size, JSFlatString* str, char quote);
4392 * Create a dependent string, i.e., a string that owns no character storage,
4393 * but that refers to a slice of another string's chars. Dependent strings
4394 * are mutable by definition, so the thread safety comments above apply.
4396 extern JS_PUBLIC_API(JSString*)
4397 JS_NewDependentString(JSContext* cx, JS::HandleString str, size_t start,
4398 size_t length);
4401 * Concatenate two strings, possibly resulting in a rope.
4402 * See above for thread safety comments.
4404 extern JS_PUBLIC_API(JSString*)
4405 JS_ConcatStrings(JSContext* cx, JS::HandleString left, JS::HandleString right);
4408 * For JS_DecodeBytes, set *dstlenp to the size of the destination buffer before
4409 * the call; on return, *dstlenp contains the number of characters actually
4410 * stored. To determine the necessary destination buffer size, make a sizing
4411 * call that passes nullptr for dst.
4413 * On errors, the functions report the error. In that case, *dstlenp contains
4414 * the number of characters or bytes transferred so far. If cx is nullptr, no
4415 * error is reported on failure, and the functions simply return false.
4417 * NB: This function does not store an additional zero byte or char16_t after the
4418 * transcoded string.
4420 JS_PUBLIC_API(bool)
4421 JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen, char16_t* dst,
4422 size_t* dstlenp);
4425 * A variation on JS_EncodeCharacters where a null terminated string is
4426 * returned that you are expected to call JS_free on when done.
4428 JS_PUBLIC_API(char*)
4429 JS_EncodeString(JSContext* cx, JSString* str);
4432 * Same behavior as JS_EncodeString(), but encode into UTF-8 string
4434 JS_PUBLIC_API(char*)
4435 JS_EncodeStringToUTF8(JSContext* cx, JS::HandleString str);
4438 * Get number of bytes in the string encoding (without accounting for a
4439 * terminating zero bytes. The function returns (size_t) -1 if the string
4440 * can not be encoded into bytes and reports an error using cx accordingly.
4442 JS_PUBLIC_API(size_t)
4443 JS_GetStringEncodingLength(JSContext* cx, JSString* str);
4446 * Encode string into a buffer. The function does not stores an additional
4447 * zero byte. The function returns (size_t) -1 if the string can not be
4448 * encoded into bytes with no error reported. Otherwise it returns the number
4449 * of bytes that are necessary to encode the string. If that exceeds the
4450 * length parameter, the string will be cut and only length bytes will be
4451 * written into the buffer.
4453 JS_PUBLIC_API(size_t)
4454 JS_EncodeStringToBuffer(JSContext* cx, JSString* str, char* buffer, size_t length);
4456 class JSAutoByteString
4458 public:
4459 JSAutoByteString(JSContext* cx, JSString* str
4460 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
4461 : mBytes(JS_EncodeString(cx, str))
4463 MOZ_ASSERT(cx);
4464 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
4467 explicit JSAutoByteString(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM)
4468 : mBytes(nullptr)
4470 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
4473 ~JSAutoByteString() {
4474 js_free(mBytes);
4477 /* Take ownership of the given byte array. */
4478 void initBytes(char* bytes) {
4479 MOZ_ASSERT(!mBytes);
4480 mBytes = bytes;
4483 char* encodeLatin1(JSContext* cx, JSString* str) {
4484 MOZ_ASSERT(!mBytes);
4485 MOZ_ASSERT(cx);
4486 mBytes = JS_EncodeString(cx, str);
4487 return mBytes;
4490 char* encodeLatin1(js::ExclusiveContext* cx, JSString* str);
4492 char* encodeUtf8(JSContext* cx, JS::HandleString str) {
4493 MOZ_ASSERT(!mBytes);
4494 MOZ_ASSERT(cx);
4495 mBytes = JS_EncodeStringToUTF8(cx, str);
4496 return mBytes;
4499 void clear() {
4500 js_free(mBytes);
4501 mBytes = nullptr;
4504 char* ptr() const {
4505 return mBytes;
4508 bool operator!() const {
4509 return !mBytes;
4512 size_t length() const {
4513 if (!mBytes)
4514 return 0;
4515 return strlen(mBytes);
4518 private:
4519 char* mBytes;
4520 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
4522 /* Copy and assignment are not supported. */
4523 JSAutoByteString(const JSAutoByteString& another);
4524 JSAutoByteString& operator=(const JSAutoByteString& another);
4527 namespace JS {
4529 extern JS_PUBLIC_API(JSAddonId*)
4530 NewAddonId(JSContext* cx, JS::HandleString str);
4532 extern JS_PUBLIC_API(JSString*)
4533 StringOfAddonId(JSAddonId* id);
4535 extern JS_PUBLIC_API(JSAddonId*)
4536 AddonIdOfObject(JSObject* obj);
4538 } // namespace JS
4540 /************************************************************************/
4542 * Symbols
4545 namespace JS {
4548 * Create a new Symbol with the given description. This function never returns
4549 * a Symbol that is in the Runtime-wide symbol registry.
4551 * If description is null, the new Symbol's [[Description]] attribute is
4552 * undefined.
4554 JS_PUBLIC_API(Symbol*)
4555 NewSymbol(JSContext* cx, HandleString description);
4558 * Symbol.for as specified in ES6.
4560 * Get a Symbol with the description 'key' from the Runtime-wide symbol registry.
4561 * If there is not already a Symbol with that description in the registry, a new
4562 * Symbol is created and registered. 'key' must not be null.
4564 JS_PUBLIC_API(Symbol*)
4565 GetSymbolFor(JSContext* cx, HandleString key);
4568 * Get the [[Description]] attribute of the given symbol.
4570 * This function is infallible. If it returns null, that means the symbol's
4571 * [[Description]] is undefined.
4573 JS_PUBLIC_API(JSString*)
4574 GetSymbolDescription(HandleSymbol symbol);
4576 /* Well-known symbols. */
4577 MOZ_BEGIN_ENUM_CLASS(SymbolCode, uint32_t)
4578 iterator, // well-known Symbol.iterator
4579 InSymbolRegistry = 0xfffffffe, // created by Symbol.for() or JS::GetSymbolFor()
4580 UniqueSymbol = 0xffffffff // created by Symbol() or JS::NewSymbol()
4581 MOZ_END_ENUM_CLASS(SymbolCode)
4583 /* For use in loops that iterate over the well-known symbols. */
4584 const size_t WellKnownSymbolLimit = 1;
4587 * Return the SymbolCode telling what sort of symbol `symbol` is.
4589 * A symbol's SymbolCode never changes once it is created.
4591 JS_PUBLIC_API(SymbolCode)
4592 GetSymbolCode(Handle<Symbol*> symbol);
4595 * Get one of the well-known symbols defined by ES6. A single set of well-known
4596 * symbols is shared by all compartments in a JSRuntime.
4598 * `which` must be in the range [0, WellKnownSymbolLimit).
4600 JS_PUBLIC_API(Symbol*)
4601 GetWellKnownSymbol(JSContext* cx, SymbolCode which);
4604 * Return true if the given JSPropertySpec::name or JSFunctionSpec::name value
4605 * is actually a symbol code and not a string. See JS_SYM_FN.
4607 inline bool
4608 PropertySpecNameIsSymbol(const char* name)
4610 uintptr_t u = reinterpret_cast<uintptr_t>(name);
4611 return u != 0 && u - 1 < WellKnownSymbolLimit;
4614 JS_PUBLIC_API(bool)
4615 PropertySpecNameEqualsId(const char* name, HandleId id);
4618 * Create a jsid that does not need to be marked for GC.
4620 * 'name' is a JSPropertySpec::name or JSFunctionSpec::name value. The
4621 * resulting jsid, on success, is either an interned string or a well-known
4622 * symbol; either way it is immune to GC so there is no need to visit *idp
4623 * during GC marking.
4625 JS_PUBLIC_API(bool)
4626 PropertySpecNameToPermanentId(JSContext* cx, const char* name, jsid* idp);
4628 } /* namespace JS */
4630 /************************************************************************/
4632 * JSON functions
4634 typedef bool (* JSONWriteCallback)(const char16_t* buf, uint32_t len, void* data);
4637 * JSON.stringify as specified by ES5.
4639 JS_PUBLIC_API(bool)
4640 JS_Stringify(JSContext* cx, JS::MutableHandleValue value, JS::HandleObject replacer,
4641 JS::HandleValue space, JSONWriteCallback callback, void* data);
4644 * JSON.parse as specified by ES5.
4646 JS_PUBLIC_API(bool)
4647 JS_ParseJSON(JSContext* cx, const char16_t* chars, uint32_t len, JS::MutableHandleValue vp);
4649 JS_PUBLIC_API(bool)
4650 JS_ParseJSON(JSContext* cx, JS::HandleString str, JS::MutableHandleValue vp);
4652 JS_PUBLIC_API(bool)
4653 JS_ParseJSONWithReviver(JSContext* cx, const char16_t* chars, uint32_t len, JS::HandleValue reviver,
4654 JS::MutableHandleValue vp);
4656 JS_PUBLIC_API(bool)
4657 JS_ParseJSONWithReviver(JSContext* cx, JS::HandleString str, JS::HandleValue reviver,
4658 JS::MutableHandleValue vp);
4660 /************************************************************************/
4663 * The default locale for the ECMAScript Internationalization API
4664 * (Intl.Collator, Intl.NumberFormat, Intl.DateTimeFormat).
4665 * Note that the Internationalization API encourages clients to
4666 * specify their own locales.
4667 * The locale string remains owned by the caller.
4669 extern JS_PUBLIC_API(bool)
4670 JS_SetDefaultLocale(JSRuntime* rt, const char* locale);
4673 * Reset the default locale to OS defaults.
4675 extern JS_PUBLIC_API(void)
4676 JS_ResetDefaultLocale(JSRuntime* rt);
4679 * Locale specific string conversion and error message callbacks.
4681 struct JSLocaleCallbacks {
4682 JSLocaleToUpperCase localeToUpperCase;
4683 JSLocaleToLowerCase localeToLowerCase;
4684 JSLocaleCompare localeCompare; // not used #if EXPOSE_INTL_API
4685 JSLocaleToUnicode localeToUnicode;
4689 * Establish locale callbacks. The pointer must persist as long as the
4690 * JSRuntime. Passing nullptr restores the default behaviour.
4692 extern JS_PUBLIC_API(void)
4693 JS_SetLocaleCallbacks(JSRuntime* rt, const JSLocaleCallbacks* callbacks);
4696 * Return the address of the current locale callbacks struct, which may
4697 * be nullptr.
4699 extern JS_PUBLIC_API(const JSLocaleCallbacks*)
4700 JS_GetLocaleCallbacks(JSRuntime* rt);
4702 /************************************************************************/
4705 * Error reporting.
4709 * Report an exception represented by the sprintf-like conversion of format
4710 * and its arguments. This exception message string is passed to a pre-set
4711 * JSErrorReporter function (set by JS_SetErrorReporter).
4713 extern JS_PUBLIC_API(void)
4714 JS_ReportError(JSContext* cx, const char* format, ...);
4717 * Use an errorNumber to retrieve the format string, args are char*
4719 extern JS_PUBLIC_API(void)
4720 JS_ReportErrorNumber(JSContext* cx, JSErrorCallback errorCallback,
4721 void* userRef, const unsigned errorNumber, ...);
4723 #ifdef va_start
4724 extern JS_PUBLIC_API(void)
4725 JS_ReportErrorNumberVA(JSContext* cx, JSErrorCallback errorCallback,
4726 void* userRef, const unsigned errorNumber, va_list ap);
4727 #endif
4730 * Use an errorNumber to retrieve the format string, args are char16_t*
4732 extern JS_PUBLIC_API(void)
4733 JS_ReportErrorNumberUC(JSContext* cx, JSErrorCallback errorCallback,
4734 void* userRef, const unsigned errorNumber, ...);
4736 extern JS_PUBLIC_API(void)
4737 JS_ReportErrorNumberUCArray(JSContext* cx, JSErrorCallback errorCallback,
4738 void* userRef, const unsigned errorNumber,
4739 const char16_t** args);
4742 * As above, but report a warning instead (JSREPORT_IS_WARNING(report.flags)).
4743 * Return true if there was no error trying to issue the warning, and if the
4744 * warning was not converted into an error due to the JSOPTION_WERROR option
4745 * being set, false otherwise.
4747 extern JS_PUBLIC_API(bool)
4748 JS_ReportWarning(JSContext* cx, const char* format, ...);
4750 extern JS_PUBLIC_API(bool)
4751 JS_ReportErrorFlagsAndNumber(JSContext* cx, unsigned flags,
4752 JSErrorCallback errorCallback, void* userRef,
4753 const unsigned errorNumber, ...);
4755 extern JS_PUBLIC_API(bool)
4756 JS_ReportErrorFlagsAndNumberUC(JSContext* cx, unsigned flags,
4757 JSErrorCallback errorCallback, void* userRef,
4758 const unsigned errorNumber, ...);
4761 * Complain when out of memory.
4763 extern JS_PUBLIC_API(void)
4764 JS_ReportOutOfMemory(JSContext* cx);
4767 * Complain when an allocation size overflows the maximum supported limit.
4769 extern JS_PUBLIC_API(void)
4770 JS_ReportAllocationOverflow(JSContext* cx);
4772 class JSErrorReport
4774 public:
4775 JSErrorReport()
4776 : filename(nullptr), lineno(0), column(0), isMuted(false), linebuf(nullptr),
4777 tokenptr(nullptr), uclinebuf(nullptr), uctokenptr(nullptr), flags(0), errorNumber(0),
4778 ucmessage(nullptr), messageArgs(nullptr), exnType(0)
4781 const char* filename; /* source file name, URL, etc., or null */
4782 unsigned lineno; /* source line number */
4783 unsigned column; /* zero-based column index in line */
4784 bool isMuted; /* See the comment in ReadOnlyCompileOptions. */
4785 const char* linebuf; /* offending source line without final \n */
4786 const char* tokenptr; /* pointer to error token in linebuf */
4787 const char16_t* uclinebuf; /* unicode (original) line buffer */
4788 const char16_t* uctokenptr; /* unicode (original) token pointer */
4789 unsigned flags; /* error/warning, etc. */
4790 unsigned errorNumber; /* the error number, e.g. see js.msg */
4791 const char16_t* ucmessage; /* the (default) error message */
4792 const char16_t** messageArgs; /* arguments for the error message */
4793 int16_t exnType; /* One of the JSExnType constants */
4797 * JSErrorReport flag values. These may be freely composed.
4799 #define JSREPORT_ERROR 0x0 /* pseudo-flag for default case */
4800 #define JSREPORT_WARNING 0x1 /* reported via JS_ReportWarning */
4801 #define JSREPORT_EXCEPTION 0x2 /* exception was thrown */
4802 #define JSREPORT_STRICT 0x4 /* error or warning due to strict option */
4805 * This condition is an error in strict mode code, a warning if
4806 * JS_HAS_STRICT_OPTION(cx), and otherwise should not be reported at
4807 * all. We check the strictness of the context's top frame's script;
4808 * where that isn't appropriate, the caller should do the right checks
4809 * itself instead of using this flag.
4811 #define JSREPORT_STRICT_MODE_ERROR 0x8
4814 * If JSREPORT_EXCEPTION is set, then a JavaScript-catchable exception
4815 * has been thrown for this runtime error, and the host should ignore it.
4816 * Exception-aware hosts should also check for JS_IsExceptionPending if
4817 * JS_ExecuteScript returns failure, and signal or propagate the exception, as
4818 * appropriate.
4820 #define JSREPORT_IS_WARNING(flags) (((flags) & JSREPORT_WARNING) != 0)
4821 #define JSREPORT_IS_EXCEPTION(flags) (((flags) & JSREPORT_EXCEPTION) != 0)
4822 #define JSREPORT_IS_STRICT(flags) (((flags) & JSREPORT_STRICT) != 0)
4823 #define JSREPORT_IS_STRICT_MODE_ERROR(flags) (((flags) & \
4824 JSREPORT_STRICT_MODE_ERROR) != 0)
4825 extern JS_PUBLIC_API(JSErrorReporter)
4826 JS_GetErrorReporter(JSRuntime* rt);
4828 extern JS_PUBLIC_API(JSErrorReporter)
4829 JS_SetErrorReporter(JSRuntime* rt, JSErrorReporter er);
4831 namespace JS {
4833 extern JS_PUBLIC_API(bool)
4834 CreateError(JSContext* cx, JSExnType type, HandleString stack,
4835 HandleString fileName, uint32_t lineNumber, uint32_t columnNumber,
4836 JSErrorReport* report, HandleString message, MutableHandleValue rval);
4838 /************************************************************************/
4841 * Weak Maps.
4844 extern JS_PUBLIC_API(JSObject*)
4845 NewWeakMapObject(JSContext* cx);
4847 extern JS_PUBLIC_API(bool)
4848 IsWeakMapObject(JSObject* obj);
4850 extern JS_PUBLIC_API(bool)
4851 GetWeakMapEntry(JSContext* cx, JS::HandleObject mapObj, JS::HandleObject key,
4852 JS::MutableHandleValue val);
4854 extern JS_PUBLIC_API(bool)
4855 SetWeakMapEntry(JSContext* cx, JS::HandleObject mapObj, JS::HandleObject key,
4856 JS::HandleValue val);
4859 * Map
4861 extern JS_PUBLIC_API(JSObject*)
4862 NewMapObject(JSContext* cx);
4864 extern JS_PUBLIC_API(uint32_t)
4865 MapSize(JSContext* cx, HandleObject obj);
4867 extern JS_PUBLIC_API(bool)
4868 MapGet(JSContext* cx, HandleObject obj,
4869 HandleValue key, MutableHandleValue rval);
4871 extern JS_PUBLIC_API(bool)
4872 MapHas(JSContext* cx, HandleObject obj, HandleValue key, bool* rval);
4874 extern JS_PUBLIC_API(bool)
4875 MapSet(JSContext* cx, HandleObject obj, HandleValue key, HandleValue val);
4877 extern JS_PUBLIC_API(bool)
4878 MapClear(JSContext* cx, HandleObject obj);
4880 extern JS_PUBLIC_API(bool)
4881 MapKeys(JSContext* cx, HandleObject obj, MutableHandleValue rval);
4883 extern JS_PUBLIC_API(bool)
4884 MapValues(JSContext* cx, HandleObject obj, MutableHandleValue rval);
4886 extern JS_PUBLIC_API(bool)
4887 MapEntries(JSContext* cx, HandleObject obj, MutableHandleValue rval);
4889 } /* namespace JS */
4892 * Dates.
4895 extern JS_PUBLIC_API(JSObject*)
4896 JS_NewDateObject(JSContext* cx, int year, int mon, int mday, int hour, int min, int sec);
4898 extern JS_PUBLIC_API(JSObject*)
4899 JS_NewDateObjectMsec(JSContext* cx, double msec);
4902 * Infallible predicate to test whether obj is a date object.
4904 extern JS_PUBLIC_API(bool)
4905 JS_ObjectIsDate(JSContext* cx, JS::HandleObject obj);
4908 * Clears the cache of calculated local time from each Date object.
4909 * Call to propagate a system timezone change.
4911 extern JS_PUBLIC_API(void)
4912 JS_ClearDateCaches(JSContext* cx);
4914 /************************************************************************/
4917 * Regular Expressions.
4919 #define JSREG_FOLD 0x01u /* fold uppercase to lowercase */
4920 #define JSREG_GLOB 0x02u /* global exec, creates array of matches */
4921 #define JSREG_MULTILINE 0x04u /* treat ^ and $ as begin and end of line */
4922 #define JSREG_STICKY 0x08u /* only match starting at lastIndex */
4924 extern JS_PUBLIC_API(JSObject*)
4925 JS_NewRegExpObject(JSContext* cx, JS::HandleObject obj, const char* bytes, size_t length,
4926 unsigned flags);
4928 extern JS_PUBLIC_API(JSObject*)
4929 JS_NewUCRegExpObject(JSContext* cx, JS::HandleObject obj, const char16_t* chars, size_t length,
4930 unsigned flags);
4932 extern JS_PUBLIC_API(bool)
4933 JS_SetRegExpInput(JSContext* cx, JS::HandleObject obj, JS::HandleString input,
4934 bool multiline);
4936 extern JS_PUBLIC_API(bool)
4937 JS_ClearRegExpStatics(JSContext* cx, JS::HandleObject obj);
4939 extern JS_PUBLIC_API(bool)
4940 JS_ExecuteRegExp(JSContext* cx, JS::HandleObject obj, JS::HandleObject reobj,
4941 char16_t* chars, size_t length, size_t* indexp, bool test,
4942 JS::MutableHandleValue rval);
4944 /* RegExp interface for clients without a global object. */
4946 extern JS_PUBLIC_API(JSObject*)
4947 JS_NewRegExpObjectNoStatics(JSContext* cx, char* bytes, size_t length, unsigned flags);
4949 extern JS_PUBLIC_API(JSObject*)
4950 JS_NewUCRegExpObjectNoStatics(JSContext* cx, char16_t* chars, size_t length, unsigned flags);
4952 extern JS_PUBLIC_API(bool)
4953 JS_ExecuteRegExpNoStatics(JSContext* cx, JS::HandleObject reobj, char16_t* chars, size_t length,
4954 size_t* indexp, bool test, JS::MutableHandleValue rval);
4956 extern JS_PUBLIC_API(bool)
4957 JS_ObjectIsRegExp(JSContext* cx, JS::HandleObject obj);
4959 extern JS_PUBLIC_API(unsigned)
4960 JS_GetRegExpFlags(JSContext* cx, JS::HandleObject obj);
4962 extern JS_PUBLIC_API(JSString*)
4963 JS_GetRegExpSource(JSContext* cx, JS::HandleObject obj);
4965 /************************************************************************/
4967 extern JS_PUBLIC_API(bool)
4968 JS_IsExceptionPending(JSContext* cx);
4970 extern JS_PUBLIC_API(bool)
4971 JS_GetPendingException(JSContext* cx, JS::MutableHandleValue vp);
4973 extern JS_PUBLIC_API(void)
4974 JS_SetPendingException(JSContext* cx, JS::HandleValue v);
4976 extern JS_PUBLIC_API(void)
4977 JS_ClearPendingException(JSContext* cx);
4979 extern JS_PUBLIC_API(bool)
4980 JS_ReportPendingException(JSContext* cx);
4982 namespace JS {
4985 * Save and later restore the current exception state of a given JSContext.
4986 * This is useful for implementing behavior in C++ that's like try/catch
4987 * or try/finally in JS.
4989 * Typical usage:
4991 * bool ok = JS::Evaluate(cx, ...);
4992 * AutoSaveExceptionState savedExc(cx);
4993 * ... cleanup that might re-enter JS ...
4994 * return ok;
4996 class JS_PUBLIC_API(AutoSaveExceptionState)
4998 private:
4999 JSContext* context;
5000 bool wasPropagatingForcedReturn;
5001 bool wasOverRecursed;
5002 bool wasThrowing;
5003 RootedValue exceptionValue;
5005 public:
5007 * Take a snapshot of cx's current exception state. Then clear any current
5008 * pending exception in cx.
5010 explicit AutoSaveExceptionState(JSContext* cx);
5013 * If neither drop() nor restore() was called, restore the exception
5014 * state only if no exception is currently pending on cx.
5016 ~AutoSaveExceptionState();
5019 * Discard any stored exception state.
5020 * If this is called, the destructor is a no-op.
5022 void drop() {
5023 wasPropagatingForcedReturn = false;
5024 wasOverRecursed = false;
5025 wasThrowing = false;
5026 exceptionValue.setUndefined();
5030 * Replace cx's exception state with the stored exception state. Then
5031 * discard the stored exception state. If this is called, the
5032 * destructor is a no-op.
5034 void restore();
5037 } /* namespace JS */
5039 /* Deprecated API. Use AutoSaveExceptionState instead. */
5040 extern JS_PUBLIC_API(JSExceptionState*)
5041 JS_SaveExceptionState(JSContext* cx);
5043 extern JS_PUBLIC_API(void)
5044 JS_RestoreExceptionState(JSContext* cx, JSExceptionState* state);
5046 extern JS_PUBLIC_API(void)
5047 JS_DropExceptionState(JSContext* cx, JSExceptionState* state);
5050 * If the given object is an exception object, the exception will have (or be
5051 * able to lazily create) an error report struct, and this function will return
5052 * the address of that struct. Otherwise, it returns nullptr. The lifetime
5053 * of the error report struct that might be returned is the same as the
5054 * lifetime of the exception object.
5056 extern JS_PUBLIC_API(JSErrorReport*)
5057 JS_ErrorFromException(JSContext* cx, JS::HandleObject obj);
5060 * Throws a StopIteration exception on cx.
5062 extern JS_PUBLIC_API(bool)
5063 JS_ThrowStopIteration(JSContext* cx);
5065 extern JS_PUBLIC_API(bool)
5066 JS_IsStopIteration(jsval v);
5068 extern JS_PUBLIC_API(intptr_t)
5069 JS_GetCurrentThread();
5072 * A JS runtime always has an "owner thread". The owner thread is set when the
5073 * runtime is created (to the current thread) and practically all entry points
5074 * into the JS engine check that a runtime (or anything contained in the
5075 * runtime: context, compartment, object, etc) is only touched by its owner
5076 * thread. Embeddings may check this invariant outside the JS engine by calling
5077 * JS_AbortIfWrongThread (which will abort if not on the owner thread, even for
5078 * non-debug builds).
5081 extern JS_PUBLIC_API(void)
5082 JS_AbortIfWrongThread(JSRuntime* rt);
5084 /************************************************************************/
5087 * A constructor can request that the JS engine create a default new 'this'
5088 * object of the given class, using the callee to determine parentage and
5089 * [[Prototype]].
5091 extern JS_PUBLIC_API(JSObject*)
5092 JS_NewObjectForConstructor(JSContext* cx, const JSClass* clasp, const JS::CallArgs& args);
5094 /************************************************************************/
5096 #ifdef JS_GC_ZEAL
5097 #define JS_DEFAULT_ZEAL_FREQ 100
5099 extern JS_PUBLIC_API(void)
5100 JS_GetGCZeal(JSContext* cx, uint8_t* zeal, uint32_t* frequency, uint32_t* nextScheduled);
5102 extern JS_PUBLIC_API(void)
5103 JS_SetGCZeal(JSContext* cx, uint8_t zeal, uint32_t frequency);
5105 extern JS_PUBLIC_API(void)
5106 JS_ScheduleGC(JSContext* cx, uint32_t count);
5107 #endif
5109 extern JS_PUBLIC_API(void)
5110 JS_SetParallelParsingEnabled(JSRuntime* rt, bool enabled);
5112 extern JS_PUBLIC_API(void)
5113 JS_SetOffthreadIonCompilationEnabled(JSRuntime* rt, bool enabled);
5115 #define JIT_COMPILER_OPTIONS(Register) \
5116 Register(BASELINE_WARMUP_TRIGGER, "baseline.warmup.trigger") \
5117 Register(ION_WARMUP_TRIGGER, "ion.warmup.trigger") \
5118 Register(ION_ENABLE, "ion.enable") \
5119 Register(BASELINE_ENABLE, "baseline.enable") \
5120 Register(OFFTHREAD_COMPILATION_ENABLE, "offthread-compilation.enable") \
5121 Register(SIGNALS_ENABLE, "signals.enable")
5123 typedef enum JSJitCompilerOption {
5124 #define JIT_COMPILER_DECLARE(key, str) \
5125 JSJITCOMPILER_ ## key,
5127 JIT_COMPILER_OPTIONS(JIT_COMPILER_DECLARE)
5128 #undef JIT_COMPILER_DECLARE
5130 JSJITCOMPILER_NOT_AN_OPTION
5131 } JSJitCompilerOption;
5133 extern JS_PUBLIC_API(void)
5134 JS_SetGlobalJitCompilerOption(JSRuntime* rt, JSJitCompilerOption opt, uint32_t value);
5135 extern JS_PUBLIC_API(int)
5136 JS_GetGlobalJitCompilerOption(JSRuntime* rt, JSJitCompilerOption opt);
5139 * Convert a uint32_t index into a jsid.
5141 extern JS_PUBLIC_API(bool)
5142 JS_IndexToId(JSContext* cx, uint32_t index, JS::MutableHandleId);
5145 * Convert chars into a jsid.
5147 * |chars| may not be an index.
5149 extern JS_PUBLIC_API(bool)
5150 JS_CharsToId(JSContext* cx, JS::TwoByteChars chars, JS::MutableHandleId);
5153 * Test if the given string is a valid ECMAScript identifier
5155 extern JS_PUBLIC_API(bool)
5156 JS_IsIdentifier(JSContext* cx, JS::HandleString str, bool* isIdentifier);
5159 * Test whether the given chars + length are a valid ECMAScript identifier.
5160 * This version is infallible, so just returns whether the chars are an
5161 * identifier.
5163 extern JS_PUBLIC_API(bool)
5164 JS_IsIdentifier(const char16_t* chars, size_t length);
5166 namespace JS {
5169 * AutoFilename encapsulates a pointer to a C-string and keeps the C-string
5170 * alive for as long as the associated AutoFilename object is alive.
5172 class MOZ_STACK_CLASS JS_PUBLIC_API(AutoFilename)
5174 void* scriptSource_;
5176 AutoFilename(const AutoFilename&) = delete;
5177 void operator=(const AutoFilename&) = delete;
5179 public:
5180 AutoFilename() : scriptSource_(nullptr) {}
5181 ~AutoFilename() { reset(nullptr); }
5183 const char* get() const;
5185 void reset(void* newScriptSource);
5189 * Return the current filename and line number of the most currently running
5190 * frame. Returns true if a scripted frame was found, false otherwise.
5192 * If a the embedding has hidden the scripted caller for the topmost activation
5193 * record, this will also return false.
5195 extern JS_PUBLIC_API(bool)
5196 DescribeScriptedCaller(JSContext* cx, AutoFilename* filename = nullptr,
5197 unsigned* lineno = nullptr);
5199 extern JS_PUBLIC_API(JSObject*)
5200 GetScriptedCallerGlobal(JSContext* cx);
5203 * Informs the JS engine that the scripted caller should be hidden. This can be
5204 * used by the embedding to maintain an override of the scripted caller in its
5205 * calculations, by hiding the scripted caller in the JS engine and pushing data
5206 * onto a separate stack, which it inspects when DescribeScriptedCaller returns
5207 * null.
5209 * We maintain a counter on each activation record. Add() increments the counter
5210 * of the topmost activation, and Remove() decrements it. The count may never
5211 * drop below zero, and must always be exactly zero when the activation is
5212 * popped from the stack.
5214 extern JS_PUBLIC_API(void)
5215 HideScriptedCaller(JSContext* cx);
5217 extern JS_PUBLIC_API(void)
5218 UnhideScriptedCaller(JSContext* cx);
5220 class AutoHideScriptedCaller
5222 public:
5223 explicit AutoHideScriptedCaller(JSContext* cx
5224 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
5225 : mContext(cx)
5227 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
5228 HideScriptedCaller(mContext);
5230 ~AutoHideScriptedCaller() {
5231 UnhideScriptedCaller(mContext);
5234 protected:
5235 JSContext* mContext;
5236 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
5239 } /* namespace JS */
5242 * Encode/Decode interpreted scripts and functions to/from memory.
5245 extern JS_PUBLIC_API(void*)
5246 JS_EncodeScript(JSContext* cx, JS::HandleScript script, uint32_t* lengthp);
5248 extern JS_PUBLIC_API(void*)
5249 JS_EncodeInterpretedFunction(JSContext* cx, JS::HandleObject funobj, uint32_t* lengthp);
5251 extern JS_PUBLIC_API(JSScript*)
5252 JS_DecodeScript(JSContext* cx, const void* data, uint32_t length);
5254 extern JS_PUBLIC_API(JSObject*)
5255 JS_DecodeInterpretedFunction(JSContext* cx, const void* data, uint32_t length);
5257 namespace JS {
5260 * This callback represents a request by the JS engine to open for reading the
5261 * existing cache entry for the given global and char range that may contain a
5262 * module. If a cache entry exists, the callback shall return 'true' and return
5263 * the size, base address and an opaque file handle as outparams. If the
5264 * callback returns 'true', the JS engine guarantees a call to
5265 * CloseAsmJSCacheEntryForReadOp, passing the same base address, size and
5266 * handle.
5268 typedef bool
5269 (* OpenAsmJSCacheEntryForReadOp)(HandleObject global, const char16_t* begin, const char16_t* limit,
5270 size_t* size, const uint8_t** memory, intptr_t* handle);
5271 typedef void
5272 (* CloseAsmJSCacheEntryForReadOp)(size_t size, const uint8_t* memory, intptr_t handle);
5274 /* The list of reasons why an asm.js module may not be stored in the cache. */
5275 enum AsmJSCacheResult
5277 AsmJSCache_MIN,
5278 AsmJSCache_Success = AsmJSCache_MIN,
5279 AsmJSCache_ModuleTooSmall,
5280 AsmJSCache_SynchronousScript,
5281 AsmJSCache_QuotaExceeded,
5282 AsmJSCache_Disabled_Internal,
5283 AsmJSCache_Disabled_ShellFlags,
5284 AsmJSCache_Disabled_JitInspector,
5285 AsmJSCache_InternalError,
5286 AsmJSCache_LIMIT
5290 * This callback represents a request by the JS engine to open for writing a
5291 * cache entry of the given size for the given global and char range containing
5292 * the just-compiled module. If cache entry space is available, the callback
5293 * shall return 'true' and return the base address and an opaque file handle as
5294 * outparams. If the callback returns 'true', the JS engine guarantees a call
5295 * to CloseAsmJSCacheEntryForWriteOp passing the same base address, size and
5296 * handle.
5298 * If 'installed' is true, then the cache entry is associated with a permanently
5299 * installed JS file (e.g., in a packaged webapp). This information allows the
5300 * embedding to store the cache entry in a installed location associated with
5301 * the principal of 'global' where it will not be evicted until the associated
5302 * installed JS file is removed.
5304 typedef AsmJSCacheResult
5305 (* OpenAsmJSCacheEntryForWriteOp)(HandleObject global, bool installed,
5306 const char16_t* begin, const char16_t* end,
5307 size_t size, uint8_t** memory, intptr_t* handle);
5308 typedef void
5309 (* CloseAsmJSCacheEntryForWriteOp)(size_t size, uint8_t* memory, intptr_t handle);
5311 typedef js::Vector<char, 0, js::SystemAllocPolicy> BuildIdCharVector;
5313 // Return the buildId (represented as a sequence of characters) associated with
5314 // the currently-executing build. If the JS engine is embedded such that a
5315 // single cache entry can be observed by different compiled versions of the JS
5316 // engine, it is critical that the buildId shall change for each new build of
5317 // the JS engine.
5319 typedef bool
5320 (* BuildIdOp)(BuildIdCharVector* buildId);
5322 struct AsmJSCacheOps
5324 OpenAsmJSCacheEntryForReadOp openEntryForRead;
5325 CloseAsmJSCacheEntryForReadOp closeEntryForRead;
5326 OpenAsmJSCacheEntryForWriteOp openEntryForWrite;
5327 CloseAsmJSCacheEntryForWriteOp closeEntryForWrite;
5328 BuildIdOp buildId;
5331 extern JS_PUBLIC_API(void)
5332 SetAsmJSCacheOps(JSRuntime* rt, const AsmJSCacheOps* callbacks);
5335 * Convenience class for imitating a JS level for-of loop. Typical usage:
5337 * ForOfIterator it(cx);
5338 * if (!it.init(iterable))
5339 * return false;
5340 * RootedValue val(cx);
5341 * while (true) {
5342 * bool done;
5343 * if (!it.next(&val, &done))
5344 * return false;
5345 * if (done)
5346 * break;
5347 * if (!DoStuff(cx, val))
5348 * return false;
5351 class MOZ_STACK_CLASS JS_PUBLIC_API(ForOfIterator) {
5352 protected:
5353 JSContext* cx_;
5355 * Use the ForOfPIC on the global object (see vm/GlobalObject.h) to try
5356 * to optimize iteration across arrays.
5358 * Case 1: Regular Iteration
5359 * iterator - pointer to the iterator object.
5360 * index - fixed to NOT_ARRAY (== UINT32_MAX)
5362 * Case 2: Optimized Array Iteration
5363 * iterator - pointer to the array object.
5364 * index - current position in array.
5366 * The cases are distinguished by whether or not |index| is equal to NOT_ARRAY.
5368 JS::RootedObject iterator;
5369 uint32_t index;
5371 static const uint32_t NOT_ARRAY = UINT32_MAX;
5373 ForOfIterator(const ForOfIterator&) = delete;
5374 ForOfIterator& operator=(const ForOfIterator&) = delete;
5376 public:
5377 explicit ForOfIterator(JSContext* cx) : cx_(cx), iterator(cx_), index(NOT_ARRAY) { }
5379 enum NonIterableBehavior {
5380 ThrowOnNonIterable,
5381 AllowNonIterable
5385 * Initialize the iterator. If AllowNonIterable is passed then if getting
5386 * the @@iterator property from iterable returns undefined init() will just
5387 * return true instead of throwing. Callers must then check
5388 * valueIsIterable() before continuing with the iteration.
5390 bool init(JS::HandleValue iterable,
5391 NonIterableBehavior nonIterableBehavior = ThrowOnNonIterable);
5394 * This method assumes that |iterator| is already an iterator. It will not
5395 * check for, and call @@iterator. Callers should make sure that the passed
5396 * in value is in fact an iterator.
5398 bool initWithIterator(JS::HandleValue aIterator);
5401 * Get the next value from the iterator. If false *done is true
5402 * after this call, do not examine val.
5404 bool next(JS::MutableHandleValue val, bool* done);
5407 * If initialized with throwOnNonCallable = false, check whether
5408 * the value is iterable.
5410 bool valueIsIterable() const {
5411 return iterator;
5414 private:
5415 inline bool nextFromOptimizedArray(MutableHandleValue val, bool* done);
5416 bool materializeArrayIterator();
5421 * If a large allocation fails when calling pod_{calloc,realloc}CanGC, the JS
5422 * engine may call the large-allocation- failure callback, if set, to allow the
5423 * embedding to flush caches, possibly perform shrinking GCs, etc. to make some
5424 * room. The allocation will then be retried (and may still fail.)
5427 typedef void
5428 (* LargeAllocationFailureCallback)(void* data);
5430 extern JS_PUBLIC_API(void)
5431 SetLargeAllocationFailureCallback(JSRuntime* rt, LargeAllocationFailureCallback afc, void* data);
5434 * Unlike the error reporter, which is only called if the exception for an OOM
5435 * bubbles up and is not caught, the OutOfMemoryCallback is called immediately
5436 * at the OOM site to allow the embedding to capture the current state of heap
5437 * allocation before anything is freed. If the large-allocation-failure callback
5438 * is called at all (not all allocation sites call the large-allocation-failure
5439 * callback on failure), it is called before the out-of-memory callback; the
5440 * out-of-memory callback is only called if the allocation still fails after the
5441 * large-allocation-failure callback has returned.
5444 typedef void
5445 (* OutOfMemoryCallback)(JSContext* cx, void* data);
5447 extern JS_PUBLIC_API(void)
5448 SetOutOfMemoryCallback(JSRuntime* rt, OutOfMemoryCallback cb, void* data);
5452 * Capture the current call stack as a chain of SavedFrame objects, and set
5453 * |stackp| to the SavedFrame for the newest stack frame. If |maxFrameCount| is
5454 * non-zero, capture at most the youngest |maxFrameCount| frames.
5456 extern JS_PUBLIC_API(bool)
5457 CaptureCurrentStack(JSContext* cx, MutableHandleObject stackp, unsigned maxFrameCount = 0);
5459 } /* namespace JS */
5461 #endif /* jsapi_h */