/js/lib/Socket.IO-node/support/expresso/deps/jscoverage/js/jscntxt.h

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs · C++ Header · 1247 lines · 611 code · 199 blank · 437 comment · 10 complexity · af93b785bab04c6f2f80b2c3388dfb27 MD5 · raw file

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