1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sw=4 et tw=78:
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
17 * The Original Code is Mozilla Communicator client code, released
20 * The Initial Developer of the Original Code is
21 * Netscape Communications Corporation.
22 * Portions created by the Initial Developer are Copyright (C) 1998
23 * the Initial Developer. All Rights Reserved.
27 * Alternatively, the contents of this file may be used under the terms of
28 * either of the GNU General Public License Version 2 or later (the "GPL"),
29 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30 * in which case the provisions of the GPL or the LGPL are applicable instead
31 * of those above. If you wish to allow use of your version of this file only
32 * under the terms of either the GPL or the LGPL, and not to allow others to
33 * use your version of this file under the terms of the MPL, indicate your
34 * decision by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL or the LGPL. If you do not delete
36 * the provisions above, a recipient may use your version of this file under
37 * the terms of any one of the MPL, the GPL or the LGPL.
39 * ***** END LICENSE BLOCK ***** */
44 * JS execution context.
46 #include "jsarena.h" /* Added by JSIFY */
63 * js_GetSrcNote cache to avoid O(n^2) growth in finding a source note for a
64 * given pc in a script.
66 typedef struct JSGSNCache
{
74 # define GSN_CACHE_METER(cache,cnt) (++(cache)->cnt)
76 # define GSN_CACHE_METER(cache,cnt) /* nothing */
80 #define GSN_CACHE_CLEAR(cache) \
82 (cache)->script = NULL; \
83 if ((cache)->table.ops) { \
84 JS_DHashTableFinish(&(cache)->table); \
85 (cache)->table.ops = NULL; \
87 GSN_CACHE_METER(cache, clears); \
90 /* These helper macros take a cx as parameter and operate on its GSN cache. */
91 #define JS_CLEAR_GSN_CACHE(cx) GSN_CACHE_CLEAR(&JS_GSN_CACHE(cx))
92 #define JS_METER_GSN_CACHE(cx,cnt) GSN_CACHE_METER(&JS_GSN_CACHE(cx), cnt)
97 * Structure uniquely representing a thread. It holds thread-private data
98 * that can be accessed without a global lock.
101 /* Linked list of all contexts active on this thread. */
104 /* Opaque thread-id, from NSPR's PR_GetCurrentThread(). */
107 /* Thread-local gc free lists array. */
108 JSGCThing
*gcFreeLists
[GC_NUM_FREELISTS
];
111 * Thread-local version of JSRuntime.gcMallocBytes to avoid taking
112 * locks on each JS_malloc.
114 uint32 gcMallocBytes
;
117 * Store the GSN cache in struct JSThread, not struct JSContext, both to
118 * save space and to simplify cleanup in js_GC. Any embedding (Firefox
119 * or another Gecko application) that uses many contexts per thread is
120 * unlikely to interleave js_GetSrcNote-intensive loops in the decompiler
121 * among two or more contexts running script in one thread.
126 #define JS_GSN_CACHE(cx) ((cx)->thread->gsnCache)
128 extern void JS_DLL_CALLBACK
129 js_ThreadDestructorCB(void *ptr
);
132 js_SetContextThread(JSContext
*cx
);
135 js_ClearContextThread(JSContext
*cx
);
138 js_GetCurrentThread(JSRuntime
*rt
);
140 #endif /* JS_THREADSAFE */
142 typedef enum JSDestroyContextMode
{
147 } JSDestroyContextMode
;
149 typedef enum JSRuntimeState
{
156 typedef struct JSPropertyTreeEntry
{
158 JSScopeProperty
*child
;
159 } JSPropertyTreeEntry
;
162 * Forward declaration for opaque JSRuntime.nativeIteratorStates.
164 typedef struct JSNativeIteratorState JSNativeIteratorState
;
167 /* Runtime state, synchronized by the stateChange/gcLock condvar/lock. */
168 JSRuntimeState state
;
170 /* Context create/destroy callback. */
171 JSContextCallback cxCallback
;
173 /* Garbage collector state, used by jsgc.c. */
174 JSGCArenaList gcArenaList
[GC_NUM_FREELISTS
];
175 JSDHashTable gcRootsHash
;
176 JSDHashTable
*gcLocksHash
;
177 jsrefcount gcKeepAtoms
;
181 uint32 gcMaxMallocBytes
;
184 JSTracer
*gcMarkingTracer
;
187 * NB: do not pack another flag here by claiming gcPadding unless the new
188 * flag is written only by the GC thread. Atomic updates to packed bytes
189 * are not guaranteed, so stores issued by one thread may be lost due to
190 * unsynchronized read-modify-write cycles on other threads.
193 JSPackedBool gcRunning
;
201 JSGCCallback gcCallback
;
202 JSGCThingCallback gcThingCallback
;
203 void *gcThingCallbackClosure
;
204 uint32 gcMallocBytes
;
205 JSGCArena
*gcUnscannedArenaStackTop
;
207 size_t gcUnscannedBagSize
;
211 * Table for tracking iterators to ensure that we close iterator's state
212 * before finalizing the iterable object.
214 JSPtrTable gcIteratorTable
;
221 * The trace operation and its data argument to trace embedding-specific
224 JSTraceDataOp gcExtraRootsTraceOp
;
225 void *gcExtraRootsData
;
227 /* Random number generator state, used by jsmath.c. */
228 JSBool rngInitialized
;
235 /* Well-known numbers held for use by this runtime's contexts. */
237 jsdouble
*jsNegativeInfinity
;
238 jsdouble
*jsPositiveInfinity
;
241 JSLock
*deflatedStringCacheLock
;
243 JSHashTable
*deflatedStringCache
;
245 uint32 deflatedStringCacheBytes
;
249 * Empty and unit-length strings held for use by this runtime's contexts.
250 * The unitStrings array and its elements are created on demand.
252 JSString
*emptyString
;
253 JSString
**unitStrings
;
255 /* List of active contexts sharing this runtime; protected by gcLock. */
258 /* Per runtime debug hooks -- see jsprvtd.h and jsdbgapi.h. */
259 JSDebugHooks globalDebugHooks
;
261 /* More debugging state, see jsdbgapi.c. */
263 JSCList watchPointList
;
265 /* Client opaque pointer */
269 /* These combine to interlock the GC and new requests. */
272 PRCondVar
*requestDone
;
276 /* Lock and owning thread pointer for JS_LOCK_RUNTIME. */
282 /* Used to synchronize down/up state change; protected by gcLock. */
283 PRCondVar
*stateChange
;
285 /* Used to serialize cycle checks when setting __proto__ or __parent__. */
287 PRCondVar
*setSlotDone
;
289 JSScope
*setSlotScope
; /* deadlock avoidance, see jslock.c */
292 * State for sharing single-threaded scopes, once a second thread tries to
293 * lock a scope. The scopeSharingDone condvar is protected by rt->gcLock,
294 * to minimize number of locks taken in JS_EndRequest.
296 * The scopeSharingTodo linked list is likewise "global" per runtime, not
297 * one-list-per-context, to conserve space over all contexts, optimizing
298 * for the likely case that scopes become shared rarely, and among a very
299 * small set of threads (contexts).
301 PRCondVar
*scopeSharingDone
;
302 JSScope
*scopeSharingTodo
;
305 * Magic terminator for the rt->scopeSharingTodo linked list, threaded through
306 * scope->u.link. This hack allows us to test whether a scope is on the list
307 * by asking whether scope->u.link is non-null. We use a large, likely bogus
308 * pointer here to distinguish this value from any valid u.count (small int)
311 #define NO_SCOPE_SHARING_TODO ((JSScope *) 0xfeedbeef)
314 * Lock serializing trapList and watchPointList accesses, and count of all
315 * mutations to trapList and watchPointList made by debugger threads. To
316 * keep the code simple, we define debuggerMutations for the thread-unsafe
319 PRLock
*debuggerLock
;
320 #endif /* JS_THREADSAFE */
321 uint32 debuggerMutations
;
324 * Check property accessibility for objects of arbitrary class. Used at
325 * present to check f.caller accessibility for any function object f.
327 JSCheckAccessOp checkObjectAccess
;
329 /* Security principals serialization support. */
330 JSPrincipalsTranscoder principalsTranscoder
;
332 /* Optional hook to find principals for an object in this runtime. */
333 JSObjectPrincipalsFinder findObjectPrincipals
;
336 * Shared scope property tree, and arena-pool for allocating its nodes.
337 * The propertyRemovals counter is incremented for every js_ClearScope,
338 * and for each js_RemoveScopeProperty that frees a slot in an object.
339 * See js_NativeGet and js_NativeSet in jsobj.c.
341 JSDHashTable propertyTreeHash
;
342 JSScopeProperty
*propertyFreeList
;
343 JSArenaPool propertyArenaPool
;
344 int32 propertyRemovals
;
346 /* Script filename table. */
347 struct JSHashTable
*scriptFilenameTable
;
348 JSCList scriptFilenamePrefixes
;
350 PRLock
*scriptFilenameTableLock
;
353 /* Number localization, used by jsnum.c */
354 const char *thousandsSeparator
;
355 const char *decimalSeparator
;
356 const char *numGrouping
;
359 * Weak references to lazily-created, well-known XML singletons.
361 * NB: Singleton objects must be carefully disconnected from the rest of
362 * the object graph usually associated with a JSContext's global object,
363 * including the set of standard class objects. See jsxml.c for details.
365 JSObject
*anynameObject
;
366 JSObject
*functionNamespaceObject
;
369 * A helper list for the GC, so it can mark native iterator states. See
370 * js_TraceNativeIteratorStates for details.
372 JSNativeIteratorState
*nativeIteratorStates
;
374 #ifndef JS_THREADSAFE
376 * For thread-unsafe embeddings, the GSN cache lives in the runtime and
377 * not each context, since we expect it to be filled once when decompiling
378 * a longer script, then hit repeatedly as js_GetSrcNote is called during
379 * the decompiler activation that filled it.
383 #define JS_GSN_CACHE(cx) ((cx)->runtime->gsnCache)
386 /* Literal table maintained by jsatom.c functions. */
387 JSAtomState atomState
;
390 /* Function invocation metering. */
391 jsrefcount inlineCalls
;
392 jsrefcount nativeCalls
;
393 jsrefcount nonInlineCalls
;
394 jsrefcount constructs
;
396 /* Scope lock and property metering. */
397 jsrefcount claimAttempts
;
398 jsrefcount claimedScopes
;
399 jsrefcount deadContexts
;
400 jsrefcount deadlocksAvoided
;
401 jsrefcount liveScopes
;
402 jsrefcount sharedScopes
;
403 jsrefcount totalScopes
;
404 jsrefcount badUndependStrings
;
405 jsrefcount liveScopeProps
;
406 jsrefcount totalScopeProps
;
407 jsrefcount livePropTreeNodes
;
408 jsrefcount duplicatePropTreeNodes
;
409 jsrefcount totalPropTreeNodes
;
410 jsrefcount propTreeKidsChunks
;
411 jsrefcount middleDeleteFixups
;
413 /* String instrumentation. */
414 jsrefcount liveStrings
;
415 jsrefcount totalStrings
;
416 jsrefcount liveDependentStrings
;
417 jsrefcount totalDependentStrings
;
419 double lengthSquaredSum
;
420 double strdepLengthSum
;
421 double strdepLengthSquaredSum
;
426 # define JS_RUNTIME_METER(rt, which) JS_ATOMIC_INCREMENT(&(rt)->which)
427 # define JS_RUNTIME_UNMETER(rt, which) JS_ATOMIC_DECREMENT(&(rt)->which)
429 # define JS_RUNTIME_METER(rt, which) /* nothing */
430 # define JS_RUNTIME_UNMETER(rt, which) /* nothing */
433 #define JS_KEEP_ATOMS(rt) JS_ATOMIC_INCREMENT(&(rt)->gcKeepAtoms);
434 #define JS_UNKEEP_ATOMS(rt) JS_ATOMIC_DECREMENT(&(rt)->gcKeepAtoms);
436 #ifdef JS_ARGUMENT_FORMATTER_DEFINED
438 * Linked list mapping format strings for JS_{Convert,Push}Arguments{,VA} to
439 * formatter functions. Elements are sorted in non-increasing format string
442 struct JSArgumentFormatMap
{
445 JSArgumentFormatter formatter
;
446 JSArgumentFormatMap
*next
;
450 struct JSStackHeader
{
455 #define JS_STACK_SEGMENT(sh) ((jsval *)(sh) + 2)
458 * Key and entry types for the JSContext.resolvingTable hash table, typedef'd
459 * here because all consumers need to see these declarations (and not just the
460 * typedef names, as would be the case for an opaque pointer-to-typedef'd-type
461 * declaration), along with cx->resolvingTable.
463 typedef struct JSResolvingKey
{
468 typedef struct JSResolvingEntry
{
474 #define JSRESFLAG_LOOKUP 0x1 /* resolving id from lookup */
475 #define JSRESFLAG_WATCH 0x2 /* resolving id from watch */
477 typedef struct JSLocalRootChunk JSLocalRootChunk
;
479 #define JSLRS_CHUNK_SHIFT 8
480 #define JSLRS_CHUNK_SIZE JS_BIT(JSLRS_CHUNK_SHIFT)
481 #define JSLRS_CHUNK_MASK JS_BITMASK(JSLRS_CHUNK_SHIFT)
483 struct JSLocalRootChunk
{
484 jsval roots
[JSLRS_CHUNK_SIZE
];
485 JSLocalRootChunk
*down
;
488 typedef struct JSLocalRootStack
{
491 JSLocalRootChunk
*topChunk
;
492 JSLocalRootChunk firstChunk
;
495 #define JSLRS_NULL_MARK ((uint32) -1)
498 * Macros to push/pop JSTempValueRooter instances to context-linked stack of
499 * temporary GC roots. If you need to protect a result value that flows out of
500 * a C function across several layers of other functions, use the
501 * js_LeaveLocalRootScopeWithResult internal API (see further below) instead.
503 * JSTempValueRooter.count defines the type of the rooted value referenced by
504 * JSTempValueRooter.u union of type JSTempValueUnion according to the
508 * JSTVU_SINGLE u.value contains the single value or GC-thing to root.
509 * JSTVU_TRACE u.trace holds a trace hook called to trace the values.
510 * JSTVU_SPROP u.sprop points to the property tree node to mark.
511 * JSTVU_WEAK_ROOTS u.weakRoots points to saved weak roots.
512 * JSTVU_PARSE_CONTEXT u.parseContext roots things generated during parsing.
513 * >= 0 u.array points to a stack-allocated vector of jsvals.
515 #define JSTVU_SINGLE (-1)
516 #define JSTVU_TRACE (-2)
517 #define JSTVU_SPROP (-3)
518 #define JSTVU_WEAK_ROOTS (-4)
519 #define JSTVU_PARSE_CONTEXT (-5)
522 * To root a single GC-thing pointer, which need not be tagged and stored as a
523 * jsval, use JS_PUSH_TEMP_ROOT_GCTHING. The macro reinterprets an arbitrary
524 * GC-thing as jsval. It works because a GC-thing is aligned on a 0 mod 8
525 * boundary, and object has the 0 jsval tag. So any GC-thing may be tagged as
526 * if it were an object and untagged, if it's then used only as an opaque
527 * pointer until discriminated by other means than tag bits (this is how the
528 * GC mark function uses its |thing| parameter -- it consults GC-thing flags
529 * stored separately from the thing to decide the type of thing).
531 * JS_PUSH_TEMP_ROOT_OBJECT and JS_PUSH_TEMP_ROOT_STRING are type-safe
532 * alternatives to JS_PUSH_TEMP_ROOT_GCTHING for JSObject and JSString. They
533 * also provide a simple way to get a single pointer to rooted JSObject or
534 * JSString via JS_PUSH_TEMP_ROOT_(OBJECT|STRTING)(cx, NULL, &tvr). Then
535 * &tvr.u.object or tvr.u.string gives the necessary pointer, which puns
536 * tvr.u.value safely because JSObject * and JSString * are GC-things and, as
537 * such, their tag bits are all zeroes.
539 * The following checks that this type-punning is possible.
541 JS_STATIC_ASSERT(sizeof(JSTempValueUnion
) == sizeof(jsval
));
542 JS_STATIC_ASSERT(sizeof(JSTempValueUnion
) == sizeof(JSObject
*));
544 #define JS_PUSH_TEMP_ROOT_COMMON(cx,tvr) \
546 JS_ASSERT((cx)->tempValueRooters != (tvr)); \
547 (tvr)->down = (cx)->tempValueRooters; \
548 (cx)->tempValueRooters = (tvr); \
551 #define JS_PUSH_SINGLE_TEMP_ROOT(cx,val,tvr) \
553 (tvr)->count = JSTVU_SINGLE; \
554 (tvr)->u.value = val; \
555 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
558 #define JS_PUSH_TEMP_ROOT(cx,cnt,arr,tvr) \
560 JS_ASSERT((ptrdiff_t)(cnt) >= 0); \
561 (tvr)->count = (ptrdiff_t)(cnt); \
562 (tvr)->u.array = (arr); \
563 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
566 #define JS_PUSH_TEMP_ROOT_TRACE(cx,trace_,tvr) \
568 (tvr)->count = JSTVU_TRACE; \
569 (tvr)->u.trace = (trace_); \
570 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
573 #define JS_PUSH_TEMP_ROOT_OBJECT(cx,obj,tvr) \
575 (tvr)->count = JSTVU_SINGLE; \
576 (tvr)->u.object = (obj); \
577 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
580 #define JS_PUSH_TEMP_ROOT_STRING(cx,str,tvr) \
582 (tvr)->count = JSTVU_SINGLE; \
583 (tvr)->u.string = (str); \
584 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
587 #define JS_PUSH_TEMP_ROOT_GCTHING(cx,thing,tvr) \
589 JS_ASSERT(JSVAL_IS_OBJECT((jsval)thing)); \
590 (tvr)->count = JSTVU_SINGLE; \
591 (tvr)->u.gcthing = (thing); \
592 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
595 #define JS_POP_TEMP_ROOT(cx,tvr) \
597 JS_ASSERT((cx)->tempValueRooters == (tvr)); \
598 (cx)->tempValueRooters = (tvr)->down; \
601 #define JS_TEMP_ROOT_EVAL(cx,cnt,val,expr) \
603 JSTempValueRooter tvr; \
604 JS_PUSH_TEMP_ROOT(cx, cnt, val, &tvr); \
606 JS_POP_TEMP_ROOT(cx, &tvr); \
609 #define JS_PUSH_TEMP_ROOT_SPROP(cx,sprop_,tvr) \
611 (tvr)->count = JSTVU_SPROP; \
612 (tvr)->u.sprop = (sprop_); \
613 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
616 #define JS_PUSH_TEMP_ROOT_WEAK_COPY(cx,weakRoots_,tvr) \
618 (tvr)->count = JSTVU_WEAK_ROOTS; \
619 (tvr)->u.weakRoots = (weakRoots_); \
620 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
623 #define JS_PUSH_TEMP_ROOT_PARSE_CONTEXT(cx,pc,tvr) \
625 (tvr)->count = JSTVU_PARSE_CONTEXT; \
626 (tvr)->u.parseContext = (pc); \
627 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
631 /* JSRuntime contextList linkage. */
634 /* Counter of operations for branch callback calls. */
635 uint32 operationCounter
;
637 #if JS_HAS_XML_SUPPORT
639 * Bit-set formed from binary exponentials of the XML_* tiny-ids defined
640 * for boolean settings in jsxml.c, plus an XSF_CACHE_VALID bit. Together
641 * these act as a cache of the boolean XML.ignore* and XML.prettyPrinting
642 * property values associated with this context's global object.
644 uint8 xmlSettingFlags
;
650 /* Runtime version control identifier. */
653 /* Per-context options. */
654 uint32 options
; /* see jsapi.h for JSOPTION_* */
656 /* Locale specific callbacks for string conversion. */
657 JSLocaleCallbacks
*localeCallbacks
;
660 * cx->resolvingTable is non-null and non-empty if we are initializing
661 * standard classes lazily, or if we are otherwise recursing indirectly
662 * from js_LookupProperty through a JSClass.resolve hook. It is used to
663 * limit runaway recursion (see jsapi.c and jsobj.c).
665 JSDHashTable
*resolvingTable
;
667 #if JS_HAS_LVALUE_RETURN
669 * Secondary return value from native method called on the left-hand side
670 * of an assignment operator. The native should store the object in which
671 * to set a property in *rval, and return the property's id expressed as a
672 * jsval by calling JS_SetCallReturnValue2(cx, idval).
675 JSPackedBool rval2set
;
679 * True if generating an error, to prevent runaway recursion.
680 * NB: generatingError packs with rval2set, #if JS_HAS_LVALUE_RETURN;
681 * with insideGCMarkCallback and with throwing below.
683 JSPackedBool generatingError
;
685 /* Flag to indicate that we run inside gcCallback(cx, JSGC_MARK_END). */
686 JSPackedBool insideGCMarkCallback
;
688 /* Exception state -- the exception member is a GC root by definition. */
689 JSPackedBool throwing
; /* is there a pending exception? */
690 jsval exception
; /* most-recently-thrown exception */
692 /* Limit pointer for checking native stack consumption during recursion. */
695 /* Quota on the size of arenas used to compile and execute scripts. */
696 size_t scriptStackQuota
;
698 /* Data shared by threads in an address space. */
701 /* Stack arena pool and frame pointer register. */
702 JSArenaPool stackPool
;
705 /* Temporary arena pool used while compiling and decompiling. */
706 JSArenaPool tempPool
;
708 /* Top-level object and pointer to top stack frame's scope chain. */
709 JSObject
*globalObject
;
711 /* Storage to root recently allocated GC things and script result. */
712 JSWeakRoots weakRoots
;
714 /* Regular expression class statics (XXX not shared globally). */
715 JSRegExpStatics regExpStatics
;
717 /* State for object and array toSource conversion. */
718 JSSharpObjectMap sharpObjectMap
;
720 /* Argument formatter support for JS_{Convert,Push}Arguments{,VA}. */
721 JSArgumentFormatMap
*argumentFormatMap
;
723 /* Last message string and trace file for debugging. */
729 /* Per-context optional user callbacks. */
730 JSBranchCallback branchCallback
;
731 JSErrorReporter errorReporter
;
733 /* Interpreter activation count. */
736 /* Client opaque pointer */
739 /* GC and thread-safe state. */
740 JSStackFrame
*dormantFrameChain
; /* dormant stack frame to scan */
743 jsrefcount requestDepth
;
744 JSScope
*scopeToShare
; /* weak reference, see jslock.c */
745 JSScope
*lockedSealedScope
; /* weak ref, for low-cost sealed
747 JSCList threadLinks
; /* JSThread contextList linkage */
749 #define CX_FROM_THREAD_LINKS(tl) \
750 ((JSContext *)((char *)(tl) - offsetof(JSContext, threadLinks)))
753 /* PDL of stack headers describing stack slots not rooted by argv, etc. */
754 JSStackHeader
*stackHeaders
;
756 /* Optional stack of heap-allocated scoped local GC roots. */
757 JSLocalRootStack
*localRootStack
;
759 /* Stack of thread-stack-allocated temporary GC roots. */
760 JSTempValueRooter
*tempValueRooters
;
762 /* Debug hooks associated with the current context. */
763 JSDebugHooks
*debugHooks
;
767 # define JS_THREAD_ID(cx) ((cx)->thread ? (cx)->thread->id : 0)
771 /* FIXME(bug 332648): Move this into a public header. */
772 class JSAutoTempValueRooter
775 JSAutoTempValueRooter(JSContext
*cx
, size_t len
, jsval
*vec
)
777 JS_PUSH_TEMP_ROOT(mContext
, len
, vec
, &mTvr
);
779 JSAutoTempValueRooter(JSContext
*cx
, jsval v
)
781 JS_PUSH_SINGLE_TEMP_ROOT(mContext
, v
, &mTvr
);
784 ~JSAutoTempValueRooter() {
785 JS_POP_TEMP_ROOT(mContext
, &mTvr
);
789 static void *operator new(size_t);
790 static void operator delete(void *, size_t);
793 JSTempValueRooter mTvr
;
798 * Slightly more readable macros for testing per-context option settings (also
799 * to hide bitset implementation detail).
801 * JSOPTION_XML must be handled specially in order to propagate from compile-
802 * to run-time (from cx->options to script->version/cx->version). To do that,
803 * we copy JSOPTION_XML from cx->options into cx->version as JSVERSION_HAS_XML
804 * whenever options are set, and preserve this XML flag across version number
805 * changes done via the JS_SetVersion API.
807 * But when executing a script or scripted function, the interpreter changes
808 * cx->version, including the XML flag, to script->version. Thus JSOPTION_XML
809 * is a compile-time option that causes a run-time version change during each
810 * activation of the compiled script. That version change has the effect of
811 * changing JS_HAS_XML_OPTION, so that any compiling done via eval enables XML
812 * support. If an XML-enabled script or function calls a non-XML function,
813 * the flag bit will be cleared during the callee's activation.
815 * Note that JS_SetVersion API calls never pass JSVERSION_HAS_XML or'd into
816 * that API's version parameter.
818 * Note also that script->version must contain this XML option flag in order
819 * for XDR'ed scripts to serialize and deserialize with that option preserved
820 * for detection at run-time. We can't copy other compile-time options into
821 * script->version because that would break backward compatibility (certain
822 * other options, e.g. JSOPTION_VAROBJFIX, are analogous to JSOPTION_XML).
824 #define JS_HAS_OPTION(cx,option) (((cx)->options & (option)) != 0)
825 #define JS_HAS_STRICT_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_STRICT)
826 #define JS_HAS_WERROR_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_WERROR)
827 #define JS_HAS_COMPILE_N_GO_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_COMPILE_N_GO)
828 #define JS_HAS_ATLINE_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_ATLINE)
830 #define JSVERSION_MASK 0x0FFF /* see JSVersion in jspubtd.h */
831 #define JSVERSION_HAS_XML 0x1000 /* flag induced by XML option */
833 #define JSVERSION_NUMBER(cx) ((JSVersion)((cx)->version & \
835 #define JS_HAS_XML_OPTION(cx) ((cx)->version & JSVERSION_HAS_XML || \
836 JSVERSION_NUMBER(cx) >= JSVERSION_1_6)
838 #define JS_HAS_NATIVE_BRANCH_CALLBACK_OPTION(cx) \
839 JS_HAS_OPTION(cx, JSOPTION_NATIVE_BRANCH_CALLBACK)
842 * Initialize a library-wide thread private data index, and remember that it
843 * has already been done, so that it happens only once ever. Returns true on
847 js_InitThreadPrivateIndex(void (JS_DLL_CALLBACK
*ptr
)(void *));
850 * Common subroutine of JS_SetVersion and js_SetVersion, to update per-context
851 * data that depends on version.
854 js_OnVersionChange(JSContext
*cx
);
857 * Unlike the JS_SetVersion API, this function stores JSVERSION_HAS_XML and
858 * any future non-version-number flags induced by compiler options.
861 js_SetVersion(JSContext
*cx
, JSVersion version
);
864 * Create and destroy functions for JSContext, which is manually allocated
865 * and exclusively owned.
868 js_NewContext(JSRuntime
*rt
, size_t stackChunkSize
);
871 js_DestroyContext(JSContext
*cx
, JSDestroyContextMode mode
);
874 * Return true if cx points to a context in rt->contextList, else return false.
875 * NB: the caller (see jslock.c:ClaimScope) must hold rt->gcLock.
878 js_ValidContextPointer(JSRuntime
*rt
, JSContext
*cx
);
881 * If unlocked, acquire and release rt->gcLock around *iterp update; otherwise
882 * the caller must be holding rt->gcLock.
885 js_ContextIterator(JSRuntime
*rt
, JSBool unlocked
, JSContext
**iterp
);
888 * JSClass.resolve and watchpoint recursion damping machinery.
891 js_StartResolving(JSContext
*cx
, JSResolvingKey
*key
, uint32 flag
,
892 JSResolvingEntry
**entryp
);
895 js_StopResolving(JSContext
*cx
, JSResolvingKey
*key
, uint32 flag
,
896 JSResolvingEntry
*entry
, uint32 generation
);
899 * Local root set management.
901 * NB: the jsval parameters below may be properly tagged jsvals, or GC-thing
902 * pointers cast to (jsval). This relies on JSObject's tag being zero, but
903 * on the up side it lets us push int-jsval-encoded scopeMark values on the
907 js_EnterLocalRootScope(JSContext
*cx
);
909 #define js_LeaveLocalRootScope(cx) \
910 js_LeaveLocalRootScopeWithResult(cx, JSVAL_NULL)
913 js_LeaveLocalRootScopeWithResult(JSContext
*cx
, jsval rval
);
916 js_ForgetLocalRoot(JSContext
*cx
, jsval v
);
919 js_PushLocalRoot(JSContext
*cx
, JSLocalRootStack
*lrs
, jsval v
);
922 js_TraceLocalRoots(JSTracer
*trc
, JSLocalRootStack
*lrs
);
925 * Report an exception, which is currently realized as a printf-style format
926 * string and its arguments.
928 typedef enum JSErrNum
{
929 #define MSG_DEF(name, number, count, exception, format) \
936 extern const JSErrorFormatString
*
937 js_GetErrorMessage(void *userRef
, const char *locale
, const uintN errorNumber
);
941 js_ReportErrorVA(JSContext
*cx
, uintN flags
, const char *format
, va_list ap
);
944 js_ReportErrorNumberVA(JSContext
*cx
, uintN flags
, JSErrorCallback callback
,
945 void *userRef
, const uintN errorNumber
,
946 JSBool charArgs
, va_list ap
);
949 js_ExpandErrorArguments(JSContext
*cx
, JSErrorCallback callback
,
950 void *userRef
, const uintN errorNumber
,
951 char **message
, JSErrorReport
*reportp
,
952 JSBool
*warningp
, JSBool charArgs
, va_list ap
);
956 js_ReportOutOfMemory(JSContext
*cx
);
959 * Report an exception using a previously composed JSErrorReport.
960 * XXXbe remove from "friend" API
962 extern JS_FRIEND_API(void)
963 js_ReportErrorAgain(JSContext
*cx
, const char *message
, JSErrorReport
*report
);
966 js_ReportIsNotDefined(JSContext
*cx
, const char *name
);
969 * Report error using js_DecompileValueGenerator(cx, spindex, v, fallback) as
970 * the first argument for the error message. If the error message has less
971 * then 3 arguments, use null for arg1 or arg2.
974 js_ReportValueErrorFlags(JSContext
*cx
, uintN flags
, const uintN errorNumber
,
975 intN spindex
, jsval v
, JSString
*fallback
,
976 const char *arg1
, const char *arg2
);
978 #define js_ReportValueError(cx,errorNumber,spindex,v,fallback) \
979 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
980 spindex, v, fallback, NULL, NULL))
982 #define js_ReportValueError2(cx,errorNumber,spindex,v,fallback,arg1) \
983 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
984 spindex, v, fallback, arg1, NULL))
986 #define js_ReportValueError3(cx,errorNumber,spindex,v,fallback,arg1,arg2) \
987 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
988 spindex, v, fallback, arg1, arg2))
990 extern JSErrorFormatString js_ErrorFormatString
[JSErr_Limit
];
993 * See JS_SetThreadStackLimit in jsapi.c, where we check that the stack grows
994 * in the expected direction. On Unix-y systems, JS_STACK_GROWTH_DIRECTION is
995 * computed on the build host by jscpucfg.c and written into jsautocfg.h. The
996 * macro is hardcoded in jscpucfg.h on Windows and Mac systems (for historical
997 * reasons pre-dating autoconf usage).
999 #if JS_STACK_GROWTH_DIRECTION > 0
1000 # define JS_CHECK_STACK_SIZE(cx, lval) ((jsuword)&(lval) < (cx)->stackLimit)
1002 # define JS_CHECK_STACK_SIZE(cx, lval) ((jsuword)&(lval) > (cx)->stackLimit)
1005 /* Relative operations weights. */
1007 #define JSOW_ALLOCATION 100
1008 #define JSOW_LOOKUP_PROPERTY 5
1009 #define JSOW_GET_PROPERTY 10
1010 #define JSOW_SET_PROPERTY 20
1011 #define JSOW_NEW_PROPERTY 200
1012 #define JSOW_DELETE_PROPERTY 30
1014 #define JSOW_BRANCH_CALLBACK JS_BIT(12)
1017 * The implementation of JS_COUNT_OPERATION macro below assumes that
1018 * JSOW_BRANCH_CALLBACK is a power of two to ensures that an unsigned int
1019 * overflow does not bring the counter below JSOW_BRANCH_CALLBACK limit.
1021 JS_STATIC_ASSERT((JSOW_BRANCH_CALLBACK
& (JSOW_BRANCH_CALLBACK
- 1)) == 0);
1024 * Update the operation counter according the specified weight. This macro
1025 * does not call the branch callback or any API.
1027 #define JS_COUNT_OPERATION(cx, weight) \
1028 ((void)(JS_ASSERT((weight) > 0), \
1029 JS_ASSERT((weight) <= JSOW_BRANCH_CALLBACK), \
1030 (cx)->operationCounter = (((cx)->operationCounter + (weight)) | \
1031 (~(JSOW_BRANCH_CALLBACK - 1) & \
1032 (cx)->operationCounter))))
1035 * Update the operation counter and call the branch callback when it reaches
1036 * JSOW_BRANCH_CALLBACK limit. This macro can run the full GC. Return true if
1037 * it is OK to continue and false otherwise.
1039 #define JS_CHECK_OPERATION_LIMIT(cx, weight) \
1040 (JS_COUNT_OPERATION(cx, weight), \
1041 ((cx)->operationCounter < JSOW_BRANCH_CALLBACK || \
1042 js_ResetOperationCounter(cx)))
1045 * Reset the operation counter and call branch callback assuming that the
1046 * operation limit is reached.
1049 js_ResetOperationCounter(JSContext
*cx
);
1053 #endif /* jscntxt_h___ */