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 */
50 #include "jsversion.h"
63 * js_GetSrcNote cache to avoid O(n^2) growth in finding a source note for a
64 * given pc in a script. We use the script->code pointer to tag the cache,
65 * instead of the script address itself, so that source notes are always found
66 * by offset from the bytecode with which they were generated.
68 typedef struct JSGSNCache
{
76 # define GSN_CACHE_METER(cache,cnt) (++(cache)->cnt)
78 # define GSN_CACHE_METER(cache,cnt) /* nothing */
82 #define GSN_CACHE_CLEAR(cache) \
84 (cache)->code = NULL; \
85 if ((cache)->table.ops) { \
86 JS_DHashTableFinish(&(cache)->table); \
87 (cache)->table.ops = NULL; \
89 GSN_CACHE_METER(cache, clears); \
92 /* These helper macros take a cx as parameter and operate on its GSN cache. */
93 #define JS_CLEAR_GSN_CACHE(cx) GSN_CACHE_CLEAR(&JS_GSN_CACHE(cx))
94 #define JS_METER_GSN_CACHE(cx,cnt) GSN_CACHE_METER(&JS_GSN_CACHE(cx), cnt)
102 extern "C++" { template<typename T
> class Queue
; }
103 typedef Queue
<uint16
> SlotList
;
108 # define CLS(T) void*
112 * Trace monitor. Every JSThread (if JS_THREADSAFE) or JSRuntime (if not
113 * JS_THREADSAFE) has an associated trace monitor that keeps track of loop
114 * frequencies for all JavaScript code loaded into that runtime.
116 typedef struct JSTraceMonitor
{
118 * Flag set when running (or recording) JIT-compiled code. This prevents
119 * both interpreter activation and last-ditch garbage collection when up
120 * against our runtime's memory limits. This flag also suppresses calls to
121 * JS_ReportOutOfMemory when failing due to runtime limits.
124 CLS(nanojit::Fragmento
) fragmento
;
125 CLS(TraceRecorder
) recorder
;
127 CLS(SlotList
) globalSlots
;
128 CLS(TypeMap
) globalTypeMap
;
129 jsval
*recoveryDoublePool
;
130 jsval
*recoveryDoublePoolPtr
;
132 /* Fragmento for the regular expression compiler. This is logically
133 * a distinct compiler but needs to be managed in exactly the same
134 * way as the real tracing Fragmento. */
135 CLS(nanojit::Fragmento
) reFragmento
;
137 /* Keep a list of recorders we need to abort on cache flush. */
138 CLS(TraceRecorder
) abortStack
;
142 # define JS_ON_TRACE(cx) (JS_TRACE_MONITOR(cx).onTrace)
143 # define JS_EXECUTING_TRACE(cx) (JS_ON_TRACE(cx) && !JS_TRACE_MONITOR(cx).recorder)
145 # define JS_ON_TRACE(cx) JS_FALSE
146 # define JS_EXECUTING_TRACE(cx) JS_FALSE
152 * Structure uniquely representing a thread. It holds thread-private data
153 * that can be accessed without a global lock.
156 /* Linked list of all contexts active on this thread. */
159 /* Opaque thread-id, from NSPR's PR_GetCurrentThread(). */
163 * Thread-local version of JSRuntime.gcMallocBytes to avoid taking
164 * locks on each JS_malloc.
166 uint32 gcMallocBytes
;
169 * Store the GSN cache in struct JSThread, not struct JSContext, both to
170 * save space and to simplify cleanup in js_GC. Any embedding (Firefox
171 * or another Gecko application) that uses many contexts per thread is
172 * unlikely to interleave js_GetSrcNote-intensive loops in the decompiler
173 * among two or more contexts running script in one thread.
177 /* Property cache for faster call/get/set invocation. */
178 JSPropertyCache propertyCache
;
180 /* Trace-tree JIT recorder/interpreter state. */
181 JSTraceMonitor traceMonitor
;
183 /* Lock-free list of scripts created by eval to garbage-collect. */
184 JSScript
*scriptsToGC
;
187 #define JS_GSN_CACHE(cx) ((cx)->thread->gsnCache)
188 #define JS_PROPERTY_CACHE(cx) ((cx)->thread->propertyCache)
189 #define JS_TRACE_MONITOR(cx) ((cx)->thread->traceMonitor)
190 #define JS_SCRIPTS_TO_GC(cx) ((cx)->thread->scriptsToGC)
193 js_ThreadDestructorCB(void *ptr
);
196 js_SetContextThread(JSContext
*cx
);
199 js_ClearContextThread(JSContext
*cx
);
202 js_GetCurrentThread(JSRuntime
*rt
);
204 #endif /* JS_THREADSAFE */
206 typedef enum JSDestroyContextMode
{
211 } JSDestroyContextMode
;
213 typedef enum JSRuntimeState
{
220 typedef struct JSPropertyTreeEntry
{
222 JSScopeProperty
*child
;
223 } JSPropertyTreeEntry
;
225 typedef struct JSSetSlotRequest JSSetSlotRequest
;
227 struct JSSetSlotRequest
{
228 JSObject
*obj
; /* object containing slot to set */
229 JSObject
*pobj
; /* new proto or parent reference */
230 uint16 slot
; /* which to set, proto or parent */
231 uint16 errnum
; /* JSMSG_NO_ERROR or error result */
232 JSSetSlotRequest
*next
; /* next request in GC worklist */
236 /* Runtime state, synchronized by the stateChange/gcLock condvar/lock. */
237 JSRuntimeState state
;
239 /* Context create/destroy callback. */
240 JSContextCallback cxCallback
;
242 /* Garbage collector state, used by jsgc.c. */
243 JSGCChunkInfo
*gcChunkList
;
244 JSGCArenaList gcArenaList
[GC_NUM_FREELISTS
];
245 JSGCDoubleArenaList gcDoubleArenaList
;
246 JSGCFreeListSet
*gcFreeListsPool
;
247 JSDHashTable gcRootsHash
;
248 JSDHashTable
*gcLocksHash
;
249 jsrefcount gcKeepAtoms
;
253 uint32 gcMaxMallocBytes
;
254 uint32 gcEmptyArenaPoolLifespan
;
257 JSTracer
*gcMarkingTracer
;
260 * NB: do not pack another flag here by claiming gcPadding unless the new
261 * flag is written only by the GC thread. Atomic updates to packed bytes
262 * are not guaranteed, so stores issued by one thread may be lost due to
263 * unsynchronized read-modify-write cycles on other threads.
266 JSPackedBool gcRunning
;
272 JSGCCallback gcCallback
;
273 uint32 gcMallocBytes
;
274 JSGCArenaInfo
*gcUntracedArenaStackTop
;
276 size_t gcTraceLaterCount
;
280 * Table for tracking iterators to ensure that we close iterator's state
281 * before finalizing the iterable object.
283 JSPtrTable gcIteratorTable
;
286 * The trace operation and its data argument to trace embedding-specific
289 JSTraceDataOp gcExtraRootsTraceOp
;
290 void *gcExtraRootsData
;
293 * Used to serialize cycle checks when setting __proto__ or __parent__ by
294 * requesting the GC handle the required cycle detection. If the GC hasn't
295 * been poked, it won't scan for garbage. This member is protected by
298 JSSetSlotRequest
*setSlotRequests
;
300 /* Random number generator state, used by jsmath.c. */
301 JSBool rngInitialized
;
308 /* Well-known numbers held for use by this runtime's contexts. */
310 jsdouble
*jsNegativeInfinity
;
311 jsdouble
*jsPositiveInfinity
;
314 JSLock
*deflatedStringCacheLock
;
316 JSHashTable
*deflatedStringCache
;
318 uint32 deflatedStringCacheBytes
;
322 * Empty and unit-length strings held for use by this runtime's contexts.
323 * The unitStrings array and its elements are created on demand.
325 JSString
*emptyString
;
326 JSString
**unitStrings
;
328 /* List of active contexts sharing this runtime; protected by gcLock. */
331 /* Per runtime debug hooks -- see jsprvtd.h and jsdbgapi.h. */
332 JSDebugHooks globalDebugHooks
;
334 /* More debugging state, see jsdbgapi.c. */
336 JSCList watchPointList
;
338 /* Client opaque pointers */
342 /* These combine to interlock the GC and new requests. */
345 PRCondVar
*requestDone
;
349 /* Lock and owning thread pointer for JS_LOCK_RUNTIME. */
355 /* Used to synchronize down/up state change; protected by gcLock. */
356 PRCondVar
*stateChange
;
359 * State for sharing single-threaded titles, once a second thread tries to
360 * lock a title. The titleSharingDone condvar is protected by rt->gcLock
361 * to minimize number of locks taken in JS_EndRequest.
363 * The titleSharingTodo linked list is likewise "global" per runtime, not
364 * one-list-per-context, to conserve space over all contexts, optimizing
365 * for the likely case that titles become shared rarely, and among a very
366 * small set of threads (contexts).
368 PRCondVar
*titleSharingDone
;
369 JSTitle
*titleSharingTodo
;
372 * Magic terminator for the rt->titleSharingTodo linked list, threaded through
373 * title->u.link. This hack allows us to test whether a title is on the list
374 * by asking whether title->u.link is non-null. We use a large, likely bogus
375 * pointer here to distinguish this value from any valid u.count (small int)
378 #define NO_TITLE_SHARING_TODO ((JSTitle *) 0xfeedbeef)
381 * Lock serializing trapList and watchPointList accesses, and count of all
382 * mutations to trapList and watchPointList made by debugger threads. To
383 * keep the code simple, we define debuggerMutations for the thread-unsafe
386 PRLock
*debuggerLock
;
387 #endif /* JS_THREADSAFE */
388 uint32 debuggerMutations
;
391 * Security callbacks set on the runtime are used by each context unless
392 * an override is set on the context.
394 JSSecurityCallbacks
*securityCallbacks
;
397 * Shared scope property tree, and arena-pool for allocating its nodes.
398 * The propertyRemovals counter is incremented for every js_ClearScope,
399 * and for each js_RemoveScopeProperty that frees a slot in an object.
400 * See js_NativeGet and js_NativeSet in jsobj.c.
402 JSDHashTable propertyTreeHash
;
403 JSScopeProperty
*propertyFreeList
;
404 JSArenaPool propertyArenaPool
;
405 int32 propertyRemovals
;
407 /* Script filename table. */
408 struct JSHashTable
*scriptFilenameTable
;
409 JSCList scriptFilenamePrefixes
;
411 PRLock
*scriptFilenameTableLock
;
414 /* Number localization, used by jsnum.c */
415 const char *thousandsSeparator
;
416 const char *decimalSeparator
;
417 const char *numGrouping
;
420 * Weak references to lazily-created, well-known XML singletons.
422 * NB: Singleton objects must be carefully disconnected from the rest of
423 * the object graph usually associated with a JSContext's global object,
424 * including the set of standard class objects. See jsxml.c for details.
426 JSObject
*anynameObject
;
427 JSObject
*functionNamespaceObject
;
430 * A helper list for the GC, so it can mark native iterator states. See
431 * js_TraceNativeEnumerators for details.
433 JSNativeEnumerator
*nativeEnumerators
;
435 #ifndef JS_THREADSAFE
437 * For thread-unsafe embeddings, the GSN cache lives in the runtime and
438 * not each context, since we expect it to be filled once when decompiling
439 * a longer script, then hit repeatedly as js_GetSrcNote is called during
440 * the decompiler activation that filled it.
444 /* Property cache for faster call/get/set invocation. */
445 JSPropertyCache propertyCache
;
447 /* Trace-tree JIT recorder/interpreter state. */
448 JSTraceMonitor traceMonitor
;
450 /* Lock-free list of scripts created by eval to garbage-collect. */
451 JSScript
*scriptsToGC
;
453 #define JS_GSN_CACHE(cx) ((cx)->runtime->gsnCache)
454 #define JS_PROPERTY_CACHE(cx) ((cx)->runtime->propertyCache)
455 #define JS_TRACE_MONITOR(cx) ((cx)->runtime->traceMonitor)
456 #define JS_SCRIPTS_TO_GC(cx) ((cx)->runtime->scriptsToGC)
460 * Object shape (property cache structural type) identifier generator.
462 * Type 0 stands for the empty scope, and must not be regenerated due to
463 * uint32 wrap-around. Since we use atomic pre-increment, the initial
464 * value for the first typed non-empty scope will be 1.
466 * The GC compresses live types, minimizing rt->shapeGen in the process.
467 * If this counter overflows into SHAPE_OVERFLOW_BIT (in jsinterp.h), the
468 * GC will disable property caches for all threads, to avoid aliasing two
469 * different types. Updated by js_GenerateShape (in jsinterp.c).
473 /* Literal table maintained by jsatom.c functions. */
474 JSAtomState atomState
;
477 * Cache of reusable JSNativeEnumerators mapped by shape identifiers (as
478 * stored in scope->shape). This cache is nulled by the GC and protected
481 #define NATIVE_ENUM_CACHE_LOG2 8
482 #define NATIVE_ENUM_CACHE_MASK JS_BITMASK(NATIVE_ENUM_CACHE_LOG2)
483 #define NATIVE_ENUM_CACHE_SIZE JS_BIT(NATIVE_ENUM_CACHE_LOG2)
485 #define NATIVE_ENUM_CACHE_HASH(shape) \
486 ((((shape) >> NATIVE_ENUM_CACHE_LOG2) ^ (shape)) & NATIVE_ENUM_CACHE_MASK)
488 jsuword nativeEnumCache
[NATIVE_ENUM_CACHE_SIZE
];
491 * Runtime-wide flag set to true when any Array prototype has an indexed
492 * property defined on it, creating a hazard for code reading or writing
493 * over a hole from a dense Array instance that is not prepared to look up
494 * the proto chain (the writing case must involve a check for a read-only
495 * element, which cannot be shadowed).
497 JSBool anyArrayProtoHasElement
;
500 * Various metering fields are defined at the end of JSRuntime. In this
501 * way there is no need to recompile all the code that refers to other
502 * fields of JSRuntime after enabling the corresponding metering macro.
504 #ifdef JS_DUMP_ENUM_CACHE_STATS
505 int32 nativeEnumProbes
;
506 int32 nativeEnumMisses
;
507 # define ENUM_CACHE_METER(name) JS_ATOMIC_INCREMENT(&cx->runtime->name)
509 # define ENUM_CACHE_METER(name) ((void) 0)
512 #ifdef JS_DUMP_LOOP_STATS
513 /* Loop statistics, to trigger trace recording and compiling. */
514 JSBasicStats loopStats
;
517 #if defined DEBUG || defined JS_DUMP_PROPTREE_STATS
518 /* Function invocation metering. */
519 jsrefcount inlineCalls
;
520 jsrefcount nativeCalls
;
521 jsrefcount nonInlineCalls
;
522 jsrefcount constructs
;
524 /* Title lock and scope property metering. */
525 jsrefcount claimAttempts
;
526 jsrefcount claimedTitles
;
527 jsrefcount deadContexts
;
528 jsrefcount deadlocksAvoided
;
529 jsrefcount liveScopes
;
530 jsrefcount sharedTitles
;
531 jsrefcount totalScopes
;
532 jsrefcount liveScopeProps
;
533 jsrefcount liveScopePropsPreSweep
;
534 jsrefcount totalScopeProps
;
535 jsrefcount livePropTreeNodes
;
536 jsrefcount duplicatePropTreeNodes
;
537 jsrefcount totalPropTreeNodes
;
538 jsrefcount propTreeKidsChunks
;
539 jsrefcount middleDeleteFixups
;
541 /* String instrumentation. */
542 jsrefcount liveStrings
;
543 jsrefcount totalStrings
;
544 jsrefcount liveDependentStrings
;
545 jsrefcount totalDependentStrings
;
546 jsrefcount badUndependStrings
;
548 double lengthSquaredSum
;
549 double strdepLengthSum
;
550 double strdepLengthSquaredSum
;
551 #endif /* DEBUG || JS_DUMP_PROPTREE_STATS */
553 #ifdef JS_SCOPE_DEPTH_METER
555 * Stats on runtime prototype chain lookups and scope chain depths, i.e.,
556 * counts of objects traversed on a chain until the wanted id is found.
558 JSBasicStats protoLookupDepthStats
;
559 JSBasicStats scopeSearchDepthStats
;
562 * Stats on compile-time host environment and lexical scope chain lengths
565 JSBasicStats hostenvScopeDepthStats
;
566 JSBasicStats lexicalScopeDepthStats
;
575 # define JS_RUNTIME_METER(rt, which) JS_ATOMIC_INCREMENT(&(rt)->which)
576 # define JS_RUNTIME_UNMETER(rt, which) JS_ATOMIC_DECREMENT(&(rt)->which)
578 # define JS_RUNTIME_METER(rt, which) /* nothing */
579 # define JS_RUNTIME_UNMETER(rt, which) /* nothing */
582 #define JS_KEEP_ATOMS(rt) JS_ATOMIC_INCREMENT(&(rt)->gcKeepAtoms);
583 #define JS_UNKEEP_ATOMS(rt) JS_ATOMIC_DECREMENT(&(rt)->gcKeepAtoms);
585 #ifdef JS_ARGUMENT_FORMATTER_DEFINED
587 * Linked list mapping format strings for JS_{Convert,Push}Arguments{,VA} to
588 * formatter functions. Elements are sorted in non-increasing format string
591 struct JSArgumentFormatMap
{
594 JSArgumentFormatter formatter
;
595 JSArgumentFormatMap
*next
;
599 struct JSStackHeader
{
604 #define JS_STACK_SEGMENT(sh) ((jsval *)(sh) + 2)
607 * Key and entry types for the JSContext.resolvingTable hash table, typedef'd
608 * here because all consumers need to see these declarations (and not just the
609 * typedef names, as would be the case for an opaque pointer-to-typedef'd-type
610 * declaration), along with cx->resolvingTable.
612 typedef struct JSResolvingKey
{
617 typedef struct JSResolvingEntry
{
623 #define JSRESFLAG_LOOKUP 0x1 /* resolving id from lookup */
624 #define JSRESFLAG_WATCH 0x2 /* resolving id from watch */
626 typedef struct JSLocalRootChunk JSLocalRootChunk
;
628 #define JSLRS_CHUNK_SHIFT 8
629 #define JSLRS_CHUNK_SIZE JS_BIT(JSLRS_CHUNK_SHIFT)
630 #define JSLRS_CHUNK_MASK JS_BITMASK(JSLRS_CHUNK_SHIFT)
632 struct JSLocalRootChunk
{
633 jsval roots
[JSLRS_CHUNK_SIZE
];
634 JSLocalRootChunk
*down
;
637 typedef struct JSLocalRootStack
{
640 JSLocalRootChunk
*topChunk
;
641 JSLocalRootChunk firstChunk
;
644 #define JSLRS_NULL_MARK ((uint32) -1)
647 * Macros to push/pop JSTempValueRooter instances to context-linked stack of
648 * temporary GC roots. If you need to protect a result value that flows out of
649 * a C function across several layers of other functions, use the
650 * js_LeaveLocalRootScopeWithResult internal API (see further below) instead.
652 * The macros also provide a simple way to get a single rooted pointer via
653 * JS_PUSH_TEMP_ROOT_<KIND>(cx, NULL, &tvr). Then &tvr.u.<kind> gives the
656 * JSTempValueRooter.count defines the type of the rooted value referenced by
657 * JSTempValueRooter.u union of type JSTempValueUnion. When count is positive
658 * or zero, u.array points to a vector of jsvals. Otherwise it must be one of
659 * the following constants:
661 #define JSTVU_SINGLE (-1) /* u.value or u.<gcthing> is single jsval
663 #define JSTVU_TRACE (-2) /* u.trace is a hook to trace a custom
665 #define JSTVU_SPROP (-3) /* u.sprop roots property tree node */
666 #define JSTVU_WEAK_ROOTS (-4) /* u.weakRoots points to saved weak roots */
667 #define JSTVU_PARSE_CONTEXT (-5) /* u.parseContext roots JSParseContext* */
668 #define JSTVU_SCRIPT (-6) /* u.script roots JSScript* */
671 * Here single JSTVU_SINGLE covers both jsval and pointers to any GC-thing via
672 * reinterpreting the thing as JSVAL_OBJECT. It works because the GC-thing is
673 * aligned on a 0 mod 8 boundary, and object has the 0 jsval tag. So any
674 * GC-thing may be tagged as if it were an object and untagged, if it's then
675 * used only as an opaque pointer until discriminated by other means than tag
676 * bits. This is how, for example, js_GetGCThingTraceKind uses its |thing|
677 * parameter -- it consults GC-thing flags stored separately from the thing to
678 * decide the kind of thing.
680 * The following checks that this type-punning is possible.
682 JS_STATIC_ASSERT(sizeof(JSTempValueUnion
) == sizeof(jsval
));
683 JS_STATIC_ASSERT(sizeof(JSTempValueUnion
) == sizeof(void *));
685 #define JS_PUSH_TEMP_ROOT_COMMON(cx,x,tvr,cnt,kind) \
687 JS_ASSERT((cx)->tempValueRooters != (tvr)); \
688 (tvr)->count = (cnt); \
689 (tvr)->u.kind = (x); \
690 (tvr)->down = (cx)->tempValueRooters; \
691 (cx)->tempValueRooters = (tvr); \
694 #define JS_POP_TEMP_ROOT(cx,tvr) \
696 JS_ASSERT((cx)->tempValueRooters == (tvr)); \
697 (cx)->tempValueRooters = (tvr)->down; \
700 #define JS_PUSH_TEMP_ROOT(cx,cnt,arr,tvr) \
702 JS_ASSERT((int)(cnt) >= 0); \
703 JS_PUSH_TEMP_ROOT_COMMON(cx, arr, tvr, (ptrdiff_t) (cnt), array); \
706 #define JS_PUSH_SINGLE_TEMP_ROOT(cx,val,tvr) \
707 JS_PUSH_TEMP_ROOT_COMMON(cx, val, tvr, JSTVU_SINGLE, value)
709 #define JS_PUSH_TEMP_ROOT_OBJECT(cx,obj,tvr) \
710 JS_PUSH_TEMP_ROOT_COMMON(cx, obj, tvr, JSTVU_SINGLE, object)
712 #define JS_PUSH_TEMP_ROOT_STRING(cx,str,tvr) \
713 JS_PUSH_TEMP_ROOT_COMMON(cx, str, tvr, JSTVU_SINGLE, string)
715 #define JS_PUSH_TEMP_ROOT_XML(cx,xml_,tvr) \
716 JS_PUSH_TEMP_ROOT_COMMON(cx, xml_, tvr, JSTVU_SINGLE, xml)
718 #define JS_PUSH_TEMP_ROOT_TRACE(cx,trace_,tvr) \
719 JS_PUSH_TEMP_ROOT_COMMON(cx, trace_, tvr, JSTVU_TRACE, trace)
721 #define JS_PUSH_TEMP_ROOT_SPROP(cx,sprop_,tvr) \
722 JS_PUSH_TEMP_ROOT_COMMON(cx, sprop_, tvr, JSTVU_SPROP, sprop)
724 #define JS_PUSH_TEMP_ROOT_WEAK_COPY(cx,weakRoots_,tvr) \
725 JS_PUSH_TEMP_ROOT_COMMON(cx, weakRoots_, tvr, JSTVU_WEAK_ROOTS, weakRoots)
727 #define JS_PUSH_TEMP_ROOT_PARSE_CONTEXT(cx,pc,tvr) \
728 JS_PUSH_TEMP_ROOT_COMMON(cx, pc, tvr, JSTVU_PARSE_CONTEXT, parseContext)
730 #define JS_PUSH_TEMP_ROOT_SCRIPT(cx,script_,tvr) \
731 JS_PUSH_TEMP_ROOT_COMMON(cx, script_, tvr, JSTVU_SCRIPT, script)
734 #define JSRESOLVE_INFER 0xffff /* infer bits from current bytecode */
737 /* JSRuntime contextList linkage. */
741 * Operation count. It is declared early in the structure as a frequently
744 int32 operationCount
;
746 #if JS_HAS_XML_SUPPORT
748 * Bit-set formed from binary exponentials of the XML_* tiny-ids defined
749 * for boolean settings in jsxml.c, plus an XSF_CACHE_VALID bit. Together
750 * these act as a cache of the boolean XML.ignore* and XML.prettyPrinting
751 * property values associated with this context's global object.
753 uint8 xmlSettingFlags
;
760 * Classic Algol "display" static link optimization.
762 #define JS_DISPLAY_SIZE 16
764 JSStackFrame
*display
[JS_DISPLAY_SIZE
];
766 /* Runtime version control identifier. */
769 /* Per-context options. */
770 uint32 options
; /* see jsapi.h for JSOPTION_* */
772 /* Locale specific callbacks for string conversion. */
773 JSLocaleCallbacks
*localeCallbacks
;
776 * cx->resolvingTable is non-null and non-empty if we are initializing
777 * standard classes lazily, or if we are otherwise recursing indirectly
778 * from js_LookupProperty through a JSClass.resolve hook. It is used to
779 * limit runaway recursion (see jsapi.c and jsobj.c).
781 JSDHashTable
*resolvingTable
;
783 #if JS_HAS_LVALUE_RETURN
785 * Secondary return value from native method called on the left-hand side
786 * of an assignment operator. The native should store the object in which
787 * to set a property in *rval, and return the property's id expressed as a
788 * jsval by calling JS_SetCallReturnValue2(cx, idval).
791 JSPackedBool rval2set
;
795 * True if generating an error, to prevent runaway recursion.
796 * NB: generatingError packs with rval2set, #if JS_HAS_LVALUE_RETURN;
797 * with insideGCMarkCallback and with throwing below.
799 JSPackedBool generatingError
;
801 /* Flag to indicate that we run inside gcCallback(cx, JSGC_MARK_END). */
802 JSPackedBool insideGCMarkCallback
;
804 /* Exception state -- the exception member is a GC root by definition. */
805 JSPackedBool throwing
; /* is there a pending exception? */
806 jsval exception
; /* most-recently-thrown exception */
808 /* Limit pointer for checking native stack consumption during recursion. */
811 /* Quota on the size of arenas used to compile and execute scripts. */
812 size_t scriptStackQuota
;
814 /* Data shared by threads in an address space. */
817 /* Stack arena pool and frame pointer register. */
818 JSArenaPool stackPool
;
823 /* Temporary arena pool used while compiling and decompiling. */
824 JSArenaPool tempPool
;
826 /* Top-level object and pointer to top stack frame's scope chain. */
827 JSObject
*globalObject
;
829 /* Storage to root recently allocated GC things and script result. */
830 JSWeakRoots weakRoots
;
832 /* Regular expression class statics (XXX not shared globally). */
833 JSRegExpStatics regExpStatics
;
835 /* State for object and array toSource conversion. */
836 JSSharpObjectMap sharpObjectMap
;
838 /* Argument formatter support for JS_{Convert,Push}Arguments{,VA}. */
839 JSArgumentFormatMap
*argumentFormatMap
;
841 /* Last message string and trace file for debugging. */
847 /* Per-context optional error reporter. */
848 JSErrorReporter errorReporter
;
851 * Flag indicating that the operation callback is set. When the flag is 0
852 * but operationCallback is not null, operationCallback stores the branch
855 uint32 operationCallbackIsSet
: 1;
856 uint32 operationLimit
: 31;
857 JSOperationCallback operationCallback
;
859 /* Interpreter activation count. */
862 /* Client opaque pointers. */
866 /* GC and thread-safe state. */
867 JSStackFrame
*dormantFrameChain
; /* dormant stack frame to scan */
870 jsrefcount requestDepth
;
871 /* Same as requestDepth but ignoring JS_SuspendRequest/JS_ResumeRequest */
872 jsrefcount outstandingRequests
;
873 JSTitle
*titleToShare
; /* weak reference, see jslock.c */
874 JSTitle
*lockedSealedTitle
; /* weak ref, for low-cost sealed
876 JSCList threadLinks
; /* JSThread contextList linkage */
878 #define CX_FROM_THREAD_LINKS(tl) \
879 ((JSContext *)((char *)(tl) - offsetof(JSContext, threadLinks)))
882 /* PDL of stack headers describing stack slots not rooted by argv, etc. */
883 JSStackHeader
*stackHeaders
;
885 /* Optional stack of heap-allocated scoped local GC roots. */
886 JSLocalRootStack
*localRootStack
;
888 /* Stack of thread-stack-allocated temporary GC roots. */
889 JSTempValueRooter
*tempValueRooters
;
892 JSGCFreeListSet
*gcLocalFreeLists
;
895 /* List of pre-allocated doubles. */
896 JSGCDoubleCell
*doubleFreeList
;
898 /* Debug hooks associated with the current context. */
899 JSDebugHooks
*debugHooks
;
901 /* Security callbacks that override any defined on the runtime. */
902 JSSecurityCallbacks
*securityCallbacks
;
904 /* Pinned regexp pool used for regular expressions. */
905 JSArenaPool regexpPool
;
907 /* Stored here to avoid passing it around as a parameter. */
912 # define JS_THREAD_ID(cx) ((cx)->thread ? (cx)->thread->id : 0)
916 /* FIXME(bug 332648): Move this into a public header. */
917 class JSAutoTempValueRooter
920 JSAutoTempValueRooter(JSContext
*cx
, size_t len
, jsval
*vec
)
922 JS_PUSH_TEMP_ROOT(mContext
, len
, vec
, &mTvr
);
924 JSAutoTempValueRooter(JSContext
*cx
, jsval v
)
926 JS_PUSH_SINGLE_TEMP_ROOT(mContext
, v
, &mTvr
);
929 ~JSAutoTempValueRooter() {
930 JS_POP_TEMP_ROOT(mContext
, &mTvr
);
938 static void *operator new(size_t);
939 static void operator delete(void *, size_t);
942 JSTempValueRooter mTvr
;
945 class JSAutoResolveFlags
948 JSAutoResolveFlags(JSContext
*cx
, uintN flags
)
949 : mContext(cx
), mSaved(cx
->resolveFlags
) {
950 cx
->resolveFlags
= flags
;
953 ~JSAutoResolveFlags() { mContext
->resolveFlags
= mSaved
; }
962 * Slightly more readable macros for testing per-context option settings (also
963 * to hide bitset implementation detail).
965 * JSOPTION_XML must be handled specially in order to propagate from compile-
966 * to run-time (from cx->options to script->version/cx->version). To do that,
967 * we copy JSOPTION_XML from cx->options into cx->version as JSVERSION_HAS_XML
968 * whenever options are set, and preserve this XML flag across version number
969 * changes done via the JS_SetVersion API.
971 * But when executing a script or scripted function, the interpreter changes
972 * cx->version, including the XML flag, to script->version. Thus JSOPTION_XML
973 * is a compile-time option that causes a run-time version change during each
974 * activation of the compiled script. That version change has the effect of
975 * changing JS_HAS_XML_OPTION, so that any compiling done via eval enables XML
976 * support. If an XML-enabled script or function calls a non-XML function,
977 * the flag bit will be cleared during the callee's activation.
979 * Note that JS_SetVersion API calls never pass JSVERSION_HAS_XML or'd into
980 * that API's version parameter.
982 * Note also that script->version must contain this XML option flag in order
983 * for XDR'ed scripts to serialize and deserialize with that option preserved
984 * for detection at run-time. We can't copy other compile-time options into
985 * script->version because that would break backward compatibility (certain
986 * other options, e.g. JSOPTION_VAROBJFIX, are analogous to JSOPTION_XML).
988 #define JS_HAS_OPTION(cx,option) (((cx)->options & (option)) != 0)
989 #define JS_HAS_STRICT_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_STRICT)
990 #define JS_HAS_WERROR_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_WERROR)
991 #define JS_HAS_COMPILE_N_GO_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_COMPILE_N_GO)
992 #define JS_HAS_ATLINE_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_ATLINE)
994 #define JSVERSION_MASK 0x0FFF /* see JSVersion in jspubtd.h */
995 #define JSVERSION_HAS_XML 0x1000 /* flag induced by XML option */
997 #define JSVERSION_NUMBER(cx) ((JSVersion)((cx)->version & \
999 #define JS_HAS_XML_OPTION(cx) ((cx)->version & JSVERSION_HAS_XML || \
1000 JSVERSION_NUMBER(cx) >= JSVERSION_1_6)
1003 * Initialize a library-wide thread private data index, and remember that it
1004 * has already been done, so that it happens only once ever. Returns true on
1008 js_InitThreadPrivateIndex(void (*ptr
)(void *));
1011 * Clean up thread-private data on the current thread. NSPR automatically
1012 * cleans up thread-private data for every thread except the main thread
1013 * (see bug 383977) on shutdown. Thus, this function should be called for
1014 * exactly those threads that survive JS_ShutDown, including the main thread.
1017 js_CleanupThreadPrivateData();
1020 * Common subroutine of JS_SetVersion and js_SetVersion, to update per-context
1021 * data that depends on version.
1024 js_OnVersionChange(JSContext
*cx
);
1027 * Unlike the JS_SetVersion API, this function stores JSVERSION_HAS_XML and
1028 * any future non-version-number flags induced by compiler options.
1031 js_SetVersion(JSContext
*cx
, JSVersion version
);
1034 * Create and destroy functions for JSContext, which is manually allocated
1035 * and exclusively owned.
1038 js_NewContext(JSRuntime
*rt
, size_t stackChunkSize
);
1041 js_DestroyContext(JSContext
*cx
, JSDestroyContextMode mode
);
1044 * Return true if cx points to a context in rt->contextList, else return false.
1045 * NB: the caller (see jslock.c:ClaimTitle) must hold rt->gcLock.
1048 js_ValidContextPointer(JSRuntime
*rt
, JSContext
*cx
);
1051 * If unlocked, acquire and release rt->gcLock around *iterp update; otherwise
1052 * the caller must be holding rt->gcLock.
1055 js_ContextIterator(JSRuntime
*rt
, JSBool unlocked
, JSContext
**iterp
);
1058 * JSClass.resolve and watchpoint recursion damping machinery.
1061 js_StartResolving(JSContext
*cx
, JSResolvingKey
*key
, uint32 flag
,
1062 JSResolvingEntry
**entryp
);
1065 js_StopResolving(JSContext
*cx
, JSResolvingKey
*key
, uint32 flag
,
1066 JSResolvingEntry
*entry
, uint32 generation
);
1069 * Local root set management.
1071 * NB: the jsval parameters below may be properly tagged jsvals, or GC-thing
1072 * pointers cast to (jsval). This relies on JSObject's tag being zero, but
1073 * on the up side it lets us push int-jsval-encoded scopeMark values on the
1077 js_EnterLocalRootScope(JSContext
*cx
);
1079 #define js_LeaveLocalRootScope(cx) \
1080 js_LeaveLocalRootScopeWithResult(cx, JSVAL_NULL)
1083 js_LeaveLocalRootScopeWithResult(JSContext
*cx
, jsval rval
);
1086 js_ForgetLocalRoot(JSContext
*cx
, jsval v
);
1089 js_PushLocalRoot(JSContext
*cx
, JSLocalRootStack
*lrs
, jsval v
);
1092 js_TraceLocalRoots(JSTracer
*trc
, JSLocalRootStack
*lrs
);
1095 * Report an exception, which is currently realized as a printf-style format
1096 * string and its arguments.
1098 typedef enum JSErrNum
{
1099 #define MSG_DEF(name, number, count, exception, format) \
1106 extern JS_FRIEND_API(const JSErrorFormatString
*)
1107 js_GetErrorMessage(void *userRef
, const char *locale
, const uintN errorNumber
);
1111 js_ReportErrorVA(JSContext
*cx
, uintN flags
, const char *format
, va_list ap
);
1114 js_ReportErrorNumberVA(JSContext
*cx
, uintN flags
, JSErrorCallback callback
,
1115 void *userRef
, const uintN errorNumber
,
1116 JSBool charArgs
, va_list ap
);
1119 js_ExpandErrorArguments(JSContext
*cx
, JSErrorCallback callback
,
1120 void *userRef
, const uintN errorNumber
,
1121 char **message
, JSErrorReport
*reportp
,
1122 JSBool
*warningp
, JSBool charArgs
, va_list ap
);
1126 js_ReportOutOfMemory(JSContext
*cx
);
1129 * Report that cx->scriptStackQuota is exhausted.
1132 js_ReportOutOfScriptQuota(JSContext
*cx
);
1135 js_ReportOverRecursed(JSContext
*cx
);
1138 js_ReportAllocationOverflow(JSContext
*cx
);
1140 #define JS_CHECK_RECURSION(cx, onerror) \
1144 if (!JS_CHECK_STACK_SIZE(cx, stackDummy_)) { \
1145 js_ReportOverRecursed(cx); \
1151 * Report an exception using a previously composed JSErrorReport.
1152 * XXXbe remove from "friend" API
1154 extern JS_FRIEND_API(void)
1155 js_ReportErrorAgain(JSContext
*cx
, const char *message
, JSErrorReport
*report
);
1158 js_ReportIsNotDefined(JSContext
*cx
, const char *name
);
1161 * Report an attempt to access the property of a null or undefined value (v).
1164 js_ReportIsNullOrUndefined(JSContext
*cx
, intN spindex
, jsval v
,
1165 JSString
*fallback
);
1168 js_ReportMissingArg(JSContext
*cx
, jsval
*vp
, uintN arg
);
1171 * Report error using js_DecompileValueGenerator(cx, spindex, v, fallback) as
1172 * the first argument for the error message. If the error message has less
1173 * then 3 arguments, use null for arg1 or arg2.
1176 js_ReportValueErrorFlags(JSContext
*cx
, uintN flags
, const uintN errorNumber
,
1177 intN spindex
, jsval v
, JSString
*fallback
,
1178 const char *arg1
, const char *arg2
);
1180 #define js_ReportValueError(cx,errorNumber,spindex,v,fallback) \
1181 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
1182 spindex, v, fallback, NULL, NULL))
1184 #define js_ReportValueError2(cx,errorNumber,spindex,v,fallback,arg1) \
1185 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
1186 spindex, v, fallback, arg1, NULL))
1188 #define js_ReportValueError3(cx,errorNumber,spindex,v,fallback,arg1,arg2) \
1189 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
1190 spindex, v, fallback, arg1, arg2))
1192 extern JSErrorFormatString js_ErrorFormatString
[JSErr_Limit
];
1195 * See JS_SetThreadStackLimit in jsapi.c, where we check that the stack grows
1196 * in the expected direction. On Unix-y systems, JS_STACK_GROWTH_DIRECTION is
1197 * computed on the build host by jscpucfg.c and written into jsautocfg.h. The
1198 * macro is hardcoded in jscpucfg.h on Windows and Mac systems (for historical
1199 * reasons pre-dating autoconf usage).
1201 #if JS_STACK_GROWTH_DIRECTION > 0
1202 # define JS_CHECK_STACK_SIZE(cx, lval) ((jsuword)&(lval) < (cx)->stackLimit)
1204 # define JS_CHECK_STACK_SIZE(cx, lval) ((jsuword)&(lval) > (cx)->stackLimit)
1208 * Update the operation counter according to the given weight and call the
1209 * operation callback when we reach the operation limit. To make this
1210 * frequently executed macro faster we decrease the counter from
1211 * JSContext.operationLimit and compare against zero to check the limit.
1213 * This macro can run the full GC. Return true if it is OK to continue and
1216 #define JS_CHECK_OPERATION_LIMIT(cx, weight) \
1217 (JS_CHECK_OPERATION_WEIGHT(weight), \
1218 (((cx)->operationCount -= (weight)) > 0 || js_ResetOperationCount(cx)))
1221 * A version of JS_CHECK_OPERATION_LIMIT that just updates the operation count
1222 * without calling the operation callback or any other API. This macro resets
1223 * the count to 0 when it becomes negative to prevent a wrap-around when the
1224 * macro is called repeatably.
1226 #define JS_COUNT_OPERATION(cx, weight) \
1227 ((void)(JS_CHECK_OPERATION_WEIGHT(weight), \
1228 (cx)->operationCount = ((cx)->operationCount > 0) \
1229 ? (cx)->operationCount - (weight) \
1233 * The implementation of the above macros assumes that subtracting weights
1234 * twice from a positive number does not wrap-around INT32_MIN.
1236 #define JS_CHECK_OPERATION_WEIGHT(weight) \
1237 (JS_ASSERT((uint32) (weight) > 0), \
1238 JS_ASSERT((uint32) (weight) < JS_BIT(30)))
1240 /* Relative operations weights. */
1242 #define JSOW_ALLOCATION 100
1243 #define JSOW_LOOKUP_PROPERTY 5
1244 #define JSOW_GET_PROPERTY 10
1245 #define JSOW_SET_PROPERTY 20
1246 #define JSOW_NEW_PROPERTY 200
1247 #define JSOW_DELETE_PROPERTY 30
1248 #define JSOW_ENTER_SHARP JS_OPERATION_WEIGHT_BASE
1249 #define JSOW_SCRIPT_JUMP JS_OPERATION_WEIGHT_BASE
1252 * Reset the operation count and call the operation callback assuming that the
1253 * operation limit is reached.
1256 js_ResetOperationCount(JSContext
*cx
);
1259 * Get the current cx->fp, first lazily instantiating stack frames if needed.
1260 * (Do not access cx->fp directly except in JS_REQUIRES_STACK code.)
1262 * Defined in jstracer.cpp if JS_TRACER is defined.
1264 extern JS_FORCES_STACK JSStackFrame
*
1265 js_GetTopStackFrame(JSContext
*cx
);
1267 extern JSStackFrame
*
1268 js_GetScriptedCaller(JSContext
*cx
, JSStackFrame
*fp
);
1272 #endif /* jscntxt_h___ */