/[jscoverage]/trunk/js/jscntxt.h
ViewVC logotype

Contents of /trunk/js/jscntxt.h

Parent Directory Parent Directory | Revision Log Revision Log


Revision 332 - (show annotations)
Thu Oct 23 19:03:33 2008 UTC (11 years, 2 months ago) by siliconforks
File MIME type: text/plain
File size: 45135 byte(s)
Add SpiderMonkey from Firefox 3.1b1.

The following directories and files were removed:
correct/, correct.js
liveconnect/
nanojit/
t/
v8/
vprof/
xpconnect/
all JavaScript files (Y.js, call.js, if.js, math-partial-sums.js, md5.js, perfect.js, trace-test.js, trace.js)


1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sw=4 et tw=78:
3 *
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6 *
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/
11 *
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.
16 *
17 * The Original Code is Mozilla Communicator client code, released
18 * March 31, 1998.
19 *
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.
24 *
25 * Contributor(s):
26 *
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.
38 *
39 * ***** END LICENSE BLOCK ***** */
40
41 #ifndef jscntxt_h___
42 #define jscntxt_h___
43 /*
44 * JS execution context.
45 */
46 #include "jsarena.h" /* Added by JSIFY */
47 #include "jsclist.h"
48 #include "jslong.h"
49 #include "jsatom.h"
50 #include "jsversion.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"
59
60 JS_BEGIN_EXTERN_C
61
62 /*
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.
67 */
68 typedef struct JSGSNCache {
69 jsbytecode *code;
70 JSDHashTable table;
71 #ifdef JS_GSNMETER
72 uint32 hits;
73 uint32 misses;
74 uint32 fills;
75 uint32 clears;
76 # define GSN_CACHE_METER(cache,cnt) (++(cache)->cnt)
77 #else
78 # define GSN_CACHE_METER(cache,cnt) /* nothing */
79 #endif
80 } JSGSNCache;
81
82 #define GSN_CACHE_CLEAR(cache) \
83 JS_BEGIN_MACRO \
84 (cache)->code = NULL; \
85 if ((cache)->table.ops) { \
86 JS_DHashTableFinish(&(cache)->table); \
87 (cache)->table.ops = NULL; \
88 } \
89 GSN_CACHE_METER(cache, clears); \
90 JS_END_MACRO
91
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)
95
96 #ifdef __cplusplus
97 namespace nanojit {
98 class Fragment;
99 class Fragmento;
100 }
101 class TraceRecorder;
102 extern "C++" { template<typename T> class Queue; }
103 typedef Queue<uint16> SlotList;
104 class TypeMap;
105
106 # define CLS(T) T*
107 #else
108 # define CLS(T) void*
109 #endif
110
111 /*
112 * Fragment quick cache entry.
113 */
114 typedef struct JSFragmentCacheEntry {
115 jsbytecode* pc;
116 CLS(nanojit::Fragment) fragment;
117 } JSFragmentCacheEntry;
118
119 #define JS_FRAGMENT_CACHE_LOG2 2
120 #define JS_FRAGMENT_CACHE_SIZE JS_BIT(JS_FRAGMENT_CACHE_LOG2)
121 #define JS_FRAGMENT_CACHE_MASK JS_BITMASK(JS_FRAGMENT_CACHE_LOG2)
122
123 /*
124 * Trace monitor. Every JSThread (if JS_THREADSAFE) or JSRuntime (if not
125 * JS_THREADSAFE) has an associated trace monitor that keeps track of loop
126 * frequencies for all JavaScript code loaded into that runtime.
127 */
128 typedef struct JSTraceMonitor {
129 /*
130 * Flag set when running (or recording) JIT-compiled code. This prevents
131 * both interpreter activation and last-ditch garbage collection when up
132 * against our runtime's memory limits. This flag also suppresses calls to
133 * JS_ReportOutOfMemory when failing due to runtime limits.
134 */
135 JSBool onTrace;
136 CLS(nanojit::Fragmento) fragmento;
137 CLS(TraceRecorder) recorder;
138 uint32 globalShape;
139 CLS(SlotList) globalSlots;
140 CLS(TypeMap) globalTypeMap;
141 JSFragmentCacheEntry fcache[JS_FRAGMENT_CACHE_SIZE];
142 jsval *recoveryDoublePool;
143 jsval *recoveryDoublePoolPtr;
144 } JSTraceMonitor;
145
146 #ifdef JS_TRACER
147 # define JS_ON_TRACE(cx) (JS_TRACE_MONITOR(cx).onTrace)
148 #else
149 # define JS_ON_TRACE(cx) JS_FALSE
150 #endif
151
152 #ifdef JS_THREADSAFE
153
154 /*
155 * Structure uniquely representing a thread. It holds thread-private data
156 * that can be accessed without a global lock.
157 */
158 struct JSThread {
159 /* Linked list of all contexts active on this thread. */
160 JSCList contextList;
161
162 /* Opaque thread-id, from NSPR's PR_GetCurrentThread(). */
163 jsword id;
164
165 /*
166 * Thread-local version of JSRuntime.gcMallocBytes to avoid taking
167 * locks on each JS_malloc.
168 */
169 uint32 gcMallocBytes;
170
171 /*
172 * Store the GSN cache in struct JSThread, not struct JSContext, both to
173 * save space and to simplify cleanup in js_GC. Any embedding (Firefox
174 * or another Gecko application) that uses many contexts per thread is
175 * unlikely to interleave js_GetSrcNote-intensive loops in the decompiler
176 * among two or more contexts running script in one thread.
177 */
178 JSGSNCache gsnCache;
179
180 /* Property cache for faster call/get/set invocation. */
181 JSPropertyCache propertyCache;
182
183 /* Trace-tree JIT recorder/interpreter state. */
184 JSTraceMonitor traceMonitor;
185
186 /* Lock-free list of scripts created by eval to garbage-collect. */
187 JSScript *scriptsToGC;
188 };
189
190 #define JS_GSN_CACHE(cx) ((cx)->thread->gsnCache)
191 #define JS_PROPERTY_CACHE(cx) ((cx)->thread->propertyCache)
192 #define JS_TRACE_MONITOR(cx) ((cx)->thread->traceMonitor)
193 #define JS_SCRIPTS_TO_GC(cx) ((cx)->thread->scriptsToGC)
194
195 extern void
196 js_ThreadDestructorCB(void *ptr);
197
198 extern JSBool
199 js_SetContextThread(JSContext *cx);
200
201 extern void
202 js_ClearContextThread(JSContext *cx);
203
204 extern JSThread *
205 js_GetCurrentThread(JSRuntime *rt);
206
207 #endif /* JS_THREADSAFE */
208
209 typedef enum JSDestroyContextMode {
210 JSDCM_NO_GC,
211 JSDCM_MAYBE_GC,
212 JSDCM_FORCE_GC,
213 JSDCM_NEW_FAILED
214 } JSDestroyContextMode;
215
216 typedef enum JSRuntimeState {
217 JSRTS_DOWN,
218 JSRTS_LAUNCHING,
219 JSRTS_UP,
220 JSRTS_LANDING
221 } JSRuntimeState;
222
223 typedef struct JSPropertyTreeEntry {
224 JSDHashEntryHdr hdr;
225 JSScopeProperty *child;
226 } JSPropertyTreeEntry;
227
228 typedef struct JSSetSlotRequest JSSetSlotRequest;
229
230 struct JSSetSlotRequest {
231 JSObject *obj; /* object containing slot to set */
232 JSObject *pobj; /* new proto or parent reference */
233 uint16 slot; /* which to set, proto or parent */
234 uint16 errnum; /* JSMSG_NO_ERROR or error result */
235 JSSetSlotRequest *next; /* next request in GC worklist */
236 };
237
238 struct JSRuntime {
239 /* Runtime state, synchronized by the stateChange/gcLock condvar/lock. */
240 JSRuntimeState state;
241
242 /* Context create/destroy callback. */
243 JSContextCallback cxCallback;
244
245 /* Garbage collector state, used by jsgc.c. */
246 JSGCChunkInfo *gcChunkList;
247 JSGCArenaList gcArenaList[GC_NUM_FREELISTS];
248 JSGCDoubleArenaList gcDoubleArenaList;
249 JSGCFreeListSet *gcFreeListsPool;
250 JSDHashTable gcRootsHash;
251 JSDHashTable *gcLocksHash;
252 jsrefcount gcKeepAtoms;
253 uint32 gcBytes;
254 uint32 gcLastBytes;
255 uint32 gcMaxBytes;
256 uint32 gcMaxMallocBytes;
257 uint32 gcEmptyArenaPoolLifespan;
258 uint32 gcLevel;
259 uint32 gcNumber;
260 JSTracer *gcMarkingTracer;
261
262 /*
263 * NB: do not pack another flag here by claiming gcPadding unless the new
264 * flag is written only by the GC thread. Atomic updates to packed bytes
265 * are not guaranteed, so stores issued by one thread may be lost due to
266 * unsynchronized read-modify-write cycles on other threads.
267 */
268 JSPackedBool gcPoke;
269 JSPackedBool gcRunning;
270 uint16 gcPadding;
271 #ifdef JS_GC_ZEAL
272 jsrefcount gcZeal;
273 #endif
274
275 JSGCCallback gcCallback;
276 uint32 gcMallocBytes;
277 JSGCArenaInfo *gcUntracedArenaStackTop;
278 #ifdef DEBUG
279 size_t gcTraceLaterCount;
280 #endif
281
282 /*
283 * Table for tracking iterators to ensure that we close iterator's state
284 * before finalizing the iterable object.
285 */
286 JSPtrTable gcIteratorTable;
287
288 /*
289 * The trace operation and its data argument to trace embedding-specific
290 * GC roots.
291 */
292 JSTraceDataOp gcExtraRootsTraceOp;
293 void *gcExtraRootsData;
294
295 /*
296 * Used to serialize cycle checks when setting __proto__ or __parent__ by
297 * requesting the GC handle the required cycle detection. If the GC hasn't
298 * been poked, it won't scan for garbage. This member is protected by
299 * rt->gcLock.
300 */
301 JSSetSlotRequest *setSlotRequests;
302
303 /* Random number generator state, used by jsmath.c. */
304 JSBool rngInitialized;
305 int64 rngMultiplier;
306 int64 rngAddend;
307 int64 rngMask;
308 int64 rngSeed;
309 jsdouble rngDscale;
310
311 /* Well-known numbers held for use by this runtime's contexts. */
312 jsdouble *jsNaN;
313 jsdouble *jsNegativeInfinity;
314 jsdouble *jsPositiveInfinity;
315
316 #ifdef JS_THREADSAFE
317 JSLock *deflatedStringCacheLock;
318 #endif
319 JSHashTable *deflatedStringCache;
320 #ifdef DEBUG
321 uint32 deflatedStringCacheBytes;
322 #endif
323
324 /*
325 * Empty and unit-length strings held for use by this runtime's contexts.
326 * The unitStrings array and its elements are created on demand.
327 */
328 JSString *emptyString;
329 JSString **unitStrings;
330
331 /* List of active contexts sharing this runtime; protected by gcLock. */
332 JSCList contextList;
333
334 /* Per runtime debug hooks -- see jsprvtd.h and jsdbgapi.h. */
335 JSDebugHooks globalDebugHooks;
336
337 /* More debugging state, see jsdbgapi.c. */
338 JSCList trapList;
339 JSCList watchPointList;
340
341 /* Client opaque pointer */
342 void *data;
343
344 #ifdef JS_THREADSAFE
345 /* These combine to interlock the GC and new requests. */
346 PRLock *gcLock;
347 PRCondVar *gcDone;
348 PRCondVar *requestDone;
349 uint32 requestCount;
350 JSThread *gcThread;
351
352 /* Lock and owning thread pointer for JS_LOCK_RUNTIME. */
353 PRLock *rtLock;
354 #ifdef DEBUG
355 jsword rtLockOwner;
356 #endif
357
358 /* Used to synchronize down/up state change; protected by gcLock. */
359 PRCondVar *stateChange;
360
361 /*
362 * State for sharing single-threaded titles, once a second thread tries to
363 * lock a title. The titleSharingDone condvar is protected by rt->gcLock
364 * to minimize number of locks taken in JS_EndRequest.
365 *
366 * The titleSharingTodo linked list is likewise "global" per runtime, not
367 * one-list-per-context, to conserve space over all contexts, optimizing
368 * for the likely case that titles become shared rarely, and among a very
369 * small set of threads (contexts).
370 */
371 PRCondVar *titleSharingDone;
372 JSTitle *titleSharingTodo;
373
374 /*
375 * Magic terminator for the rt->titleSharingTodo linked list, threaded through
376 * title->u.link. This hack allows us to test whether a title is on the list
377 * by asking whether title->u.link is non-null. We use a large, likely bogus
378 * pointer here to distinguish this value from any valid u.count (small int)
379 * value.
380 */
381 #define NO_TITLE_SHARING_TODO ((JSTitle *) 0xfeedbeef)
382
383 /*
384 * Lock serializing trapList and watchPointList accesses, and count of all
385 * mutations to trapList and watchPointList made by debugger threads. To
386 * keep the code simple, we define debuggerMutations for the thread-unsafe
387 * case too.
388 */
389 PRLock *debuggerLock;
390 #endif /* JS_THREADSAFE */
391 uint32 debuggerMutations;
392
393 /*
394 * Security callbacks set on the runtime are used by each context unless
395 * an override is set on the context.
396 */
397 JSSecurityCallbacks *securityCallbacks;
398
399 /*
400 * Shared scope property tree, and arena-pool for allocating its nodes.
401 * The propertyRemovals counter is incremented for every js_ClearScope,
402 * and for each js_RemoveScopeProperty that frees a slot in an object.
403 * See js_NativeGet and js_NativeSet in jsobj.c.
404 */
405 JSDHashTable propertyTreeHash;
406 JSScopeProperty *propertyFreeList;
407 JSArenaPool propertyArenaPool;
408 int32 propertyRemovals;
409
410 /* Script filename table. */
411 struct JSHashTable *scriptFilenameTable;
412 JSCList scriptFilenamePrefixes;
413 #ifdef JS_THREADSAFE
414 PRLock *scriptFilenameTableLock;
415 #endif
416
417 /* Number localization, used by jsnum.c */
418 const char *thousandsSeparator;
419 const char *decimalSeparator;
420 const char *numGrouping;
421
422 /*
423 * Weak references to lazily-created, well-known XML singletons.
424 *
425 * NB: Singleton objects must be carefully disconnected from the rest of
426 * the object graph usually associated with a JSContext's global object,
427 * including the set of standard class objects. See jsxml.c for details.
428 */
429 JSObject *anynameObject;
430 JSObject *functionNamespaceObject;
431
432 /*
433 * A helper list for the GC, so it can mark native iterator states. See
434 * js_TraceNativeEnumerators for details.
435 */
436 JSNativeEnumerator *nativeEnumerators;
437
438 #ifndef JS_THREADSAFE
439 /*
440 * For thread-unsafe embeddings, the GSN cache lives in the runtime and
441 * not each context, since we expect it to be filled once when decompiling
442 * a longer script, then hit repeatedly as js_GetSrcNote is called during
443 * the decompiler activation that filled it.
444 */
445 JSGSNCache gsnCache;
446
447 /* Property cache for faster call/get/set invocation. */
448 JSPropertyCache propertyCache;
449
450 /* Trace-tree JIT recorder/interpreter state. */
451 JSTraceMonitor traceMonitor;
452
453 /* Lock-free list of scripts created by eval to garbage-collect. */
454 JSScript *scriptsToGC;
455
456 #define JS_GSN_CACHE(cx) ((cx)->runtime->gsnCache)
457 #define JS_PROPERTY_CACHE(cx) ((cx)->runtime->propertyCache)
458 #define JS_TRACE_MONITOR(cx) ((cx)->runtime->traceMonitor)
459 #define JS_SCRIPTS_TO_GC(cx) ((cx)->runtime->scriptsToGC)
460 #endif
461
462 /*
463 * Object shape (property cache structural type) identifier generator.
464 *
465 * Type 0 stands for the empty scope, and must not be regenerated due to
466 * uint32 wrap-around. Since we use atomic pre-increment, the initial
467 * value for the first typed non-empty scope will be 1.
468 *
469 * The GC compresses live types, minimizing rt->shapeGen in the process.
470 * If this counter overflows into SHAPE_OVERFLOW_BIT (in jsinterp.h), the
471 * GC will disable property caches for all threads, to avoid aliasing two
472 * different types. Updated by js_GenerateShape (in jsinterp.c).
473 */
474 uint32 shapeGen;
475
476 /* Literal table maintained by jsatom.c functions. */
477 JSAtomState atomState;
478
479 /*
480 * Cache of reusable JSNativeEnumerators mapped by shape identifiers (as
481 * stored in scope->shape). This cache is nulled by the GC and protected
482 * by gcLock.
483 */
484 #define NATIVE_ENUM_CACHE_LOG2 8
485 #define NATIVE_ENUM_CACHE_MASK JS_BITMASK(NATIVE_ENUM_CACHE_LOG2)
486 #define NATIVE_ENUM_CACHE_SIZE JS_BIT(NATIVE_ENUM_CACHE_LOG2)
487
488 #define NATIVE_ENUM_CACHE_HASH(shape) \
489 ((((shape) >> NATIVE_ENUM_CACHE_LOG2) ^ (shape)) & NATIVE_ENUM_CACHE_MASK)
490
491 jsuword nativeEnumCache[NATIVE_ENUM_CACHE_SIZE];
492
493 /*
494 * Various metering fields are defined at the end of JSRuntime. In this
495 * way there is no need to recompile all the code that refers to other
496 * fields of JSRuntime after enabling the corresponding metering macro.
497 */
498 #ifdef JS_DUMP_ENUM_CACHE_STATS
499 int32 nativeEnumProbes;
500 int32 nativeEnumMisses;
501 # define ENUM_CACHE_METER(name) JS_ATOMIC_INCREMENT(&cx->runtime->name)
502 #else
503 # define ENUM_CACHE_METER(name) ((void) 0)
504 #endif
505
506 #ifdef JS_DUMP_LOOP_STATS
507 /* Loop statistics, to trigger trace recording and compiling. */
508 JSBasicStats loopStats;
509 #endif
510
511 #if defined DEBUG || defined JS_DUMP_PROPTREE_STATS
512 /* Function invocation metering. */
513 jsrefcount inlineCalls;
514 jsrefcount nativeCalls;
515 jsrefcount nonInlineCalls;
516 jsrefcount constructs;
517
518 /* Title lock and scope property metering. */
519 jsrefcount claimAttempts;
520 jsrefcount claimedTitles;
521 jsrefcount deadContexts;
522 jsrefcount deadlocksAvoided;
523 jsrefcount liveScopes;
524 jsrefcount sharedTitles;
525 jsrefcount totalScopes;
526 jsrefcount liveScopeProps;
527 jsrefcount liveScopePropsPreSweep;
528 jsrefcount totalScopeProps;
529 jsrefcount livePropTreeNodes;
530 jsrefcount duplicatePropTreeNodes;
531 jsrefcount totalPropTreeNodes;
532 jsrefcount propTreeKidsChunks;
533 jsrefcount middleDeleteFixups;
534
535 /* String instrumentation. */
536 jsrefcount liveStrings;
537 jsrefcount totalStrings;
538 jsrefcount liveDependentStrings;
539 jsrefcount totalDependentStrings;
540 jsrefcount badUndependStrings;
541 double lengthSum;
542 double lengthSquaredSum;
543 double strdepLengthSum;
544 double strdepLengthSquaredSum;
545 #endif /* DEBUG || JS_DUMP_PROPTREE_STATS */
546
547 #ifdef JS_SCOPE_DEPTH_METER
548 /*
549 * Stats on runtime prototype chain lookups and scope chain depths, i.e.,
550 * counts of objects traversed on a chain until the wanted id is found.
551 */
552 JSBasicStats protoLookupDepthStats;
553 JSBasicStats scopeSearchDepthStats;
554
555 /*
556 * Stats on compile-time host environment and lexical scope chain lengths
557 * (maximum depths).
558 */
559 JSBasicStats hostenvScopeDepthStats;
560 JSBasicStats lexicalScopeDepthStats;
561 #endif
562
563 #ifdef JS_GCMETER
564 JSGCStats gcStats;
565 #endif
566 };
567
568 #ifdef DEBUG
569 # define JS_RUNTIME_METER(rt, which) JS_ATOMIC_INCREMENT(&(rt)->which)
570 # define JS_RUNTIME_UNMETER(rt, which) JS_ATOMIC_DECREMENT(&(rt)->which)
571 #else
572 # define JS_RUNTIME_METER(rt, which) /* nothing */
573 # define JS_RUNTIME_UNMETER(rt, which) /* nothing */
574 #endif
575
576 #define JS_KEEP_ATOMS(rt) JS_ATOMIC_INCREMENT(&(rt)->gcKeepAtoms);
577 #define JS_UNKEEP_ATOMS(rt) JS_ATOMIC_DECREMENT(&(rt)->gcKeepAtoms);
578
579 #ifdef JS_ARGUMENT_FORMATTER_DEFINED
580 /*
581 * Linked list mapping format strings for JS_{Convert,Push}Arguments{,VA} to
582 * formatter functions. Elements are sorted in non-increasing format string
583 * length order.
584 */
585 struct JSArgumentFormatMap {
586 const char *format;
587 size_t length;
588 JSArgumentFormatter formatter;
589 JSArgumentFormatMap *next;
590 };
591 #endif
592
593 struct JSStackHeader {
594 uintN nslots;
595 JSStackHeader *down;
596 };
597
598 #define JS_STACK_SEGMENT(sh) ((jsval *)(sh) + 2)
599
600 /*
601 * Key and entry types for the JSContext.resolvingTable hash table, typedef'd
602 * here because all consumers need to see these declarations (and not just the
603 * typedef names, as would be the case for an opaque pointer-to-typedef'd-type
604 * declaration), along with cx->resolvingTable.
605 */
606 typedef struct JSResolvingKey {
607 JSObject *obj;
608 jsid id;
609 } JSResolvingKey;
610
611 typedef struct JSResolvingEntry {
612 JSDHashEntryHdr hdr;
613 JSResolvingKey key;
614 uint32 flags;
615 } JSResolvingEntry;
616
617 #define JSRESFLAG_LOOKUP 0x1 /* resolving id from lookup */
618 #define JSRESFLAG_WATCH 0x2 /* resolving id from watch */
619
620 typedef struct JSLocalRootChunk JSLocalRootChunk;
621
622 #define JSLRS_CHUNK_SHIFT 8
623 #define JSLRS_CHUNK_SIZE JS_BIT(JSLRS_CHUNK_SHIFT)
624 #define JSLRS_CHUNK_MASK JS_BITMASK(JSLRS_CHUNK_SHIFT)
625
626 struct JSLocalRootChunk {
627 jsval roots[JSLRS_CHUNK_SIZE];
628 JSLocalRootChunk *down;
629 };
630
631 typedef struct JSLocalRootStack {
632 uint32 scopeMark;
633 uint32 rootCount;
634 JSLocalRootChunk *topChunk;
635 JSLocalRootChunk firstChunk;
636 } JSLocalRootStack;
637
638 #define JSLRS_NULL_MARK ((uint32) -1)
639
640 /*
641 * Macros to push/pop JSTempValueRooter instances to context-linked stack of
642 * temporary GC roots. If you need to protect a result value that flows out of
643 * a C function across several layers of other functions, use the
644 * js_LeaveLocalRootScopeWithResult internal API (see further below) instead.
645 *
646 * The macros also provide a simple way to get a single rooted pointer via
647 * JS_PUSH_TEMP_ROOT_<KIND>(cx, NULL, &tvr). Then &tvr.u.<kind> gives the
648 * necessary pointer.
649 *
650 * JSTempValueRooter.count defines the type of the rooted value referenced by
651 * JSTempValueRooter.u union of type JSTempValueUnion. When count is positive
652 * or zero, u.array points to a vector of jsvals. Otherwise it must be one of
653 * the following constants:
654 */
655 #define JSTVU_SINGLE (-1) /* u.value or u.<gcthing> is single jsval
656 or GC-thing */
657 #define JSTVU_TRACE (-2) /* u.trace is a hook to trace a custom
658 * structure */
659 #define JSTVU_SPROP (-3) /* u.sprop roots property tree node */
660 #define JSTVU_WEAK_ROOTS (-4) /* u.weakRoots points to saved weak roots */
661 #define JSTVU_PARSE_CONTEXT (-5) /* u.parseContext roots JSParseContext* */
662 #define JSTVU_SCRIPT (-6) /* u.script roots JSScript* */
663
664 /*
665 * Here single JSTVU_SINGLE covers both jsval and pointers to any GC-thing via
666 * reinterpreting the thing as JSVAL_OBJECT. It works because the GC-thing is
667 * aligned on a 0 mod 8 boundary, and object has the 0 jsval tag. So any
668 * GC-thing may be tagged as if it were an object and untagged, if it's then
669 * used only as an opaque pointer until discriminated by other means than tag
670 * bits. This is how, for example, js_GetGCThingTraceKind uses its |thing|
671 * parameter -- it consults GC-thing flags stored separately from the thing to
672 * decide the kind of thing.
673 *
674 * The following checks that this type-punning is possible.
675 */
676 JS_STATIC_ASSERT(sizeof(JSTempValueUnion) == sizeof(jsval));
677 JS_STATIC_ASSERT(sizeof(JSTempValueUnion) == sizeof(void *));
678
679 #define JS_PUSH_TEMP_ROOT_COMMON(cx,x,tvr,cnt,kind) \
680 JS_BEGIN_MACRO \
681 JS_ASSERT((cx)->tempValueRooters != (tvr)); \
682 (tvr)->count = (cnt); \
683 (tvr)->u.kind = (x); \
684 (tvr)->down = (cx)->tempValueRooters; \
685 (cx)->tempValueRooters = (tvr); \
686 JS_END_MACRO
687
688 #define JS_POP_TEMP_ROOT(cx,tvr) \
689 JS_BEGIN_MACRO \
690 JS_ASSERT((cx)->tempValueRooters == (tvr)); \
691 (cx)->tempValueRooters = (tvr)->down; \
692 JS_END_MACRO
693
694 #define JS_PUSH_TEMP_ROOT(cx,cnt,arr,tvr) \
695 JS_BEGIN_MACRO \
696 JS_ASSERT((int)(cnt) >= 0); \
697 JS_PUSH_TEMP_ROOT_COMMON(cx, arr, tvr, (ptrdiff_t) (cnt), array); \
698 JS_END_MACRO
699
700 #define JS_PUSH_SINGLE_TEMP_ROOT(cx,val,tvr) \
701 JS_PUSH_TEMP_ROOT_COMMON(cx, val, tvr, JSTVU_SINGLE, value)
702
703 #define JS_PUSH_TEMP_ROOT_OBJECT(cx,obj,tvr) \
704 JS_PUSH_TEMP_ROOT_COMMON(cx, obj, tvr, JSTVU_SINGLE, object)
705
706 #define JS_PUSH_TEMP_ROOT_STRING(cx,str,tvr) \
707 JS_PUSH_TEMP_ROOT_COMMON(cx, str, tvr, JSTVU_SINGLE, string)
708
709 #define JS_PUSH_TEMP_ROOT_XML(cx,xml_,tvr) \
710 JS_PUSH_TEMP_ROOT_COMMON(cx, xml_, tvr, JSTVU_SINGLE, xml)
711
712 #define JS_PUSH_TEMP_ROOT_TRACE(cx,trace_,tvr) \
713 JS_PUSH_TEMP_ROOT_COMMON(cx, trace_, tvr, JSTVU_TRACE, trace)
714
715 #define JS_PUSH_TEMP_ROOT_SPROP(cx,sprop_,tvr) \
716 JS_PUSH_TEMP_ROOT_COMMON(cx, sprop_, tvr, JSTVU_SPROP, sprop)
717
718 #define JS_PUSH_TEMP_ROOT_WEAK_COPY(cx,weakRoots_,tvr) \
719 JS_PUSH_TEMP_ROOT_COMMON(cx, weakRoots_, tvr, JSTVU_WEAK_ROOTS, weakRoots)
720
721 #define JS_PUSH_TEMP_ROOT_PARSE_CONTEXT(cx,pc,tvr) \
722 JS_PUSH_TEMP_ROOT_COMMON(cx, pc, tvr, JSTVU_PARSE_CONTEXT, parseContext)
723
724 #define JS_PUSH_TEMP_ROOT_SCRIPT(cx,script_,tvr) \
725 JS_PUSH_TEMP_ROOT_COMMON(cx, script_, tvr, JSTVU_SCRIPT, script)
726
727
728 #define JSRESOLVE_INFER 0xffff /* infer bits from current bytecode */
729
730 struct JSContext {
731 /* JSRuntime contextList linkage. */
732 JSCList links;
733
734 /*
735 * Operation count. It is declared early in the structure as a frequently
736 * accessed field.
737 */
738 int32 operationCount;
739
740 #if JS_HAS_XML_SUPPORT
741 /*
742 * Bit-set formed from binary exponentials of the XML_* tiny-ids defined
743 * for boolean settings in jsxml.c, plus an XSF_CACHE_VALID bit. Together
744 * these act as a cache of the boolean XML.ignore* and XML.prettyPrinting
745 * property values associated with this context's global object.
746 */
747 uint8 xmlSettingFlags;
748 uint8 padding;
749 #else
750 uint16 padding;
751 #endif
752
753 /*
754 * Classic Algol "display" static link optimization.
755 */
756 #define JS_DISPLAY_SIZE 16
757
758 JSStackFrame *display[JS_DISPLAY_SIZE];
759
760 /* Runtime version control identifier. */
761 uint16 version;
762
763 /* Per-context options. */
764 uint32 options; /* see jsapi.h for JSOPTION_* */
765
766 /* Locale specific callbacks for string conversion. */
767 JSLocaleCallbacks *localeCallbacks;
768
769 /*
770 * cx->resolvingTable is non-null and non-empty if we are initializing
771 * standard classes lazily, or if we are otherwise recursing indirectly
772 * from js_LookupProperty through a JSClass.resolve hook. It is used to
773 * limit runaway recursion (see jsapi.c and jsobj.c).
774 */
775 JSDHashTable *resolvingTable;
776
777 #if JS_HAS_LVALUE_RETURN
778 /*
779 * Secondary return value from native method called on the left-hand side
780 * of an assignment operator. The native should store the object in which
781 * to set a property in *rval, and return the property's id expressed as a
782 * jsval by calling JS_SetCallReturnValue2(cx, idval).
783 */
784 jsval rval2;
785 JSPackedBool rval2set;
786 #endif
787
788 /*
789 * True if generating an error, to prevent runaway recursion.
790 * NB: generatingError packs with rval2set, #if JS_HAS_LVALUE_RETURN;
791 * with insideGCMarkCallback and with throwing below.
792 */
793 JSPackedBool generatingError;
794
795 /* Flag to indicate that we run inside gcCallback(cx, JSGC_MARK_END). */
796 JSPackedBool insideGCMarkCallback;
797
798 /* Exception state -- the exception member is a GC root by definition. */
799 JSPackedBool throwing; /* is there a pending exception? */
800 jsval exception; /* most-recently-thrown exception */
801
802 /* Limit pointer for checking native stack consumption during recursion. */
803 jsuword stackLimit;
804
805 /* Quota on the size of arenas used to compile and execute scripts. */
806 size_t scriptStackQuota;
807
808 /* Data shared by threads in an address space. */
809 JSRuntime *runtime;
810
811 /* Stack arena pool and frame pointer register. */
812 JSArenaPool stackPool;
813 JSStackFrame *fp;
814
815 /* Temporary arena pool used while compiling and decompiling. */
816 JSArenaPool tempPool;
817
818 /* Top-level object and pointer to top stack frame's scope chain. */
819 JSObject *globalObject;
820
821 /* Storage to root recently allocated GC things and script result. */
822 JSWeakRoots weakRoots;
823
824 /* Regular expression class statics (XXX not shared globally). */
825 JSRegExpStatics regExpStatics;
826
827 /* State for object and array toSource conversion. */
828 JSSharpObjectMap sharpObjectMap;
829
830 /* Argument formatter support for JS_{Convert,Push}Arguments{,VA}. */
831 JSArgumentFormatMap *argumentFormatMap;
832
833 /* Last message string and trace file for debugging. */
834 char *lastMessage;
835 #ifdef DEBUG
836 void *tracefp;
837 #endif
838
839 /* Per-context optional error reporter. */
840 JSErrorReporter errorReporter;
841
842 /*
843 * Flag indicating that the operation callback is set. When the flag is 0
844 * but operationCallback is not null, operationCallback stores the branch
845 * callback.
846 */
847 uint32 operationCallbackIsSet : 1;
848 uint32 operationLimit : 31;
849 JSOperationCallback operationCallback;
850
851 /* Interpreter activation count. */
852 uintN interpLevel;
853
854 /* Client opaque pointer */
855 void *data;
856
857 /* GC and thread-safe state. */
858 JSStackFrame *dormantFrameChain; /* dormant stack frame to scan */
859 #ifdef JS_THREADSAFE
860 JSThread *thread;
861 jsrefcount requestDepth;
862 /* Same as requestDepth but ignoring JS_SuspendRequest/JS_ResumeRequest */
863 jsrefcount outstandingRequests;
864 JSTitle *titleToShare; /* weak reference, see jslock.c */
865 JSTitle *lockedSealedTitle; /* weak ref, for low-cost sealed
866 title locking */
867 JSCList threadLinks; /* JSThread contextList linkage */
868
869 #define CX_FROM_THREAD_LINKS(tl) \
870 ((JSContext *)((char *)(tl) - offsetof(JSContext, threadLinks)))
871 #endif
872
873 /* PDL of stack headers describing stack slots not rooted by argv, etc. */
874 JSStackHeader *stackHeaders;
875
876 /* Optional stack of heap-allocated scoped local GC roots. */
877 JSLocalRootStack *localRootStack;
878
879 /* Stack of thread-stack-allocated temporary GC roots. */
880 JSTempValueRooter *tempValueRooters;
881
882 #ifdef JS_THREADSAFE
883 JSGCFreeListSet *gcLocalFreeLists;
884 #endif
885
886 /* List of pre-allocated doubles. */
887 JSGCDoubleCell *doubleFreeList;
888
889 /* Debug hooks associated with the current context. */
890 JSDebugHooks *debugHooks;
891
892 /* Security callbacks that override any defined on the runtime. */
893 JSSecurityCallbacks *securityCallbacks;
894
895 /* Pinned regexp pool used for regular expressions. */
896 JSArenaPool regexpPool;
897
898 /* Stored here to avoid passing it around as a parameter. */
899 uintN resolveFlags;
900 };
901
902 #ifdef JS_THREADSAFE
903 # define JS_THREAD_ID(cx) ((cx)->thread ? (cx)->thread->id : 0)
904 #endif
905
906 #ifdef __cplusplus
907 /* FIXME(bug 332648): Move this into a public header. */
908 class JSAutoTempValueRooter
909 {
910 public:
911 JSAutoTempValueRooter(JSContext *cx, size_t len, jsval *vec)
912 : mContext(cx) {
913 JS_PUSH_TEMP_ROOT(mContext, len, vec, &mTvr);
914 }
915 JSAutoTempValueRooter(JSContext *cx, jsval v)
916 : mContext(cx) {
917 JS_PUSH_SINGLE_TEMP_ROOT(mContext, v, &mTvr);
918 }
919
920 ~JSAutoTempValueRooter() {
921 JS_POP_TEMP_ROOT(mContext, &mTvr);
922 }
923
924 private:
925 #ifndef AIX
926 static void *operator new(size_t);
927 static void operator delete(void *, size_t);
928 #endif
929
930 JSContext *mContext;
931 JSTempValueRooter mTvr;
932 };
933
934 class JSAutoResolveFlags
935 {
936 public:
937 JSAutoResolveFlags(JSContext *cx, uintN flags)
938 : mContext(cx), mSaved(cx->resolveFlags) {
939 cx->resolveFlags = flags;
940 }
941
942 ~JSAutoResolveFlags() { mContext->resolveFlags = mSaved; }
943
944 private:
945 JSContext *mContext;
946 uintN mSaved;
947 };
948 #endif
949
950 /*
951 * Slightly more readable macros for testing per-context option settings (also
952 * to hide bitset implementation detail).
953 *
954 * JSOPTION_XML must be handled specially in order to propagate from compile-
955 * to run-time (from cx->options to script->version/cx->version). To do that,
956 * we copy JSOPTION_XML from cx->options into cx->version as JSVERSION_HAS_XML
957 * whenever options are set, and preserve this XML flag across version number
958 * changes done via the JS_SetVersion API.
959 *
960 * But when executing a script or scripted function, the interpreter changes
961 * cx->version, including the XML flag, to script->version. Thus JSOPTION_XML
962 * is a compile-time option that causes a run-time version change during each
963 * activation of the compiled script. That version change has the effect of
964 * changing JS_HAS_XML_OPTION, so that any compiling done via eval enables XML
965 * support. If an XML-enabled script or function calls a non-XML function,
966 * the flag bit will be cleared during the callee's activation.
967 *
968 * Note that JS_SetVersion API calls never pass JSVERSION_HAS_XML or'd into
969 * that API's version parameter.
970 *
971 * Note also that script->version must contain this XML option flag in order
972 * for XDR'ed scripts to serialize and deserialize with that option preserved
973 * for detection at run-time. We can't copy other compile-time options into
974 * script->version because that would break backward compatibility (certain
975 * other options, e.g. JSOPTION_VAROBJFIX, are analogous to JSOPTION_XML).
976 */
977 #define JS_HAS_OPTION(cx,option) (((cx)->options & (option)) != 0)
978 #define JS_HAS_STRICT_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_STRICT)
979 #define JS_HAS_WERROR_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_WERROR)
980 #define JS_HAS_COMPILE_N_GO_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_COMPILE_N_GO)
981 #define JS_HAS_ATLINE_OPTION(cx) JS_HAS_OPTION(cx, JSOPTION_ATLINE)
982
983 #define JSVERSION_MASK 0x0FFF /* see JSVersion in jspubtd.h */
984 #define JSVERSION_HAS_XML 0x1000 /* flag induced by XML option */
985
986 #define JSVERSION_NUMBER(cx) ((JSVersion)((cx)->version & \
987 JSVERSION_MASK))
988 #define JS_HAS_XML_OPTION(cx) ((cx)->version & JSVERSION_HAS_XML || \
989 JSVERSION_NUMBER(cx) >= JSVERSION_1_6)
990
991 /*
992 * Initialize a library-wide thread private data index, and remember that it
993 * has already been done, so that it happens only once ever. Returns true on
994 * success.
995 */
996 extern JSBool
997 js_InitThreadPrivateIndex(void (*ptr)(void *));
998
999 /*
1000 * Common subroutine of JS_SetVersion and js_SetVersion, to update per-context
1001 * data that depends on version.
1002 */
1003 extern void
1004 js_OnVersionChange(JSContext *cx);
1005
1006 /*
1007 * Unlike the JS_SetVersion API, this function stores JSVERSION_HAS_XML and
1008 * any future non-version-number flags induced by compiler options.
1009 */
1010 extern void
1011 js_SetVersion(JSContext *cx, JSVersion version);
1012
1013 /*
1014 * Create and destroy functions for JSContext, which is manually allocated
1015 * and exclusively owned.
1016 */
1017 extern JSContext *
1018 js_NewContext(JSRuntime *rt, size_t stackChunkSize);
1019
1020 extern void
1021 js_DestroyContext(JSContext *cx, JSDestroyContextMode mode);
1022
1023 /*
1024 * Return true if cx points to a context in rt->contextList, else return false.
1025 * NB: the caller (see jslock.c:ClaimTitle) must hold rt->gcLock.
1026 */
1027 extern JSBool
1028 js_ValidContextPointer(JSRuntime *rt, JSContext *cx);
1029
1030 /*
1031 * If unlocked, acquire and release rt->gcLock around *iterp update; otherwise
1032 * the caller must be holding rt->gcLock.
1033 */
1034 extern JSContext *
1035 js_ContextIterator(JSRuntime *rt, JSBool unlocked, JSContext **iterp);
1036
1037 /*
1038 * JSClass.resolve and watchpoint recursion damping machinery.
1039 */
1040 extern JSBool
1041 js_StartResolving(JSContext *cx, JSResolvingKey *key, uint32 flag,
1042 JSResolvingEntry **entryp);
1043
1044 extern void
1045 js_StopResolving(JSContext *cx, JSResolvingKey *key, uint32 flag,
1046 JSResolvingEntry *entry, uint32 generation);
1047
1048 /*
1049 * Local root set management.
1050 *
1051 * NB: the jsval parameters below may be properly tagged jsvals, or GC-thing
1052 * pointers cast to (jsval). This relies on JSObject's tag being zero, but
1053 * on the up side it lets us push int-jsval-encoded scopeMark values on the
1054 * local root stack.
1055 */
1056 extern JSBool
1057 js_EnterLocalRootScope(JSContext *cx);
1058
1059 #define js_LeaveLocalRootScope(cx) \
1060 js_LeaveLocalRootScopeWithResult(cx, JSVAL_NULL)
1061
1062 extern void
1063 js_LeaveLocalRootScopeWithResult(JSContext *cx, jsval rval);
1064
1065 extern void
1066 js_ForgetLocalRoot(JSContext *cx, jsval v);
1067
1068 extern int
1069 js_PushLocalRoot(JSContext *cx, JSLocalRootStack *lrs, jsval v);
1070
1071 extern void
1072 js_TraceLocalRoots(JSTracer *trc, JSLocalRootStack *lrs);
1073
1074 /*
1075 * Report an exception, which is currently realized as a printf-style format
1076 * string and its arguments.
1077 */
1078 typedef enum JSErrNum {
1079 #define MSG_DEF(name, number, count, exception, format) \
1080 name = number,
1081 #include "js.msg"
1082 #undef MSG_DEF
1083 JSErr_Limit
1084 } JSErrNum;
1085
1086 extern JS_FRIEND_API(const JSErrorFormatString *)
1087 js_GetErrorMessage(void *userRef, const char *locale, const uintN errorNumber);
1088
1089 #ifdef va_start
1090 extern JSBool
1091 js_ReportErrorVA(JSContext *cx, uintN flags, const char *format, va_list ap);
1092
1093 extern JSBool
1094 js_ReportErrorNumberVA(JSContext *cx, uintN flags, JSErrorCallback callback,
1095 void *userRef, const uintN errorNumber,
1096 JSBool charArgs, va_list ap);
1097
1098 extern JSBool
1099 js_ExpandErrorArguments(JSContext *cx, JSErrorCallback callback,
1100 void *userRef, const uintN errorNumber,
1101 char **message, JSErrorReport *reportp,
1102 JSBool *warningp, JSBool charArgs, va_list ap);
1103 #endif
1104
1105 extern void
1106 js_ReportOutOfMemory(JSContext *cx);
1107
1108 /*
1109 * Report that cx->scriptStackQuota is exhausted.
1110 */
1111 extern void
1112 js_ReportOutOfScriptQuota(JSContext *cx);
1113
1114 extern void
1115 js_ReportOverRecursed(JSContext *cx);
1116
1117 extern void
1118 js_ReportAllocationOverflow(JSContext *cx);
1119
1120 #define JS_CHECK_RECURSION(cx, onerror) \
1121 JS_BEGIN_MACRO \
1122 int stackDummy_; \
1123 \
1124 if (!JS_CHECK_STACK_SIZE(cx, stackDummy_)) { \
1125 js_ReportOverRecursed(cx); \
1126 onerror; \
1127 } \
1128 JS_END_MACRO
1129
1130 /*
1131 * Report an exception using a previously composed JSErrorReport.
1132 * XXXbe remove from "friend" API
1133 */
1134 extern JS_FRIEND_API(void)
1135 js_ReportErrorAgain(JSContext *cx, const char *message, JSErrorReport *report);
1136
1137 extern void
1138 js_ReportIsNotDefined(JSContext *cx, const char *name);
1139
1140 /*
1141 * Report an attempt to access the property of a null or undefined value (v).
1142 */
1143 extern JSBool
1144 js_ReportIsNullOrUndefined(JSContext *cx, intN spindex, jsval v,
1145 JSString *fallback);
1146
1147 extern void
1148 js_ReportMissingArg(JSContext *cx, jsval *vp, uintN arg);
1149
1150 /*
1151 * Report error using js_DecompileValueGenerator(cx, spindex, v, fallback) as
1152 * the first argument for the error message. If the error message has less
1153 * then 3 arguments, use null for arg1 or arg2.
1154 */
1155 extern JSBool
1156 js_ReportValueErrorFlags(JSContext *cx, uintN flags, const uintN errorNumber,
1157 intN spindex, jsval v, JSString *fallback,
1158 const char *arg1, const char *arg2);
1159
1160 #define js_ReportValueError(cx,errorNumber,spindex,v,fallback) \
1161 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
1162 spindex, v, fallback, NULL, NULL))
1163
1164 #define js_ReportValueError2(cx,errorNumber,spindex,v,fallback,arg1) \
1165 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
1166 spindex, v, fallback, arg1, NULL))
1167
1168 #define js_ReportValueError3(cx,errorNumber,spindex,v,fallback,arg1,arg2) \
1169 ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \
1170 spindex, v, fallback, arg1, arg2))
1171
1172 extern JSErrorFormatString js_ErrorFormatString[JSErr_Limit];
1173
1174 /*
1175 * See JS_SetThreadStackLimit in jsapi.c, where we check that the stack grows
1176 * in the expected direction. On Unix-y systems, JS_STACK_GROWTH_DIRECTION is
1177 * computed on the build host by jscpucfg.c and written into jsautocfg.h. The
1178 * macro is hardcoded in jscpucfg.h on Windows and Mac systems (for historical
1179 * reasons pre-dating autoconf usage).
1180 */
1181 #if JS_STACK_GROWTH_DIRECTION > 0
1182 # define JS_CHECK_STACK_SIZE(cx, lval) ((jsuword)&(lval) < (cx)->stackLimit)
1183 #else
1184 # define JS_CHECK_STACK_SIZE(cx, lval) ((jsuword)&(lval) > (cx)->stackLimit)
1185 #endif
1186
1187 /*
1188 * Update the operation counter according to the given weight and call the
1189 * operation callback when we reach the operation limit. To make this
1190 * frequently executed macro faster we decrease the counter from
1191 * JSContext.operationLimit and compare against zero to check the limit.
1192 *
1193 * This macro can run the full GC. Return true if it is OK to continue and
1194 * false otherwise.
1195 */
1196 #define JS_CHECK_OPERATION_LIMIT(cx, weight) \
1197 (JS_CHECK_OPERATION_WEIGHT(weight), \
1198 (((cx)->operationCount -= (weight)) > 0 || js_ResetOperationCount(cx)))
1199
1200 /*
1201 * A version of JS_CHECK_OPERATION_LIMIT that just updates the operation count
1202 * without calling the operation callback or any other API. This macro resets
1203 * the count to 0 when it becomes negative to prevent a wrap-around when the
1204 * macro is called repeatably.
1205 */
1206 #define JS_COUNT_OPERATION(cx, weight) \
1207 ((void)(JS_CHECK_OPERATION_WEIGHT(weight), \
1208 (cx)->operationCount = ((cx)->operationCount > 0) \
1209 ? (cx)->operationCount - (weight) \
1210 : 0))
1211
1212 /*
1213 * The implementation of the above macros assumes that subtracting weights
1214 * twice from a positive number does not wrap-around INT32_MIN.
1215 */
1216 #define JS_CHECK_OPERATION_WEIGHT(weight) \
1217 (JS_ASSERT((uint32) (weight) > 0), \
1218 JS_ASSERT((uint32) (weight) < JS_BIT(30)))
1219
1220 /* Relative operations weights. */
1221 #define JSOW_JUMP 1
1222 #define JSOW_ALLOCATION 100
1223 #define JSOW_LOOKUP_PROPERTY 5
1224 #define JSOW_GET_PROPERTY 10
1225 #define JSOW_SET_PROPERTY 20
1226 #define JSOW_NEW_PROPERTY 200
1227 #define JSOW_DELETE_PROPERTY 30
1228 #define JSOW_ENTER_SHARP JS_OPERATION_WEIGHT_BASE
1229 #define JSOW_SCRIPT_JUMP JS_OPERATION_WEIGHT_BASE
1230
1231 /*
1232 * Reset the operation count and call the operation callback assuming that the
1233 * operation limit is reached.
1234 */
1235 extern JSBool
1236 js_ResetOperationCount(JSContext *cx);
1237
1238 JS_END_EXTERN_C
1239
1240 #endif /* jscntxt_h___ */

  ViewVC Help
Powered by ViewVC 1.1.24