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"
64 * js_GetSrcNote cache to avoid O(n^2) growth in finding a source note for a
65 * given pc in a script. We use the script->code pointer to tag the cache,
66 * instead of the script address itself, so that source notes are always found
67 * by offset from the bytecode with which they were generated.
69 typedef struct JSGSNCache
{
77 # define GSN_CACHE_METER(cache,cnt) (++(cache)->cnt)
79 # define GSN_CACHE_METER(cache,cnt) /* nothing */
83 #define js_FinishGSNCache(cache) js_PurgeGSNCache(cache)
86 js_PurgeGSNCache(JSGSNCache
*cache
);
88 /* These helper macros take a cx as parameter and operate on its GSN cache. */
89 #define JS_PURGE_GSN_CACHE(cx) js_PurgeGSNCache(&JS_GSN_CACHE(cx))
90 #define JS_METER_GSN_CACHE(cx,cnt) GSN_CACHE_METER(&JS_GSN_CACHE(cx), cnt)
92 typedef struct InterpState InterpState
;
93 typedef struct VMSideExit VMSideExit
;
104 template<typename K
> struct DefaultHash
;
105 template<typename K
, typename V
, typename H
> class HashMap
;
106 template<typename T
> class Seq
;
109 #if defined(JS_JIT_SPEW) || defined(DEBUG)
111 typedef nanojit::HashMap
<uint32
, FragPI
, nanojit::DefaultHash
<uint32
> > FragStatsMap
;
115 extern "C++" { template<typename T
> class Queue
; }
116 typedef Queue
<uint16
> SlotList
;
118 #define FRAGMENT_TABLE_SIZE 512
123 class FrameInfoCache
;
124 typedef nanojit::HashMap
<REHashKey
, nanojit::Fragment
*, REHashFn
> REHashMap
;
126 #define MONITOR_N_GLOBAL_STATES 4
130 SlotList
* globalSlots
;
134 * Trace monitor. Every JSThread (if JS_THREADSAFE) or JSRuntime (if not
135 * JS_THREADSAFE) has an associated trace monitor that keeps track of loop
136 * frequencies for all JavaScript code loaded into that runtime.
138 struct JSTraceMonitor
{
140 * The context currently executing JIT-compiled code on this thread, or
141 * NULL if none. Among other things, this can in certain cases prevent
142 * last-ditch GC and suppress calls to JS_ReportOutOfMemory.
144 * !tracecx && !recorder: not on trace
145 * !tracecx && recorder: recording
146 * tracecx && !recorder: executing a trace
147 * tracecx && recorder: executing inner loop, recording outer loop
152 * There are 3 allocators here. This might seem like overkill, but they
153 * have different lifecycles, and by keeping them separate we keep the
154 * amount of retained memory down significantly.
156 * The dataAlloc has the lifecycle of the monitor. It's flushed only
157 * when the monitor is flushed.
159 * The traceAlloc has the same flush lifecycle as the dataAlloc, but
160 * it is also *marked* when a recording starts and rewinds to the mark
161 * point if recording aborts. So you can put things in it that are only
162 * reachable on a successful record/compile cycle.
164 * The tempAlloc is flushed after each recording, successful or not.
167 VMAllocator
* dataAlloc
; /* A chunk allocator for fragments. */
168 VMAllocator
* traceAlloc
; /* An allocator for trace metadata. */
169 VMAllocator
* tempAlloc
; /* A temporary chunk allocator. */
170 nanojit::CodeAlloc
* codeAlloc
; /* An allocator for native code. */
171 nanojit::Assembler
* assembler
;
172 nanojit::LirBuffer
* lirbuf
;
173 nanojit::LirBuffer
* reLirBuf
;
174 FrameInfoCache
* frameCache
;
176 nanojit::LabelMap
* labels
;
179 TraceRecorder
* recorder
;
180 jsval
*reservedDoublePool
;
181 jsval
*reservedDoublePoolPtr
;
183 struct GlobalState globalStates
[MONITOR_N_GLOBAL_STATES
];
184 struct VMFragment
* vmfragments
[FRAGMENT_TABLE_SIZE
];
185 JSDHashTable recordAttempts
;
188 * Maximum size of the code cache before we start flushing. 1/16 of this
189 * size is used as threshold for the regular expression code cache.
191 uint32 maxCodeCacheBytes
;
194 * If nonzero, do not flush the JIT cache after a deep bail. That would
195 * free JITted code pages that we will later return to. Instead, set the
196 * needFlush flag so that it can be flushed later.
201 * reservedObjects is a linked list (via fslots[0]) of preallocated JSObjects.
202 * The JIT uses this to ensure that leaving a trace tree can't fail.
204 JSBool useReservedObjects
;
205 JSObject
*reservedObjects
;
208 * Fragment map for the regular expression compiler.
210 REHashMap
* reFragments
;
213 * A temporary allocator for RE recording.
215 VMAllocator
* reTempAlloc
;
218 /* Fields needed for fragment/guard profiling. */
219 nanojit::Seq
<nanojit::Fragment
*>* branches
;
222 * profAlloc has a lifetime which spans exactly from js_InitJIT to
225 VMAllocator
* profAlloc
;
226 FragStatsMap
* profTab
;
229 /* Flush the JIT cache. */
232 /* Mark all objects baked into native code in the code cache. */
233 void mark(JSTracer
*trc
);
236 typedef struct InterpStruct InterpStruct
;
239 * N.B. JS_ON_TRACE(cx) is true if JIT code is on the stack in the current
240 * thread, regardless of whether cx is the context in which that trace is
241 * executing. cx must be a context on the current thread.
244 # define JS_ON_TRACE(cx) (JS_TRACE_MONITOR(cx).tracecx != NULL)
246 # define JS_ON_TRACE(cx) JS_FALSE
250 # define JS_EVAL_CACHE_METERING 1
251 # define JS_FUNCTION_METERING 1
254 /* Number of potentially reusable scriptsToGC to search for the eval cache. */
255 #ifndef JS_EVAL_CACHE_SHIFT
256 # define JS_EVAL_CACHE_SHIFT 6
258 #define JS_EVAL_CACHE_SIZE JS_BIT(JS_EVAL_CACHE_SHIFT)
260 #ifdef JS_EVAL_CACHE_METERING
261 # define EVAL_CACHE_METER_LIST(_) _(probe), _(hit), _(step), _(noscope)
262 # define identity(x) x
264 struct JSEvalCacheMeter
{
265 uint64
EVAL_CACHE_METER_LIST(identity
);
271 #ifdef JS_FUNCTION_METERING
272 # define FUNCTION_KIND_METER_LIST(_) \
273 _(allfun), _(heavy), _(nofreeupvar), _(onlyfreevar), \
274 _(display), _(flat), _(setupvar), _(badfunarg)
275 # define identity(x) x
277 typedef struct JSFunctionMeter
{
278 int32
FUNCTION_KIND_METER_LIST(identity
);
284 struct JSThreadData
{
285 JSGCFreeLists gcFreeLists
;
288 * The GSN cache is per thread since even multi-cx-per-thread embeddings
289 * do not interleave js_GetSrcNote calls.
293 /* Property cache for faster call/get/set invocation. */
294 JSPropertyCache propertyCache
;
296 /* Random number generator state, used by jsmath.cpp. */
300 /* Trace-tree JIT recorder/interpreter state. */
301 JSTraceMonitor traceMonitor
;
304 /* Lock-free hashed lists of scripts created by eval to garbage-collect. */
305 JSScript
*scriptsToGC
[JS_EVAL_CACHE_SIZE
];
307 #ifdef JS_EVAL_CACHE_METERING
308 JSEvalCacheMeter evalCacheMeter
;
312 * Cache of reusable JSNativeEnumerators mapped by shape identifiers (as
313 * stored in scope->shape). This cache is nulled by the GC and protected
316 #define NATIVE_ENUM_CACHE_LOG2 8
317 #define NATIVE_ENUM_CACHE_MASK JS_BITMASK(NATIVE_ENUM_CACHE_LOG2)
318 #define NATIVE_ENUM_CACHE_SIZE JS_BIT(NATIVE_ENUM_CACHE_LOG2)
320 #define NATIVE_ENUM_CACHE_HASH(shape) \
321 ((((shape) >> NATIVE_ENUM_CACHE_LOG2) ^ (shape)) & NATIVE_ENUM_CACHE_MASK)
323 jsuword nativeEnumCache
[NATIVE_ENUM_CACHE_SIZE
];
327 * Deallocator task for this thread.
329 JSFreePointerListTask
*deallocatorTask
;
332 void mark(JSTracer
*trc
) {
334 traceMonitor
.mark(trc
);
342 * Structure uniquely representing a thread. It holds thread-private data
343 * that can be accessed without a global lock.
346 /* Linked list of all contexts in use on this thread. */
349 /* Opaque thread-id, from NSPR's PR_GetCurrentThread(). */
352 /* Indicates that the thread is waiting in ClaimTitle from jslock.cpp. */
353 JSTitle
*titleToShare
;
356 * Thread-local version of JSRuntime.gcMallocBytes to avoid taking
357 * locks on each JS_malloc.
359 ptrdiff_t gcThreadMallocBytes
;
361 /* Factored out of JSThread for !JS_THREADSAFE embedding in JSRuntime. */
366 * Only when JSThread::gcThreadMallocBytes exhausts the following limit we
367 * update JSRuntime::gcMallocBytes.
370 const size_t JS_GC_THREAD_MALLOC_LIMIT
= 1 << 19;
372 #define JS_THREAD_DATA(cx) (&(cx)->thread->data)
374 struct JSThreadsHashEntry
{
375 JSDHashEntryHdr base
;
380 * The function takes the GC lock and does not release in successful return.
381 * On error (out of memory) the function releases the lock but delegates
382 * the error reporting to the caller.
385 js_InitContextThread(JSContext
*cx
);
388 * On entrance the GC lock must be held and it will be held on exit.
391 js_ClearContextThread(JSContext
*cx
);
393 #endif /* JS_THREADSAFE */
395 typedef enum JSDestroyContextMode
{
400 } JSDestroyContextMode
;
402 typedef enum JSRuntimeState
{
409 typedef enum JSBuiltinFunctionId
{
410 JSBUILTIN_ObjectToIterator
,
411 JSBUILTIN_CallIteratorNext
,
413 } JSBuiltinFunctionId
;
415 typedef struct JSPropertyTreeEntry
{
417 JSScopeProperty
*child
;
418 } JSPropertyTreeEntry
;
420 typedef struct JSSetSlotRequest JSSetSlotRequest
;
422 struct JSSetSlotRequest
{
423 JSObject
*obj
; /* object containing slot to set */
424 JSObject
*pobj
; /* new proto or parent reference */
425 uint16 slot
; /* which to set, proto or parent */
426 JSPackedBool cycle
; /* true if a cycle was detected */
427 JSSetSlotRequest
*next
; /* next request in GC worklist */
431 /* Runtime state, synchronized by the stateChange/gcLock condvar/lock. */
432 JSRuntimeState state
;
434 /* Context create/destroy callback. */
435 JSContextCallback cxCallback
;
438 * Shape regenerated whenever a prototype implicated by an "add property"
439 * property cache fill and induced trace guard has a readonly property or a
440 * setter defined on it. This number proxies for the shapes of all objects
441 * along the prototype chain of all objects in the runtime on which such an
442 * add-property result has been cached/traced.
444 * See bug 492355 for more details.
446 * This comes early in JSRuntime to minimize the immediate format used by
447 * trace-JITted code that reads it.
449 uint32 protoHazardShape
;
451 /* Garbage collector state, used by jsgc.c. */
452 JSGCChunkInfo
*gcChunkList
;
453 JSGCArenaList gcArenaList
[FINALIZE_LIMIT
];
454 JSGCDoubleArenaList gcDoubleArenaList
;
455 JSDHashTable gcRootsHash
;
456 JSDHashTable
*gcLocksHash
;
457 jsrefcount gcKeepAtoms
;
461 size_t gcMaxMallocBytes
;
462 uint32 gcEmptyArenaPoolLifespan
;
465 JSTracer
*gcMarkingTracer
;
466 uint32 gcTriggerFactor
;
467 size_t gcTriggerBytes
;
468 volatile JSBool gcIsNeeded
;
469 volatile JSBool gcFlushCodeCaches
;
472 * NB: do not pack another flag here by claiming gcPadding unless the new
473 * flag is written only by the GC thread. Atomic updates to packed bytes
474 * are not guaranteed, so stores issued by one thread may be lost due to
475 * unsynchronized read-modify-write cycles on other threads.
478 JSPackedBool gcRunning
;
479 JSPackedBool gcRegenShapes
;
482 * During gc, if rt->gcRegenShapes &&
483 * (scope->flags & JSScope::SHAPE_REGEN) == rt->gcRegenShapesScopeFlag,
484 * then the scope's shape has already been regenerated during this GC.
485 * To avoid having to sweep JSScopes, the bit's meaning toggles with each
486 * shape-regenerating GC.
488 * FIXME Once scopes are GC'd (bug 505004), this will be obsolete.
490 uint8 gcRegenShapesScopeFlag
;
496 JSGCCallback gcCallback
;
499 * Malloc counter to measure memory pressure for GC scheduling. It runs
500 * from gcMaxMallocBytes down to zero.
502 ptrdiff_t gcMallocBytes
;
505 * Stack of GC arenas containing things that the GC marked, where children
506 * reached from those things have not yet been marked. This helps avoid
507 * using too much native stack during recursive GC marking.
509 JSGCArenaInfo
*gcUntracedArenaStackTop
;
511 size_t gcTraceLaterCount
;
515 * Table for tracking iterators to ensure that we close iterator's state
516 * before finalizing the iterable object.
518 js::Vector
<JSObject
*, 0, js::SystemAllocPolicy
> gcIteratorTable
;
521 * The trace operation and its data argument to trace embedding-specific
524 JSTraceDataOp gcExtraRootsTraceOp
;
525 void *gcExtraRootsData
;
528 * Used to serialize cycle checks when setting __proto__ or __parent__ by
529 * requesting the GC handle the required cycle detection. If the GC hasn't
530 * been poked, it won't scan for garbage. This member is protected by
533 JSSetSlotRequest
*setSlotRequests
;
535 /* Well-known numbers held for use by this runtime's contexts. */
537 jsdouble
*jsNegativeInfinity
;
538 jsdouble
*jsPositiveInfinity
;
541 JSLock
*deflatedStringCacheLock
;
543 JSHashTable
*deflatedStringCache
;
545 uint32 deflatedStringCacheBytes
;
548 JSString
*emptyString
;
551 * Builtin functions, lazily created and held for use by the trace recorder.
553 * This field would be #ifdef JS_TRACER, but XPConnect is compiled without
554 * -DJS_TRACER and includes this header.
556 JSObject
*builtinFunctions
[JSBUILTIN_LIMIT
];
558 /* List of active contexts sharing this runtime; protected by gcLock. */
561 /* Per runtime debug hooks -- see jsprvtd.h and jsdbgapi.h. */
562 JSDebugHooks globalDebugHooks
;
564 /* More debugging state, see jsdbgapi.c. */
566 JSCList watchPointList
;
568 /* Client opaque pointers */
572 /* These combine to interlock the GC and new requests. */
575 PRCondVar
*requestDone
;
579 /* Lock and owning thread pointer for JS_LOCK_RUNTIME. */
585 /* Used to synchronize down/up state change; protected by gcLock. */
586 PRCondVar
*stateChange
;
589 * State for sharing single-threaded titles, once a second thread tries to
590 * lock a title. The titleSharingDone condvar is protected by rt->gcLock
591 * to minimize number of locks taken in JS_EndRequest.
593 * The titleSharingTodo linked list is likewise "global" per runtime, not
594 * one-list-per-context, to conserve space over all contexts, optimizing
595 * for the likely case that titles become shared rarely, and among a very
596 * small set of threads (contexts).
598 PRCondVar
*titleSharingDone
;
599 JSTitle
*titleSharingTodo
;
602 * Magic terminator for the rt->titleSharingTodo linked list, threaded through
603 * title->u.link. This hack allows us to test whether a title is on the list
604 * by asking whether title->u.link is non-null. We use a large, likely bogus
605 * pointer here to distinguish this value from any valid u.count (small int)
608 #define NO_TITLE_SHARING_TODO ((JSTitle *) 0xfeedbeef)
611 * Lock serializing trapList and watchPointList accesses, and count of all
612 * mutations to trapList and watchPointList made by debugger threads. To
613 * keep the code simple, we define debuggerMutations for the thread-unsafe
616 PRLock
*debuggerLock
;
618 JSDHashTable threads
;
619 #endif /* JS_THREADSAFE */
620 uint32 debuggerMutations
;
623 * Security callbacks set on the runtime are used by each context unless
624 * an override is set on the context.
626 JSSecurityCallbacks
*securityCallbacks
;
629 * Shared scope property tree, and arena-pool for allocating its nodes.
630 * The propertyRemovals counter is incremented for every JSScope::clear,
631 * and for each JSScope::remove method call that frees a slot in an object.
632 * See js_NativeGet and js_NativeSet in jsobj.c.
634 JSDHashTable propertyTreeHash
;
635 JSScopeProperty
*propertyFreeList
;
636 JSArenaPool propertyArenaPool
;
637 int32 propertyRemovals
;
639 /* Script filename table. */
640 struct JSHashTable
*scriptFilenameTable
;
641 JSCList scriptFilenamePrefixes
;
643 PRLock
*scriptFilenameTableLock
;
646 /* Number localization, used by jsnum.c */
647 const char *thousandsSeparator
;
648 const char *decimalSeparator
;
649 const char *numGrouping
;
652 * Weak references to lazily-created, well-known XML singletons.
654 * NB: Singleton objects must be carefully disconnected from the rest of
655 * the object graph usually associated with a JSContext's global object,
656 * including the set of standard class objects. See jsxml.c for details.
658 JSObject
*anynameObject
;
659 JSObject
*functionNamespaceObject
;
661 #ifndef JS_THREADSAFE
662 JSThreadData threadData
;
664 #define JS_THREAD_DATA(cx) (&(cx)->runtime->threadData)
668 * Object shape (property cache structural type) identifier generator.
670 * Type 0 stands for the empty scope, and must not be regenerated due to
671 * uint32 wrap-around. Since js_GenerateShape (in jsinterp.cpp) uses
672 * atomic pre-increment, the initial value for the first typed non-empty
675 * If this counter overflows into SHAPE_OVERFLOW_BIT (in jsinterp.h), the
676 * cache is disabled, to avoid aliasing two different types. It stays
677 * disabled until a triggered GC at some later moment compresses live
678 * types, minimizing rt->shapeGen in the process.
680 volatile uint32 shapeGen
;
682 /* Literal table maintained by jsatom.c functions. */
683 JSAtomState atomState
;
686 JSBackgroundThread
*deallocatorThread
;
690 * Various metering fields are defined at the end of JSRuntime. In this
691 * way there is no need to recompile all the code that refers to other
692 * fields of JSRuntime after enabling the corresponding metering macro.
694 #ifdef JS_DUMP_ENUM_CACHE_STATS
695 int32 nativeEnumProbes
;
696 int32 nativeEnumMisses
;
697 # define ENUM_CACHE_METER(name) JS_ATOMIC_INCREMENT(&cx->runtime->name)
699 # define ENUM_CACHE_METER(name) ((void) 0)
702 #ifdef JS_DUMP_LOOP_STATS
703 /* Loop statistics, to trigger trace recording and compiling. */
704 JSBasicStats loopStats
;
707 #if defined DEBUG || defined JS_DUMP_PROPTREE_STATS
708 /* Function invocation metering. */
709 jsrefcount inlineCalls
;
710 jsrefcount nativeCalls
;
711 jsrefcount nonInlineCalls
;
712 jsrefcount constructs
;
714 /* Title lock and scope property metering. */
715 jsrefcount claimAttempts
;
716 jsrefcount claimedTitles
;
717 jsrefcount deadContexts
;
718 jsrefcount deadlocksAvoided
;
719 jsrefcount liveScopes
;
720 jsrefcount sharedTitles
;
721 jsrefcount totalScopes
;
722 jsrefcount liveScopeProps
;
723 jsrefcount liveScopePropsPreSweep
;
724 jsrefcount totalScopeProps
;
725 jsrefcount livePropTreeNodes
;
726 jsrefcount duplicatePropTreeNodes
;
727 jsrefcount totalPropTreeNodes
;
728 jsrefcount propTreeKidsChunks
;
729 jsrefcount middleDeleteFixups
;
731 /* String instrumentation. */
732 jsrefcount liveStrings
;
733 jsrefcount totalStrings
;
734 jsrefcount liveDependentStrings
;
735 jsrefcount totalDependentStrings
;
736 jsrefcount badUndependStrings
;
738 double lengthSquaredSum
;
739 double strdepLengthSum
;
740 double strdepLengthSquaredSum
;
742 /* Script instrumentation. */
743 jsrefcount liveScripts
;
744 jsrefcount totalScripts
;
745 jsrefcount liveEmptyScripts
;
746 jsrefcount totalEmptyScripts
;
747 #endif /* DEBUG || JS_DUMP_PROPTREE_STATS */
749 #ifdef JS_SCOPE_DEPTH_METER
751 * Stats on runtime prototype chain lookups and scope chain depths, i.e.,
752 * counts of objects traversed on a chain until the wanted id is found.
754 JSBasicStats protoLookupDepthStats
;
755 JSBasicStats scopeSearchDepthStats
;
758 * Stats on compile-time host environment and lexical scope chain lengths
761 JSBasicStats hostenvScopeDepthStats
;
762 JSBasicStats lexicalScopeDepthStats
;
769 #ifdef JS_FUNCTION_METERING
770 JSFunctionMeter functionMeter
;
771 char lastScriptFilename
[1024];
777 bool init(uint32 maxbytes
);
779 void setGCTriggerFactor(uint32 factor
);
780 void setGCLastBytes(size_t lastBytes
);
782 void* malloc(size_t bytes
) { return ::js_malloc(bytes
); }
784 void* calloc(size_t bytes
) { return ::js_calloc(bytes
); }
786 void* realloc(void* p
, size_t bytes
) { return ::js_realloc(p
, bytes
); }
788 void free(void* p
) { ::js_free(p
); }
790 bool isGCMallocLimitReached() const { return gcMallocBytes
<= 0; }
792 void resetGCMallocBytes() { gcMallocBytes
= ptrdiff_t(gcMaxMallocBytes
); }
794 void setGCMaxMallocBytes(size_t value
) {
796 * For compatibility treat any value that exceeds PTRDIFF_T_MAX to
799 gcMaxMallocBytes
= (ptrdiff_t(value
) >= 0) ? value
: size_t(-1) >> 1;
800 resetGCMallocBytes();
804 /* Common macros to access thread-local caches in JSThread or JSRuntime. */
805 #define JS_GSN_CACHE(cx) (JS_THREAD_DATA(cx)->gsnCache)
806 #define JS_PROPERTY_CACHE(cx) (JS_THREAD_DATA(cx)->propertyCache)
807 #define JS_TRACE_MONITOR(cx) (JS_THREAD_DATA(cx)->traceMonitor)
808 #define JS_SCRIPTS_TO_GC(cx) (JS_THREAD_DATA(cx)->scriptsToGC)
810 #ifdef JS_EVAL_CACHE_METERING
811 # define EVAL_CACHE_METER(x) (JS_THREAD_DATA(cx)->evalCacheMeter.x++)
813 # define EVAL_CACHE_METER(x) ((void) 0)
817 # define JS_RUNTIME_METER(rt, which) JS_ATOMIC_INCREMENT(&(rt)->which)
818 # define JS_RUNTIME_UNMETER(rt, which) JS_ATOMIC_DECREMENT(&(rt)->which)
820 # define JS_RUNTIME_METER(rt, which) /* nothing */
821 # define JS_RUNTIME_UNMETER(rt, which) /* nothing */
824 #define JS_KEEP_ATOMS(rt) JS_ATOMIC_INCREMENT(&(rt)->gcKeepAtoms);
825 #define JS_UNKEEP_ATOMS(rt) JS_ATOMIC_DECREMENT(&(rt)->gcKeepAtoms);
827 #ifdef JS_ARGUMENT_FORMATTER_DEFINED
829 * Linked list mapping format strings for JS_{Convert,Push}Arguments{,VA} to
830 * formatter functions. Elements are sorted in non-increasing format string
833 struct JSArgumentFormatMap
{
836 JSArgumentFormatter formatter
;
837 JSArgumentFormatMap
*next
;
841 struct JSStackHeader
{
846 #define JS_STACK_SEGMENT(sh) ((jsval *)(sh) + 2)
849 * Key and entry types for the JSContext.resolvingTable hash table, typedef'd
850 * here because all consumers need to see these declarations (and not just the
851 * typedef names, as would be the case for an opaque pointer-to-typedef'd-type
852 * declaration), along with cx->resolvingTable.
854 typedef struct JSResolvingKey
{
859 typedef struct JSResolvingEntry
{
865 #define JSRESFLAG_LOOKUP 0x1 /* resolving id from lookup */
866 #define JSRESFLAG_WATCH 0x2 /* resolving id from watch */
868 typedef struct JSLocalRootChunk JSLocalRootChunk
;
870 #define JSLRS_CHUNK_SHIFT 8
871 #define JSLRS_CHUNK_SIZE JS_BIT(JSLRS_CHUNK_SHIFT)
872 #define JSLRS_CHUNK_MASK JS_BITMASK(JSLRS_CHUNK_SHIFT)
874 struct JSLocalRootChunk
{
875 jsval roots
[JSLRS_CHUNK_SIZE
];
876 JSLocalRootChunk
*down
;
879 typedef struct JSLocalRootStack
{
882 JSLocalRootChunk
*topChunk
;
883 JSLocalRootChunk firstChunk
;
886 #define JSLRS_NULL_MARK ((uint32) -1)
889 * Macros to push/pop JSTempValueRooter instances to context-linked stack of
890 * temporary GC roots. If you need to protect a result value that flows out of
891 * a C function across several layers of other functions, use the
892 * js_LeaveLocalRootScopeWithResult internal API (see further below) instead.
894 * The macros also provide a simple way to get a single rooted pointer via
895 * JS_PUSH_TEMP_ROOT_<KIND>(cx, NULL, &tvr). Then &tvr.u.<kind> gives the
898 * JSTempValueRooter.count defines the type of the rooted value referenced by
899 * JSTempValueRooter.u union of type JSTempValueUnion. When count is positive
900 * or zero, u.array points to a vector of jsvals. Otherwise it must be one of
901 * the following constants:
903 #define JSTVU_SINGLE (-1) /* u.value or u.<gcthing> is single jsval
904 or non-JSString GC-thing pointer */
905 #define JSTVU_TRACE (-2) /* u.trace is a hook to trace a custom
907 #define JSTVU_SPROP (-3) /* u.sprop roots property tree node */
908 #define JSTVU_WEAK_ROOTS (-4) /* u.weakRoots points to saved weak roots */
909 #define JSTVU_COMPILER (-5) /* u.compiler roots JSCompiler* */
910 #define JSTVU_SCRIPT (-6) /* u.script roots JSScript* */
911 #define JSTVU_ENUMERATOR (-7) /* a pointer to JSTempValueRooter points
912 to an instance of JSAutoEnumStateRooter
913 with u.object storing the enumeration
917 * Here single JSTVU_SINGLE covers both jsval and pointers to almost (see note
918 * below) any GC-thing via reinterpreting the thing as JSVAL_OBJECT. This works
919 * because the GC-thing is aligned on a 0 mod 8 boundary, and object has the 0
920 * jsval tag. So any GC-heap-allocated thing pointer may be tagged as if it
921 * were an object and untagged, if it's then used only as an opaque pointer
922 * until discriminated by other means than tag bits. This is how, for example,
923 * js_GetGCThingTraceKind uses its |thing| parameter -- it consults GC-thing
924 * flags stored separately from the thing to decide the kind of thing.
926 * Note well that JSStrings may be statically allocated (see the intStringTable
927 * and unitStringTable static arrays), so this hack does not work for arbitrary
930 #define JS_PUSH_TEMP_ROOT_COMMON(cx,x,tvr,cnt,kind) \
932 JS_ASSERT((cx)->tempValueRooters != (tvr)); \
933 (tvr)->count = (cnt); \
934 (tvr)->u.kind = (x); \
935 (tvr)->down = (cx)->tempValueRooters; \
936 (cx)->tempValueRooters = (tvr); \
939 #define JS_POP_TEMP_ROOT(cx,tvr) \
941 JS_ASSERT((cx)->tempValueRooters == (tvr)); \
942 (cx)->tempValueRooters = (tvr)->down; \
945 #define JS_PUSH_TEMP_ROOT(cx,cnt,arr,tvr) \
947 JS_ASSERT((int)(cnt) >= 0); \
948 JS_PUSH_TEMP_ROOT_COMMON(cx, arr, tvr, (ptrdiff_t) (cnt), array); \
951 #define JS_PUSH_SINGLE_TEMP_ROOT(cx,val,tvr) \
952 JS_PUSH_TEMP_ROOT_COMMON(cx, val, tvr, JSTVU_SINGLE, value)
954 #define JS_PUSH_TEMP_ROOT_OBJECT(cx,obj,tvr) \
955 JS_PUSH_TEMP_ROOT_COMMON(cx, obj, tvr, JSTVU_SINGLE, object)
957 #define JS_PUSH_TEMP_ROOT_STRING(cx,str,tvr) \
958 JS_PUSH_SINGLE_TEMP_ROOT(cx, str ? STRING_TO_JSVAL(str) : JSVAL_NULL, tvr)
960 #define JS_PUSH_TEMP_ROOT_XML(cx,xml_,tvr) \
961 JS_PUSH_TEMP_ROOT_COMMON(cx, xml_, tvr, JSTVU_SINGLE, xml)
963 #define JS_PUSH_TEMP_ROOT_TRACE(cx,trace_,tvr) \
964 JS_PUSH_TEMP_ROOT_COMMON(cx, trace_, tvr, JSTVU_TRACE, trace)
966 #define JS_PUSH_TEMP_ROOT_SPROP(cx,sprop_,tvr) \
967 JS_PUSH_TEMP_ROOT_COMMON(cx, sprop_, tvr, JSTVU_SPROP, sprop)
969 #define JS_PUSH_TEMP_ROOT_WEAK_COPY(cx,weakRoots_,tvr) \
970 JS_PUSH_TEMP_ROOT_COMMON(cx, weakRoots_, tvr, JSTVU_WEAK_ROOTS, weakRoots)
972 #define JS_PUSH_TEMP_ROOT_COMPILER(cx,pc,tvr) \
973 JS_PUSH_TEMP_ROOT_COMMON(cx, pc, tvr, JSTVU_COMPILER, compiler)
975 #define JS_PUSH_TEMP_ROOT_SCRIPT(cx,script_,tvr) \
976 JS_PUSH_TEMP_ROOT_COMMON(cx, script_, tvr, JSTVU_SCRIPT, script)
978 #define JSRESOLVE_INFER 0xffff /* infer bits from current bytecode */
982 * If this flag is set, we were asked to call back the operation callback
983 * as soon as possible.
985 volatile jsint operationCallbackFlag
;
987 /* JSRuntime contextList linkage. */
990 #if JS_HAS_XML_SUPPORT
992 * Bit-set formed from binary exponentials of the XML_* tiny-ids defined
993 * for boolean settings in jsxml.c, plus an XSF_CACHE_VALID bit. Together
994 * these act as a cache of the boolean XML.ignore* and XML.prettyPrinting
995 * property values associated with this context's global object.
997 uint8 xmlSettingFlags
;
1004 * Classic Algol "display" static link optimization.
1006 #define JS_DISPLAY_SIZE 16U
1008 JSStackFrame
*display
[JS_DISPLAY_SIZE
];
1010 /* Runtime version control identifier. */
1013 /* Per-context options. */
1014 uint32 options
; /* see jsapi.h for JSOPTION_* */
1016 /* Locale specific callbacks for string conversion. */
1017 JSLocaleCallbacks
*localeCallbacks
;
1020 * cx->resolvingTable is non-null and non-empty if we are initializing
1021 * standard classes lazily, or if we are otherwise recursing indirectly
1022 * from js_LookupProperty through a JSClass.resolve hook. It is used to
1023 * limit runaway recursion (see jsapi.c and jsobj.c).
1025 JSDHashTable
*resolvingTable
;
1028 * True if generating an error, to prevent runaway recursion.
1029 * NB: generatingError packs with insideGCMarkCallback and throwing below.
1031 JSPackedBool generatingError
;
1033 /* Flag to indicate that we run inside gcCallback(cx, JSGC_MARK_END). */
1034 JSPackedBool insideGCMarkCallback
;
1036 /* Exception state -- the exception member is a GC root by definition. */
1037 JSPackedBool throwing
; /* is there a pending exception? */
1038 jsval exception
; /* most-recently-thrown exception */
1040 /* Limit pointer for checking native stack consumption during recursion. */
1043 /* Quota on the size of arenas used to compile and execute scripts. */
1044 size_t scriptStackQuota
;
1046 /* Data shared by threads in an address space. */
1047 JSRuntime
* const runtime
;
1049 explicit JSContext(JSRuntime
*rt
) : runtime(rt
) {}
1051 /* Stack arena pool and frame pointer register. */
1053 JSArenaPool stackPool
;
1058 /* Temporary arena pool used while compiling and decompiling. */
1059 JSArenaPool tempPool
;
1061 /* Top-level object and pointer to top stack frame's scope chain. */
1062 JSObject
*globalObject
;
1064 /* Storage to root recently allocated GC things and script result. */
1065 JSWeakRoots weakRoots
;
1067 /* Regular expression class statics (XXX not shared globally). */
1068 JSRegExpStatics regExpStatics
;
1070 /* State for object and array toSource conversion. */
1071 JSSharpObjectMap sharpObjectMap
;
1072 JSHashTable
*busyArrayTable
;
1074 /* Argument formatter support for JS_{Convert,Push}Arguments{,VA}. */
1075 JSArgumentFormatMap
*argumentFormatMap
;
1077 /* Last message string and trace file for debugging. */
1081 jsbytecode
*tracePrevPc
;
1084 /* Per-context optional error reporter. */
1085 JSErrorReporter errorReporter
;
1087 /* Branch callback. */
1088 JSOperationCallback operationCallback
;
1090 /* Interpreter activation count. */
1093 /* Client opaque pointers. */
1097 /* GC and thread-safe state. */
1098 JSStackFrame
*dormantFrameChain
; /* dormant stack frame to scan */
1099 #ifdef JS_THREADSAFE
1101 jsrefcount requestDepth
;
1102 /* Same as requestDepth but ignoring JS_SuspendRequest/JS_ResumeRequest */
1103 jsrefcount outstandingRequests
;
1104 JSTitle
*lockedSealedTitle
; /* weak ref, for low-cost sealed
1106 JSCList threadLinks
; /* JSThread contextList linkage */
1108 #define CX_FROM_THREAD_LINKS(tl) \
1109 ((JSContext *)((char *)(tl) - offsetof(JSContext, threadLinks)))
1112 /* PDL of stack headers describing stack slots not rooted by argv, etc. */
1113 JSStackHeader
*stackHeaders
;
1115 /* Optional stack of heap-allocated scoped local GC roots. */
1116 JSLocalRootStack
*localRootStack
;
1118 /* Stack of thread-stack-allocated temporary GC roots. */
1119 JSTempValueRooter
*tempValueRooters
;
1121 /* Debug hooks associated with the current context. */
1122 JSDebugHooks
*debugHooks
;
1124 /* Security callbacks that override any defined on the runtime. */
1125 JSSecurityCallbacks
*securityCallbacks
;
1127 /* Pinned regexp pool used for regular expressions. */
1128 JSArenaPool regexpPool
;
1130 /* Stored here to avoid passing it around as a parameter. */
1135 * State for the current tree execution. bailExit is valid if the tree has
1136 * called back into native code via a _FAIL builtin and has not yet bailed,
1137 * else garbage (NULL in debug builds).
1139 InterpState
*interpState
;
1140 VMSideExit
*bailExit
;
1143 #ifdef JS_THREADSAFE
1144 inline void createDeallocatorTask() {
1145 JSThreadData
* tls
= JS_THREAD_DATA(this);
1146 JS_ASSERT(!tls
->deallocatorTask
);
1147 if (runtime
->deallocatorThread
&& !runtime
->deallocatorThread
->busy())
1148 tls
->deallocatorTask
= new JSFreePointerListTask();
1151 inline void submitDeallocatorTask() {
1152 JSThreadData
* tls
= JS_THREAD_DATA(this);
1153 if (tls
->deallocatorTask
) {
1154 runtime
->deallocatorThread
->schedule(tls
->deallocatorTask
);
1155 tls
->deallocatorTask
= NULL
;
1160 ptrdiff_t &getMallocCounter() {
1161 #ifdef JS_THREADSAFE
1162 return thread
->gcThreadMallocBytes
;
1164 return runtime
->gcMallocBytes
;
1169 * Call this after allocating memory held by GC things, to update memory
1170 * pressure counters or report the OOM error if necessary.
1172 inline void updateMallocCounter(void *p
, size_t nbytes
) {
1173 JS_ASSERT(ptrdiff_t(nbytes
) >= 0);
1174 ptrdiff_t &counter
= getMallocCounter();
1175 counter
-= ptrdiff_t(nbytes
);
1176 if (!p
|| counter
<= 0)
1177 checkMallocGCPressure(p
);
1181 * Call this after successfully allocating memory held by GC things, to
1182 * update memory pressure counters.
1184 inline void updateMallocCounter(size_t nbytes
) {
1185 JS_ASSERT(ptrdiff_t(nbytes
) >= 0);
1186 ptrdiff_t &counter
= getMallocCounter();
1187 counter
-= ptrdiff_t(nbytes
);
1190 * Use 1 as an arbitrary non-null pointer indicating successful
1193 checkMallocGCPressure(reinterpret_cast<void *>(jsuword(1)));
1197 inline void* malloc(size_t bytes
) {
1198 JS_ASSERT(bytes
!= 0);
1199 void *p
= runtime
->malloc(bytes
);
1200 updateMallocCounter(p
, bytes
);
1204 inline void* mallocNoReport(size_t bytes
) {
1205 JS_ASSERT(bytes
!= 0);
1206 void *p
= runtime
->malloc(bytes
);
1209 updateMallocCounter(bytes
);
1213 inline void* calloc(size_t bytes
) {
1214 JS_ASSERT(bytes
!= 0);
1215 void *p
= runtime
->calloc(bytes
);
1216 updateMallocCounter(p
, bytes
);
1220 inline void* realloc(void* p
, size_t bytes
) {
1222 p
= runtime
->realloc(p
, bytes
);
1225 * For compatibility we do not account for realloc that increases
1226 * previously allocated memory.
1228 updateMallocCounter(p
, orig
? 0 : bytes
);
1232 #ifdef JS_THREADSAFE
1233 inline void free(void* p
) {
1237 JSFreePointerListTask
* task
= JS_THREAD_DATA(this)->deallocatorTask
;
1246 inline void free(void* p
) {
1254 * In the common case that we'd like to allocate the memory for an object
1255 * with cx->malloc/free, we cannot use overloaded C++ operators (no
1256 * placement delete). Factor the common workaround into one place.
1258 #define CREATE_BODY(parms) \
1259 void *memory = this->malloc(sizeof(T)); \
1262 return new(memory) T parms;
1265 JS_ALWAYS_INLINE T
*create() {
1269 template <class T
, class P1
>
1270 JS_ALWAYS_INLINE T
*create(const P1
&p1
) {
1274 template <class T
, class P1
, class P2
>
1275 JS_ALWAYS_INLINE T
*create(const P1
&p1
, const P2
&p2
) {
1276 CREATE_BODY((p1
, p2
))
1279 template <class T
, class P1
, class P2
, class P3
>
1280 JS_ALWAYS_INLINE T
*create(const P1
&p1
, const P2
&p2
, const P3
&p3
) {
1281 CREATE_BODY((p1
, p2
, p3
))
1286 JS_ALWAYS_INLINE
void destroy(T
*p
) {
1294 * The allocation code calls the function to indicate either OOM failure
1295 * when p is null or that a memory pressure counter has reached some
1296 * threshold when p is not null. The function takes the pointer and not
1297 * a boolean flag to minimize the amount of code in its inlined callers.
1299 void checkMallocGCPressure(void *p
);
1302 #ifdef JS_THREADSAFE
1303 # define JS_THREAD_ID(cx) ((cx)->thread ? (cx)->thread->id : 0)
1308 static inline JSAtom
**
1309 FrameAtomBase(JSContext
*cx
, JSStackFrame
*fp
)
1312 ? COMMON_ATOMS_START(&cx
->runtime
->atomState
)
1313 : fp
->script
->atomMap
.vector
;
1316 /* FIXME(bug 332648): Move this into a public header. */
1317 class JSAutoTempValueRooter
1320 JSAutoTempValueRooter(JSContext
*cx
, size_t len
, jsval
*vec
1321 JS_GUARD_OBJECT_NOTIFIER_PARAM
)
1323 JS_GUARD_OBJECT_NOTIFIER_INIT
;
1324 JS_PUSH_TEMP_ROOT(mContext
, len
, vec
, &mTvr
);
1326 explicit JSAutoTempValueRooter(JSContext
*cx
, jsval v
= JSVAL_NULL
1327 JS_GUARD_OBJECT_NOTIFIER_PARAM
)
1329 JS_GUARD_OBJECT_NOTIFIER_INIT
;
1330 JS_PUSH_SINGLE_TEMP_ROOT(mContext
, v
, &mTvr
);
1332 JSAutoTempValueRooter(JSContext
*cx
, JSString
*str
1333 JS_GUARD_OBJECT_NOTIFIER_PARAM
)
1335 JS_GUARD_OBJECT_NOTIFIER_INIT
;
1336 JS_PUSH_TEMP_ROOT_STRING(mContext
, str
, &mTvr
);
1338 JSAutoTempValueRooter(JSContext
*cx
, JSObject
*obj
1339 JS_GUARD_OBJECT_NOTIFIER_PARAM
)
1341 JS_GUARD_OBJECT_NOTIFIER_INIT
;
1342 JS_PUSH_TEMP_ROOT_OBJECT(mContext
, obj
, &mTvr
);
1344 JSAutoTempValueRooter(JSContext
*cx
, JSScopeProperty
*sprop
1345 JS_GUARD_OBJECT_NOTIFIER_PARAM
)
1347 JS_GUARD_OBJECT_NOTIFIER_INIT
;
1348 JS_PUSH_TEMP_ROOT_SPROP(mContext
, sprop
, &mTvr
);
1351 ~JSAutoTempValueRooter() {
1352 JS_POP_TEMP_ROOT(mContext
, &mTvr
);
1355 jsval
value() { return mTvr
.u
.value
; }
1356 jsval
*addr() { return &mTvr
.u
.value
; }
1359 JSContext
*mContext
;
1363 static void *operator new(size_t);
1364 static void operator delete(void *, size_t);
1367 JSTempValueRooter mTvr
;
1368 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1371 class JSAutoTempIdRooter
1374 explicit JSAutoTempIdRooter(JSContext
*cx
, jsid id
= INT_TO_JSID(0)
1375 JS_GUARD_OBJECT_NOTIFIER_PARAM
)
1377 JS_GUARD_OBJECT_NOTIFIER_INIT
;
1378 JS_PUSH_SINGLE_TEMP_ROOT(mContext
, ID_TO_VALUE(id
), &mTvr
);
1381 ~JSAutoTempIdRooter() {
1382 JS_POP_TEMP_ROOT(mContext
, &mTvr
);
1385 jsid
id() { return (jsid
) mTvr
.u
.value
; }
1386 jsid
* addr() { return (jsid
*) &mTvr
.u
.value
; }
1389 JSContext
*mContext
;
1390 JSTempValueRooter mTvr
;
1391 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1394 class JSAutoIdArray
{
1396 JSAutoIdArray(JSContext
*cx
, JSIdArray
*ida
1397 JS_GUARD_OBJECT_NOTIFIER_PARAM
)
1398 : cx(cx
), idArray(ida
) {
1399 JS_GUARD_OBJECT_NOTIFIER_INIT
;
1401 JS_PUSH_TEMP_ROOT(cx
, ida
->length
, ida
->vector
, &tvr
);
1405 JS_POP_TEMP_ROOT(cx
, &tvr
);
1406 JS_DestroyIdArray(cx
, idArray
);
1410 return idArray
== NULL
;
1412 jsid
operator[](size_t i
) const {
1414 JS_ASSERT(i
< size_t(idArray
->length
));
1415 return idArray
->vector
[i
];
1417 size_t length() const {
1418 return idArray
->length
;
1421 JSContext
* const cx
;
1422 JSIdArray
* const idArray
;
1423 JSTempValueRooter tvr
;
1424 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1427 /* The auto-root for enumeration object and its state. */
1428 class JSAutoEnumStateRooter
: public JSTempValueRooter
1431 JSAutoEnumStateRooter(JSContext
*cx
, JSObject
*obj
, jsval
*statep
1432 JS_GUARD_OBJECT_NOTIFIER_PARAM
)
1433 : mContext(cx
), mStatep(statep
)
1435 JS_GUARD_OBJECT_NOTIFIER_INIT
;
1438 JS_PUSH_TEMP_ROOT_COMMON(cx
, obj
, this, JSTVU_ENUMERATOR
, object
);
1441 ~JSAutoEnumStateRooter() {
1442 JS_POP_TEMP_ROOT(mContext
, this);
1445 void mark(JSTracer
*trc
) {
1446 JS_CALL_OBJECT_TRACER(trc
, u
.object
, "enumerator_obj");
1447 js_MarkEnumeratorState(trc
, u
.object
, *mStatep
);
1451 JSContext
*mContext
;
1453 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1456 class JSAutoResolveFlags
1459 JSAutoResolveFlags(JSContext
*cx
, uintN flags
1460 JS_GUARD_OBJECT_NOTIFIER_PARAM
)
1461 : mContext(cx
), mSaved(cx
->resolveFlags
) {
1462 JS_GUARD_OBJECT_NOTIFIER_INIT
;
1463 cx
->resolveFlags
= flags
;
1466 ~JSAutoResolveFlags() { mContext
->resolveFlags
= mSaved
; }
1469 JSContext
*mContext
;
1471 JS_DECL_USE_GUARD_OBJECT_NOTIFIER
1474 #endif /* __cpluscplus */
1477 * Slightly more readable macros for testing per-context option settings (also
1478 * to hide bitset implementation detail).
1480 * JSOPTION_XML must be handled specially in order to propagate from compile-
1481 * to run-time (from cx->options to script->version/cx->version). To do that,
1482 * we copy JSOPTION_XML from cx->options into cx->version as JSVERSION_HAS_XML
1483 * whenever options are set, and preserve this XML flag across version number
1484 * changes done via the JS_SetVersion API.
1486 * But when executing a script or scripted function, the interpreter changes
1487 * cx->version, including the XML flag, to script->version. Thus JSOPTION_XML
1488 * is a compile-time option that causes a run-time version change during each
1489 * activation of the compiled script. That version change has the effect of
1490 * changing JS_HAS_XML_OPTION, so that any compiling done via eval enables XML
1491 * support. If an XML-enabled script or function calls a non-XML function,
1492 * the flag bit will be cleared during the callee's activation.
1494 * Note that JS_SetVersion API calls never pass JSVERSION_HAS_XML or'd into
1495 * that API's version parameter.
1497 * Note also that script->version must contain this XML option flag in order
1498 * for XDR'ed scripts to serialize and deserialize with that option preserved
1499 * for detection at run-time. We can't copy other compile-time options into
1500 * script->version because that would break backward compatibility (certain
1501 * other options, e.g. JSOPTION_VAROBJFIX, are analogous to JSOPTION_XML).
1503 #define JS_HAS_OPTION(cx,option) (((cx)->options & (option)) != 0)
1504 #define JS_HAS_STRICT_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_STRICT)
1505 #define JS_HAS_WERROR_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_WERROR)
1506 #define JS_HAS_COMPILE_N_GO_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_COMPILE_N_GO)
1507 #define JS_HAS_ATLINE_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_ATLINE)
1509 #define JSVERSION_MASK 0x0FFF /* see JSVersion in jspubtd.h */
1510 #define JSVERSION_HAS_XML 0x1000 /* flag induced by XML option */
1511 #define JSVERSION_ANONFUNFIX 0x2000 /* see jsapi.h, the comments
1512 for JSOPTION_ANONFUNFIX */
1514 #define JSVERSION_NUMBER(cx) ((JSVersion)((cx)->version & \
1516 #define JS_HAS_XML_OPTION(cx) ((cx)->version & JSVERSION_HAS_XML || \
1517 JSVERSION_NUMBER(cx) >= JSVERSION_1_6)
1520 js_InitThreads(JSRuntime
*rt
);
1523 js_FinishThreads(JSRuntime
*rt
);
1526 js_PurgeThreads(JSContext
*cx
);
1529 js_TraceThreads(JSRuntime
*rt
, JSTracer
*trc
);
1532 * Ensures the JSOPTION_XML and JSOPTION_ANONFUNFIX bits of cx->options are
1533 * reflected in cx->version, since each bit must travel with a script that has
1537 js_SyncOptionsToVersion(JSContext
*cx
);
1540 * Common subroutine of JS_SetVersion and js_SetVersion, to update per-context
1541 * data that depends on version.
1544 js_OnVersionChange(JSContext
*cx
);
1547 * Unlike the JS_SetVersion API, this function stores JSVERSION_HAS_XML and
1548 * any future non-version-number flags induced by compiler options.
1551 js_SetVersion(JSContext
*cx
, JSVersion version
);
1554 * Create and destroy functions for JSContext, which is manually allocated
1555 * and exclusively owned.
1558 js_NewContext(JSRuntime
*rt
, size_t stackChunkSize
);
1561 js_DestroyContext(JSContext
*cx
, JSDestroyContextMode mode
);
1564 * Return true if cx points to a context in rt->contextList, else return false.
1565 * NB: the caller (see jslock.c:ClaimTitle) must hold rt->gcLock.
1568 js_ValidContextPointer(JSRuntime
*rt
, JSContext
*cx
);
1570 static JS_INLINE JSContext
*
1571 js_ContextFromLinkField(JSCList
*link
)
1574 return (JSContext
*) ((uint8
*) link
- offsetof(JSContext
, link
));
1578 * If unlocked, acquire and release rt->gcLock around *iterp update; otherwise
1579 * the caller must be holding rt->gcLock.
1582 js_ContextIterator(JSRuntime
*rt
, JSBool unlocked
, JSContext
**iterp
);
1585 * Iterate through contexts with active requests. The caller must be holding
1586 * rt->gcLock in case of a thread-safe build, or otherwise guarantee that the
1587 * context list is not alternated asynchroniously.
1589 extern JS_FRIEND_API(JSContext
*)
1590 js_NextActiveContext(JSRuntime
*, JSContext
*);
1592 #ifdef JS_THREADSAFE
1595 * Count the number of contexts entered requests on the current thread.
1598 js_CountThreadRequests(JSContext
*cx
);
1601 * This is a helper for code at can potentially run outside JS request to
1602 * ensure that the GC is not running when the function returns.
1604 * This function must be called with the GC lock held.
1607 js_WaitForGC(JSRuntime
*rt
);
1610 * If we're in one or more requests (possibly on more than one context)
1611 * running on the current thread, indicate, temporarily, that all these
1612 * requests are inactive so a possible GC can proceed on another thread.
1613 * This function returns the number of discounted requests. The number must
1614 * be passed later to js_ActivateRequestAfterGC to reactivate the requests.
1616 * This function must be called with the GC lock held.
1619 js_DiscountRequestsForGC(JSContext
*cx
);
1622 * This function must be called with the GC lock held.
1625 js_RecountRequestsAfterGC(JSRuntime
*rt
, uint32 requestDebit
);
1627 #else /* !JS_THREADSAFE */
1629 # define js_WaitForGC(rt) ((void) 0)
1634 * JSClass.resolve and watchpoint recursion damping machinery.
1637 js_StartResolving(JSContext
*cx
, JSResolvingKey
*key
, uint32 flag
,
1638 JSResolvingEntry
**entryp
);
1641 js_StopResolving(JSContext
*cx
, JSResolvingKey
*key
, uint32 flag
,
1642 JSResolvingEntry
*entry
, uint32 generation
);
1645 * Local root set management.
1647 * NB: the jsval parameters below may be properly tagged jsvals, or GC-thing
1648 * pointers cast to (jsval). This relies on JSObject's tag being zero, but
1649 * on the up side it lets us push int-jsval-encoded scopeMark values on the
1653 js_EnterLocalRootScope(JSContext
*cx
);
1655 #define js_LeaveLocalRootScope(cx) \
1656 js_LeaveLocalRootScopeWithResult(cx, JSVAL_NULL)
1659 js_LeaveLocalRootScopeWithResult(JSContext
*cx
, jsval rval
);
1662 js_ForgetLocalRoot(JSContext
*cx
, jsval v
);
1665 js_PushLocalRoot(JSContext
*cx
, JSLocalRootStack
*lrs
, jsval v
);
1668 js_TraceLocalRoots(JSTracer
*trc
, JSLocalRootStack
*lrs
);
1671 * Report an exception, which is currently realized as a printf-style format
1672 * string and its arguments.
1674 typedef enum JSErrNum
{
1675 #define MSG_DEF(name, number, count, exception, format) \
1682 extern JS_FRIEND_API(const JSErrorFormatString
*)
1683 js_GetErrorMessage(void *userRef
, const char *locale
, const uintN errorNumber
);
1687 js_ReportErrorVA(JSContext
*cx
, uintN flags
, const char *format
, va_list ap
);
1690 js_ReportErrorNumberVA(JSContext
*cx
, uintN flags
, JSErrorCallback callback
,
1691 void *userRef
, const uintN errorNumber
,
1692 JSBool charArgs
, va_list ap
);
1695 js_ExpandErrorArguments(JSContext
*cx
, JSErrorCallback callback
,
1696 void *userRef
, const uintN errorNumber
,
1697 char **message
, JSErrorReport
*reportp
,
1698 JSBool
*warningp
, JSBool charArgs
, va_list ap
);
1702 js_ReportOutOfMemory(JSContext
*cx
);
1705 * Report that cx->scriptStackQuota is exhausted.
1708 js_ReportOutOfScriptQuota(JSContext
*cx
);
1711 js_ReportOverRecursed(JSContext
*cx
);
1714 js_ReportAllocationOverflow(JSContext
*cx
);
1716 #define JS_CHECK_RECURSION(cx, onerror) \
1720 if (!JS_CHECK_STACK_SIZE(cx, stackDummy_)) { \
1721 js_ReportOverRecursed(cx); \
1727 * Report an exception using a previously composed JSErrorReport.
1728 * XXXbe remove from "friend" API
1730 extern JS_FRIEND_API(void)
1731 js_ReportErrorAgain(JSContext
*cx
, const char *message
, JSErrorReport
*report
);
1734 js_ReportIsNotDefined(JSContext
*cx
, const char *name
);
1737 * Report an attempt to access the property of a null or undefined value (v).
1740 js_ReportIsNullOrUndefined(JSContext
*cx
, intN spindex
, jsval v
,
1741 JSString
*fallback
);
1744 js_ReportMissingArg(JSContext
*cx
, jsval
*vp
, uintN arg
);
1747 * Report error using js_DecompileValueGenerator(cx, spindex, v, fallback) as
1748 * the first argument for the error message. If the error message has less
1749 * then 3 arguments, use null for arg1 or arg2.
1752 js_ReportValueErrorFlags(JSContext
*cx
, uintN flags
, const uintN errorNumber
,
1753 intN spindex
, jsval v
, JSString
*fallback
,
1754 const char *arg1
, const char *arg2
);
1756 #define js_ReportValueError(cx,errorNumber,spindex,v,fallback) \
1757 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
1758 spindex, v, fallback, NULL, NULL))
1760 #define js_ReportValueError2(cx,errorNumber,spindex,v,fallback,arg1) \
1761 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
1762 spindex, v, fallback, arg1, NULL))
1764 #define js_ReportValueError3(cx,errorNumber,spindex,v,fallback,arg1,arg2) \
1765 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
1766 spindex, v, fallback, arg1, arg2))
1768 extern JSErrorFormatString js_ErrorFormatString
[JSErr_Limit
];
1771 * See JS_SetThreadStackLimit in jsapi.c, where we check that the stack grows
1772 * in the expected direction. On Unix-y systems, JS_STACK_GROWTH_DIRECTION is
1773 * computed on the build host by jscpucfg.c and written into jsautocfg.h. The
1774 * macro is hardcoded in jscpucfg.h on Windows and Mac systems (for historical
1775 * reasons pre-dating autoconf usage).
1777 #if JS_STACK_GROWTH_DIRECTION > 0
1778 # define JS_CHECK_STACK_SIZE(cx, lval) ((jsuword)&(lval) < (cx)->stackLimit)
1780 # define JS_CHECK_STACK_SIZE(cx, lval) ((jsuword)&(lval) > (cx)->stackLimit)
1784 * If the operation callback flag was set, call the operation callback.
1785 * This macro can run the full GC. Return true if it is OK to continue and
1788 #define JS_CHECK_OPERATION_LIMIT(cx) \
1789 (!(cx)->operationCallbackFlag || js_InvokeOperationCallback(cx))
1792 * Invoke the operation callback and return false if the current execution
1793 * is to be terminated.
1796 js_InvokeOperationCallback(JSContext
*cx
);
1798 #ifndef JS_THREADSAFE
1799 # define js_TriggerAllOperationCallbacks(rt, gcLocked) \
1800 js_TriggerAllOperationCallbacks (rt)
1804 js_TriggerAllOperationCallbacks(JSRuntime
*rt
, JSBool gcLocked
);
1806 extern JSStackFrame
*
1807 js_GetScriptedCaller(JSContext
*cx
, JSStackFrame
*fp
);
1810 js_GetCurrentBytecodePC(JSContext
* cx
);
1813 js_CurrentPCIsInImacro(JSContext
*cx
);
1817 * Reconstruct the JS stack and clear cx->tracecx. We must be currently in a
1818 * _FAIL builtin from trace on cx or another context on the same thread. The
1819 * machine code for the trace remains on the C stack when js_DeepBail returns.
1821 * Implemented in jstracer.cpp.
1823 JS_FORCES_STACK
JS_FRIEND_API(void)
1824 js_DeepBail(JSContext
*cx
);
1827 static JS_FORCES_STACK JS_INLINE
void
1828 js_LeaveTrace(JSContext
*cx
)
1831 if (JS_ON_TRACE(cx
))
1836 static JS_INLINE
void
1837 js_LeaveTraceIfGlobalObject(JSContext
*cx
, JSObject
*obj
)
1839 if (!obj
->fslots
[JSSLOT_PARENT
])
1843 static JS_INLINE JSBool
1844 js_CanLeaveTrace(JSContext
*cx
)
1846 JS_ASSERT(JS_ON_TRACE(cx
));
1848 return cx
->bailExit
!= NULL
;
1855 * Get the current cx->fp, first lazily instantiating stack frames if needed.
1856 * (Do not access cx->fp directly except in JS_REQUIRES_STACK code.)
1858 * Defined in jstracer.cpp if JS_TRACER is defined.
1860 static JS_FORCES_STACK JS_INLINE JSStackFrame
*
1861 js_GetTopStackFrame(JSContext
*cx
)
1867 static JS_INLINE JSBool
1868 js_IsPropertyCacheDisabled(JSContext
*cx
)
1870 return cx
->runtime
->shapeGen
>= SHAPE_OVERFLOW_BIT
;
1873 static JS_INLINE uint32
1874 js_RegenerateShapeForGC(JSContext
*cx
)
1876 JS_ASSERT(cx
->runtime
->gcRunning
);
1877 JS_ASSERT(cx
->runtime
->gcRegenShapes
);
1880 * Under the GC, compared with js_GenerateShape, we don't need to use
1881 * atomic increments but we still must make sure that after an overflow
1882 * the shape stays such.
1884 uint32 shape
= cx
->runtime
->shapeGen
;
1885 shape
= (shape
+ 1) | (shape
& SHAPE_OVERFLOW_BIT
);
1886 cx
->runtime
->shapeGen
= shape
;
1893 * Policy that calls JSContext:: memory functions and reports errors to the
1894 * context. Since the JSContext* given on construction is stored for the
1895 * lifetime of the container, this policy may only be used for containers whose
1896 * lifetime is a shorter than the given JSContext.
1898 class ContextAllocPolicy
1903 ContextAllocPolicy(JSContext
*cx
) : mCx(cx
) {}
1904 JSContext
*context() const { return mCx
; }
1906 void *malloc(size_t bytes
) { return mCx
->malloc(bytes
); }
1907 void free(void *p
) { mCx
->free(p
); }
1908 void *realloc(void *p
, size_t bytes
) { return mCx
->realloc(p
, bytes
); }
1909 void reportAllocOverflow() const { js_ReportAllocationOverflow(mCx
); }
1914 #endif /* jscntxt_h___ */