Save all modification
[mozilla-1.9/m8.git] / js / src / jscntxt.h
blobedf9f87eac7be68b691c6ef4d466e1944af66caa
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sw=4 et tw=78:
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
15 * License.
17 * The Original Code is Mozilla Communicator client code, released
18 * March 31, 1998.
20 * The Initial Developer of the Original Code is
21 * Netscape Communications Corporation.
22 * Portions created by the Initial Developer are Copyright (C) 1998
23 * the Initial Developer. All Rights Reserved.
25 * Contributor(s):
27 * Alternatively, the contents of this file may be used under the terms of
28 * either of the GNU General Public License Version 2 or later (the "GPL"),
29 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30 * in which case the provisions of the GPL or the LGPL are applicable instead
31 * of those above. If you wish to allow use of your version of this file only
32 * under the terms of either the GPL or the LGPL, and not to allow others to
33 * use your version of this file under the terms of the MPL, indicate your
34 * decision by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL or the LGPL. If you do not delete
36 * the provisions above, a recipient may use your version of this file under
37 * the terms of any one of the MPL, the GPL or the LGPL.
39 * ***** END LICENSE BLOCK ***** */
41 #ifndef jscntxt_h___
42 #define jscntxt_h___
44 * JS execution context.
46 #include "jsarena.h" /* Added by JSIFY */
47 #include "jsclist.h"
48 #include "jslong.h"
49 #include "jsatom.h"
50 #include "jsconfig.h"
51 #include "jsdhash.h"
52 #include "jsgc.h"
53 #include "jsinterp.h"
54 #include "jsobj.h"
55 #include "jsprvtd.h"
56 #include "jspubtd.h"
57 #include "jsregexp.h"
58 #include "jsutil.h"
60 JS_BEGIN_EXTERN_C
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 {
67 JSScript *script;
68 JSDHashTable table;
69 #ifdef JS_GSNMETER
70 uint32 hits;
71 uint32 misses;
72 uint32 fills;
73 uint32 clears;
74 # define GSN_CACHE_METER(cache,cnt) (++(cache)->cnt)
75 #else
76 # define GSN_CACHE_METER(cache,cnt) /* nothing */
77 #endif
78 } JSGSNCache;
80 #define GSN_CACHE_CLEAR(cache) \
81 JS_BEGIN_MACRO \
82 (cache)->script = NULL; \
83 if ((cache)->table.ops) { \
84 JS_DHashTableFinish(&(cache)->table); \
85 (cache)->table.ops = NULL; \
86 } \
87 GSN_CACHE_METER(cache, clears); \
88 JS_END_MACRO
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)
94 #ifdef JS_THREADSAFE
97 * Structure uniquely representing a thread. It holds thread-private data
98 * that can be accessed without a global lock.
100 struct JSThread {
101 /* Linked list of all contexts active on this thread. */
102 JSCList contextList;
104 /* Opaque thread-id, from NSPR's PR_GetCurrentThread(). */
105 jsword id;
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.
123 JSGSNCache gsnCache;
126 #define JS_GSN_CACHE(cx) ((cx)->thread->gsnCache)
128 extern void JS_DLL_CALLBACK
129 js_ThreadDestructorCB(void *ptr);
131 extern JSBool
132 js_SetContextThread(JSContext *cx);
134 extern void
135 js_ClearContextThread(JSContext *cx);
137 extern JSThread *
138 js_GetCurrentThread(JSRuntime *rt);
140 #endif /* JS_THREADSAFE */
142 typedef enum JSDestroyContextMode {
143 JSDCM_NO_GC,
144 JSDCM_MAYBE_GC,
145 JSDCM_FORCE_GC,
146 JSDCM_NEW_FAILED
147 } JSDestroyContextMode;
149 typedef enum JSRuntimeState {
150 JSRTS_DOWN,
151 JSRTS_LAUNCHING,
152 JSRTS_UP,
153 JSRTS_LANDING
154 } JSRuntimeState;
156 typedef struct JSPropertyTreeEntry {
157 JSDHashEntryHdr hdr;
158 JSScopeProperty *child;
159 } JSPropertyTreeEntry;
162 * Forward declaration for opaque JSRuntime.nativeIteratorStates.
164 typedef struct JSNativeIteratorState JSNativeIteratorState;
166 struct JSRuntime {
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;
178 uint32 gcBytes;
179 uint32 gcLastBytes;
180 uint32 gcMaxBytes;
181 uint32 gcMaxMallocBytes;
182 uint32 gcLevel;
183 uint32 gcNumber;
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.
192 JSPackedBool gcPoke;
193 JSPackedBool gcRunning;
194 #ifdef JS_GC_ZEAL
195 uint8 gcZeal;
196 uint8 gcPadding;
197 #else
198 uint16 gcPadding;
199 #endif
201 JSGCCallback gcCallback;
202 JSGCThingCallback gcThingCallback;
203 void *gcThingCallbackClosure;
204 uint32 gcMallocBytes;
205 JSGCArena *gcUnscannedArenaStackTop;
206 #ifdef DEBUG
207 size_t gcUnscannedBagSize;
208 #endif
211 * Table for tracking iterators to ensure that we close iterator's state
212 * before finalizing the iterable object.
214 JSPtrTable gcIteratorTable;
216 #ifdef JS_GCMETER
217 JSGCStats gcStats;
218 #endif
221 * The trace operation and its data argument to trace embedding-specific
222 * GC roots.
224 JSTraceDataOp gcExtraRootsTraceOp;
225 void *gcExtraRootsData;
227 /* Random number generator state, used by jsmath.c. */
228 JSBool rngInitialized;
229 int64 rngMultiplier;
230 int64 rngAddend;
231 int64 rngMask;
232 int64 rngSeed;
233 jsdouble rngDscale;
235 /* Well-known numbers held for use by this runtime's contexts. */
236 jsdouble *jsNaN;
237 jsdouble *jsNegativeInfinity;
238 jsdouble *jsPositiveInfinity;
240 #ifdef JS_THREADSAFE
241 JSLock *deflatedStringCacheLock;
242 #endif
243 JSHashTable *deflatedStringCache;
244 #ifdef DEBUG
245 uint32 deflatedStringCacheBytes;
246 #endif
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. */
256 JSCList contextList;
258 /* Per runtime debug hooks -- see jsprvtd.h and jsdbgapi.h. */
259 JSDebugHooks globalDebugHooks;
261 /* More debugging state, see jsdbgapi.c. */
262 JSCList trapList;
263 JSCList watchPointList;
265 /* Client opaque pointer */
266 void *data;
268 #ifdef JS_THREADSAFE
269 /* These combine to interlock the GC and new requests. */
270 PRLock *gcLock;
271 PRCondVar *gcDone;
272 PRCondVar *requestDone;
273 uint32 requestCount;
274 JSThread *gcThread;
276 /* Lock and owning thread pointer for JS_LOCK_RUNTIME. */
277 PRLock *rtLock;
278 #ifdef DEBUG
279 jsword rtLockOwner;
280 #endif
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__. */
286 PRLock *setSlotLock;
287 PRCondVar *setSlotDone;
288 JSBool setSlotBusy;
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)
309 * value.
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
317 * case too.
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;
349 #ifdef JS_THREADSAFE
350 PRLock *scriptFilenameTableLock;
351 #endif
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.
381 JSGSNCache gsnCache;
383 #define JS_GSN_CACHE(cx) ((cx)->runtime->gsnCache)
384 #endif
386 /* Literal table maintained by jsatom.c functions. */
387 JSAtomState atomState;
389 #ifdef DEBUG
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;
418 double lengthSum;
419 double lengthSquaredSum;
420 double strdepLengthSum;
421 double strdepLengthSquaredSum;
422 #endif
425 #ifdef DEBUG
426 # define JS_RUNTIME_METER(rt, which) JS_ATOMIC_INCREMENT(&(rt)->which)
427 # define JS_RUNTIME_UNMETER(rt, which) JS_ATOMIC_DECREMENT(&(rt)->which)
428 #else
429 # define JS_RUNTIME_METER(rt, which) /* nothing */
430 # define JS_RUNTIME_UNMETER(rt, which) /* nothing */
431 #endif
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
440 * length order.
442 struct JSArgumentFormatMap {
443 const char *format;
444 size_t length;
445 JSArgumentFormatter formatter;
446 JSArgumentFormatMap *next;
448 #endif
450 struct JSStackHeader {
451 uintN nslots;
452 JSStackHeader *down;
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 {
464 JSObject *obj;
465 jsid id;
466 } JSResolvingKey;
468 typedef struct JSResolvingEntry {
469 JSDHashEntryHdr hdr;
470 JSResolvingKey key;
471 uint32 flags;
472 } 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 {
489 uint32 scopeMark;
490 uint32 rootCount;
491 JSLocalRootChunk *topChunk;
492 JSLocalRootChunk firstChunk;
493 } JSLocalRootStack;
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
505 * following table:
507 * count description
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) \
545 JS_BEGIN_MACRO \
546 JS_ASSERT((cx)->tempValueRooters != (tvr)); \
547 (tvr)->down = (cx)->tempValueRooters; \
548 (cx)->tempValueRooters = (tvr); \
549 JS_END_MACRO
551 #define JS_PUSH_SINGLE_TEMP_ROOT(cx,val,tvr) \
552 JS_BEGIN_MACRO \
553 (tvr)->count = JSTVU_SINGLE; \
554 (tvr)->u.value = val; \
555 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
556 JS_END_MACRO
558 #define JS_PUSH_TEMP_ROOT(cx,cnt,arr,tvr) \
559 JS_BEGIN_MACRO \
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); \
564 JS_END_MACRO
566 #define JS_PUSH_TEMP_ROOT_TRACE(cx,trace_,tvr) \
567 JS_BEGIN_MACRO \
568 (tvr)->count = JSTVU_TRACE; \
569 (tvr)->u.trace = (trace_); \
570 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
571 JS_END_MACRO
573 #define JS_PUSH_TEMP_ROOT_OBJECT(cx,obj,tvr) \
574 JS_BEGIN_MACRO \
575 (tvr)->count = JSTVU_SINGLE; \
576 (tvr)->u.object = (obj); \
577 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
578 JS_END_MACRO
580 #define JS_PUSH_TEMP_ROOT_STRING(cx,str,tvr) \
581 JS_BEGIN_MACRO \
582 (tvr)->count = JSTVU_SINGLE; \
583 (tvr)->u.string = (str); \
584 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
585 JS_END_MACRO
587 #define JS_PUSH_TEMP_ROOT_GCTHING(cx,thing,tvr) \
588 JS_BEGIN_MACRO \
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); \
593 JS_END_MACRO
595 #define JS_POP_TEMP_ROOT(cx,tvr) \
596 JS_BEGIN_MACRO \
597 JS_ASSERT((cx)->tempValueRooters == (tvr)); \
598 (cx)->tempValueRooters = (tvr)->down; \
599 JS_END_MACRO
601 #define JS_TEMP_ROOT_EVAL(cx,cnt,val,expr) \
602 JS_BEGIN_MACRO \
603 JSTempValueRooter tvr; \
604 JS_PUSH_TEMP_ROOT(cx, cnt, val, &tvr); \
605 (expr); \
606 JS_POP_TEMP_ROOT(cx, &tvr); \
607 JS_END_MACRO
609 #define JS_PUSH_TEMP_ROOT_SPROP(cx,sprop_,tvr) \
610 JS_BEGIN_MACRO \
611 (tvr)->count = JSTVU_SPROP; \
612 (tvr)->u.sprop = (sprop_); \
613 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
614 JS_END_MACRO
616 #define JS_PUSH_TEMP_ROOT_WEAK_COPY(cx,weakRoots_,tvr) \
617 JS_BEGIN_MACRO \
618 (tvr)->count = JSTVU_WEAK_ROOTS; \
619 (tvr)->u.weakRoots = (weakRoots_); \
620 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
621 JS_END_MACRO
623 #define JS_PUSH_TEMP_ROOT_PARSE_CONTEXT(cx,pc,tvr) \
624 JS_BEGIN_MACRO \
625 (tvr)->count = JSTVU_PARSE_CONTEXT; \
626 (tvr)->u.parseContext = (pc); \
627 JS_PUSH_TEMP_ROOT_COMMON(cx, tvr); \
628 JS_END_MACRO
630 struct JSContext {
631 /* JSRuntime contextList linkage. */
632 JSCList links;
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;
645 uint8 padding;
646 #else
647 uint16 padding;
648 #endif
650 /* Runtime version control identifier. */
651 uint16 version;
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).
674 jsval rval2;
675 JSPackedBool rval2set;
676 #endif
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. */
693 jsuword stackLimit;
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. */
699 JSRuntime *runtime;
701 /* Stack arena pool and frame pointer register. */
702 JSArenaPool stackPool;
703 JSStackFrame *fp;
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. */
724 char *lastMessage;
725 #ifdef DEBUG
726 void *tracefp;
727 #endif
729 /* Per-context optional user callbacks. */
730 JSBranchCallback branchCallback;
731 JSErrorReporter errorReporter;
733 /* Interpreter activation count. */
734 uintN interpLevel;
736 /* Client opaque pointer */
737 void *data;
739 /* GC and thread-safe state. */
740 JSStackFrame *dormantFrameChain; /* dormant stack frame to scan */
741 #ifdef JS_THREADSAFE
742 JSThread *thread;
743 jsrefcount requestDepth;
744 JSScope *scopeToShare; /* weak reference, see jslock.c */
745 JSScope *lockedSealedScope; /* weak ref, for low-cost sealed
746 scope locking */
747 JSCList threadLinks; /* JSThread contextList linkage */
749 #define CX_FROM_THREAD_LINKS(tl) \
750 ((JSContext *)((char *)(tl) - offsetof(JSContext, threadLinks)))
751 #endif
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;
766 #ifdef JS_THREADSAFE
767 # define JS_THREAD_ID(cx) ((cx)->thread ? (cx)->thread->id : 0)
768 #endif
770 #ifdef __cplusplus
771 /* FIXME(bug 332648): Move this into a public header. */
772 class JSAutoTempValueRooter
774 public:
775 JSAutoTempValueRooter(JSContext *cx, size_t len, jsval *vec)
776 : mContext(cx) {
777 JS_PUSH_TEMP_ROOT(mContext, len, vec, &mTvr);
779 JSAutoTempValueRooter(JSContext *cx, jsval v)
780 : mContext(cx) {
781 JS_PUSH_SINGLE_TEMP_ROOT(mContext, v, &mTvr);
784 ~JSAutoTempValueRooter() {
785 JS_POP_TEMP_ROOT(mContext, &mTvr);
788 private:
789 static void *operator new(size_t);
790 static void operator delete(void *, size_t);
792 JSContext *mContext;
793 JSTempValueRooter mTvr;
795 #endif
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 & \
834 JSVERSION_MASK))
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
844 * success.
846 extern JSBool
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.
853 extern void
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.
860 extern void
861 js_SetVersion(JSContext *cx, JSVersion version);
864 * Create and destroy functions for JSContext, which is manually allocated
865 * and exclusively owned.
867 extern JSContext *
868 js_NewContext(JSRuntime *rt, size_t stackChunkSize);
870 extern void
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.
877 extern JSBool
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.
884 extern JSContext *
885 js_ContextIterator(JSRuntime *rt, JSBool unlocked, JSContext **iterp);
888 * JSClass.resolve and watchpoint recursion damping machinery.
890 extern JSBool
891 js_StartResolving(JSContext *cx, JSResolvingKey *key, uint32 flag,
892 JSResolvingEntry **entryp);
894 extern void
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
904 * local root stack.
906 extern JSBool
907 js_EnterLocalRootScope(JSContext *cx);
909 #define js_LeaveLocalRootScope(cx) \
910 js_LeaveLocalRootScopeWithResult(cx, JSVAL_NULL)
912 extern void
913 js_LeaveLocalRootScopeWithResult(JSContext *cx, jsval rval);
915 extern void
916 js_ForgetLocalRoot(JSContext *cx, jsval v);
918 extern int
919 js_PushLocalRoot(JSContext *cx, JSLocalRootStack *lrs, jsval v);
921 extern void
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) \
930 name = number,
931 #include "js.msg"
932 #undef MSG_DEF
933 JSErr_Limit
934 } JSErrNum;
936 extern const JSErrorFormatString *
937 js_GetErrorMessage(void *userRef, const char *locale, const uintN errorNumber);
939 #ifdef va_start
940 extern JSBool
941 js_ReportErrorVA(JSContext *cx, uintN flags, const char *format, va_list ap);
943 extern JSBool
944 js_ReportErrorNumberVA(JSContext *cx, uintN flags, JSErrorCallback callback,
945 void *userRef, const uintN errorNumber,
946 JSBool charArgs, va_list ap);
948 extern JSBool
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);
953 #endif
955 extern void
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);
965 extern void
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.
973 extern JSBool
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)
1001 #else
1002 # define JS_CHECK_STACK_SIZE(cx, lval) ((jsuword)&(lval) > (cx)->stackLimit)
1003 #endif
1005 /* Relative operations weights. */
1006 #define JSOW_JUMP 1
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.
1048 extern JSBool
1049 js_ResetOperationCounter(JSContext *cx);
1051 JS_END_EXTERN_C
1053 #endif /* jscntxt_h___ */