Code

moving trunk for module inkscape
[inkscape.git] / src / dom / js / jsinterp.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2  *
3  * ***** BEGIN LICENSE BLOCK *****
4  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is Mozilla Communicator client code, released
17  * March 31, 1998.
18  *
19  * The Initial Developer of the Original Code is
20  * Netscape Communications Corporation.
21  * Portions created by the Initial Developer are Copyright (C) 1998
22  * the Initial Developer. All Rights Reserved.
23  *
24  * Contributor(s):
25  *
26  * Alternatively, the contents of this file may be used under the terms of
27  * either of the GNU General Public License Version 2 or later (the "GPL"),
28  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29  * in which case the provisions of the GPL or the LGPL are applicable instead
30  * of those above. If you wish to allow use of your version of this file only
31  * under the terms of either the GPL or the LGPL, and not to allow others to
32  * use your version of this file under the terms of the MPL, indicate your
33  * decision by deleting the provisions above and replace them with the notice
34  * and other provisions required by the GPL or the LGPL. If you do not delete
35  * the provisions above, a recipient may use your version of this file under
36  * the terms of any one of the MPL, the GPL or the LGPL.
37  *
38  * ***** END LICENSE BLOCK ***** */
40 /* build on macs with low memory */
41 #if defined(XP_MAC) && defined(MOZ_MAC_LOWMEM)
42 #pragma optimization_level 1
43 #endif
45 /*
46  * JavaScript bytecode interpreter.
47  */
48 #include "jsstddef.h"
49 #include <stdio.h>
50 #include <string.h>
51 #include <math.h>
52 #include "jstypes.h"
53 #include "jsarena.h" /* Added by JSIFY */
54 #include "jsutil.h" /* Added by JSIFY */
55 #include "jsprf.h"
56 #include "jsapi.h"
57 #include "jsarray.h"
58 #include "jsatom.h"
59 #include "jsbool.h"
60 #include "jscntxt.h"
61 #include "jsconfig.h"
62 #include "jsdbgapi.h"
63 #include "jsfun.h"
64 #include "jsgc.h"
65 #include "jsinterp.h"
66 #include "jslock.h"
67 #include "jsnum.h"
68 #include "jsobj.h"
69 #include "jsopcode.h"
70 #include "jsscope.h"
71 #include "jsscript.h"
72 #include "jsstr.h"
74 #if JS_HAS_JIT
75 #include "jsjit.h"
76 #endif
78 #ifdef DEBUG
79 #define ASSERT_CACHE_IS_EMPTY(cache)                                          \
80     JS_BEGIN_MACRO                                                            \
81         JSPropertyCacheEntry *end_, *pce_, entry_;                            \
82         JSPropertyCache *cache_ = (cache);                                    \
83         JS_ASSERT(cache_->empty);                                             \
84         end_ = &cache_->table[PROPERTY_CACHE_SIZE];                           \
85         for (pce_ = &cache_->table[0]; pce_ < end_; pce_++) {                 \
86             PCE_LOAD(cache_, pce_, entry_);                                   \
87             JS_ASSERT(!PCE_OBJECT(entry_));                                   \
88             JS_ASSERT(!PCE_PROPERTY(entry_));                                 \
89         }                                                                     \
90     JS_END_MACRO
91 #else
92 #define ASSERT_CACHE_IS_EMPTY(cache) ((void)0)
93 #endif
95 void
96 js_FlushPropertyCache(JSContext *cx)
97 {
98     JSPropertyCache *cache;
100     cache = &cx->runtime->propertyCache;
101     if (cache->empty) {
102         ASSERT_CACHE_IS_EMPTY(cache);
103         return;
104     }
105     memset(cache->table, 0, sizeof cache->table);
106     cache->empty = JS_TRUE;
107 #ifdef JS_PROPERTY_CACHE_METERING
108     cache->flushes++;
109 #endif
112 void
113 js_DisablePropertyCache(JSContext *cx)
115     JS_ASSERT(!cx->runtime->propertyCache.disabled);
116     cx->runtime->propertyCache.disabled = JS_TRUE;
119 void
120 js_EnablePropertyCache(JSContext *cx)
122     JS_ASSERT(cx->runtime->propertyCache.disabled);
123     ASSERT_CACHE_IS_EMPTY(&cx->runtime->propertyCache);
124     cx->runtime->propertyCache.disabled = JS_FALSE;
127 /*
128  * Class for for/in loop property iterator objects.
129  */
130 #define JSSLOT_ITER_STATE   JSSLOT_PRIVATE
132 static void
133 prop_iterator_finalize(JSContext *cx, JSObject *obj)
135     jsval iter_state;
136     jsval iteratee;
138     /* Protect against stillborn iterators. */
139     iter_state = obj->slots[JSSLOT_ITER_STATE];
140     iteratee = obj->slots[JSSLOT_PARENT];
141     if (!JSVAL_IS_NULL(iter_state) && !JSVAL_IS_PRIMITIVE(iteratee)) {
142         OBJ_ENUMERATE(cx, JSVAL_TO_OBJECT(iteratee), JSENUMERATE_DESTROY,
143                       &iter_state, NULL);
144     }
145     js_RemoveRoot(cx->runtime, &obj->slots[JSSLOT_PARENT]);
147     /* XXX force the GC to restart so we can collect iteratee, if possible,
148            during the current collector activation */
149     cx->runtime->gcLevel++;
152 static JSClass prop_iterator_class = {
153     "PropertyIterator",
154     0,
155     JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,
156     JS_EnumerateStub, JS_ResolveStub,   JS_ConvertStub,   prop_iterator_finalize,
157     JSCLASS_NO_OPTIONAL_MEMBERS
158 };
160 /*
161  * Stack macros and functions.  These all use a local variable, jsval *sp, to
162  * point to the next free stack slot.  SAVE_SP must be called before any call
163  * to a function that may invoke the interpreter.  RESTORE_SP must be called
164  * only after return from js_Invoke, because only js_Invoke changes fp->sp.
165  */
166 #define PUSH(v)         (*sp++ = (v))
167 #define POP()           (*--sp)
168 #ifdef DEBUG
169 #define SAVE_SP(fp)                                                           \
170     (JS_ASSERT((fp)->script || !(fp)->spbase || (sp) == (fp)->spbase),        \
171      (fp)->sp = sp)
172 #else
173 #define SAVE_SP(fp)     ((fp)->sp = sp)
174 #endif
175 #define RESTORE_SP(fp)  (sp = (fp)->sp)
177 /*
178  * Push the generating bytecode's pc onto the parallel pc stack that runs
179  * depth slots below the operands.
180  *
181  * NB: PUSH_OPND uses sp, depth, and pc from its lexical environment.  See
182  * js_Interpret for these local variables' declarations and uses.
183  */
184 #define PUSH_OPND(v)    (sp[-depth] = (jsval)pc, PUSH(v))
185 #define STORE_OPND(n,v) (sp[(n)-depth] = (jsval)pc, sp[n] = (v))
186 #define POP_OPND()      POP()
187 #define FETCH_OPND(n)   (sp[n])
189 /*
190  * Push the jsdouble d using sp, depth, and pc from the lexical environment.
191  * Try to convert d to a jsint that fits in a jsval, otherwise GC-alloc space
192  * for it and push a reference.
193  */
194 #define STORE_NUMBER(cx, n, d)                                                \
195     JS_BEGIN_MACRO                                                            \
196         jsint i_;                                                             \
197         jsval v_;                                                             \
198                                                                               \
199         if (JSDOUBLE_IS_INT(d, i_) && INT_FITS_IN_JSVAL(i_)) {                \
200             v_ = INT_TO_JSVAL(i_);                                            \
201         } else {                                                              \
202             ok = js_NewDoubleValue(cx, d, &v_);                               \
203             if (!ok)                                                          \
204                 goto out;                                                     \
205         }                                                                     \
206         STORE_OPND(n, v_);                                                    \
207     JS_END_MACRO
209 #define FETCH_NUMBER(cx, n, d)                                                \
210     JS_BEGIN_MACRO                                                            \
211         jsval v_;                                                             \
212                                                                               \
213         v_ = FETCH_OPND(n);                                                   \
214         VALUE_TO_NUMBER(cx, v_, d);                                           \
215     JS_END_MACRO
217 #define FETCH_INT(cx, n, i)                                                   \
218     JS_BEGIN_MACRO                                                            \
219         jsval v_ = FETCH_OPND(n);                                             \
220         if (JSVAL_IS_INT(v_)) {                                               \
221             i = JSVAL_TO_INT(v_);                                             \
222         } else {                                                              \
223             SAVE_SP(fp);                                                      \
224             ok = js_ValueToECMAInt32(cx, v_, &i);                             \
225             if (!ok)                                                          \
226                 goto out;                                                     \
227         }                                                                     \
228     JS_END_MACRO
230 #define FETCH_UINT(cx, n, ui)                                                 \
231     JS_BEGIN_MACRO                                                            \
232         jsval v_ = FETCH_OPND(n);                                             \
233         jsint i_;                                                             \
234         if (JSVAL_IS_INT(v_) && (i_ = JSVAL_TO_INT(v_)) >= 0) {               \
235             ui = (uint32) i_;                                                 \
236         } else {                                                              \
237             SAVE_SP(fp);                                                      \
238             ok = js_ValueToECMAUint32(cx, v_, &ui);                           \
239             if (!ok)                                                          \
240                 goto out;                                                     \
241         }                                                                     \
242     JS_END_MACRO
244 /*
245  * Optimized conversion macros that test for the desired type in v before
246  * homing sp and calling a conversion function.
247  */
248 #define VALUE_TO_NUMBER(cx, v, d)                                             \
249     JS_BEGIN_MACRO                                                            \
250         if (JSVAL_IS_INT(v)) {                                                \
251             d = (jsdouble)JSVAL_TO_INT(v);                                    \
252         } else if (JSVAL_IS_DOUBLE(v)) {                                      \
253             d = *JSVAL_TO_DOUBLE(v);                                          \
254         } else {                                                              \
255             SAVE_SP(fp);                                                      \
256             ok = js_ValueToNumber(cx, v, &d);                                 \
257             if (!ok)                                                          \
258                 goto out;                                                     \
259         }                                                                     \
260     JS_END_MACRO
262 #define POP_BOOLEAN(cx, v, b)                                                 \
263     JS_BEGIN_MACRO                                                            \
264         v = FETCH_OPND(-1);                                                   \
265         if (v == JSVAL_NULL) {                                                \
266             b = JS_FALSE;                                                     \
267         } else if (JSVAL_IS_BOOLEAN(v)) {                                     \
268             b = JSVAL_TO_BOOLEAN(v);                                          \
269         } else {                                                              \
270             SAVE_SP(fp);                                                      \
271             ok = js_ValueToBoolean(cx, v, &b);                                \
272             if (!ok)                                                          \
273                 goto out;                                                     \
274         }                                                                     \
275         sp--;                                                                 \
276     JS_END_MACRO
278 #define VALUE_TO_OBJECT(cx, v, obj)                                           \
279     JS_BEGIN_MACRO                                                            \
280         if (JSVAL_IS_OBJECT(v) && v != JSVAL_NULL) {                          \
281             obj = JSVAL_TO_OBJECT(v);                                         \
282         } else {                                                              \
283             SAVE_SP(fp);                                                      \
284             obj = js_ValueToNonNullObject(cx, v);                             \
285             if (!obj) {                                                       \
286                 ok = JS_FALSE;                                                \
287                 goto out;                                                     \
288             }                                                                 \
289         }                                                                     \
290     JS_END_MACRO
292 #if JS_BUG_VOID_TOSTRING
293 #define CHECK_VOID_TOSTRING(cx, v)                                            \
294     if (JSVAL_IS_VOID(v)) {                                                   \
295         JSString *str_;                                                       \
296         str_ = ATOM_TO_STRING(cx->runtime->atomState.typeAtoms[JSTYPE_VOID]); \
297         v = STRING_TO_JSVAL(str_);                                            \
298     }
299 #else
300 #define CHECK_VOID_TOSTRING(cx, v)  ((void)0)
301 #endif
303 #if JS_BUG_EAGER_TOSTRING
304 #define CHECK_EAGER_TOSTRING(hint)  (hint = JSTYPE_STRING)
305 #else
306 #define CHECK_EAGER_TOSTRING(hint)  ((void)0)
307 #endif
309 #define VALUE_TO_PRIMITIVE(cx, v, hint, vp)                                   \
310     JS_BEGIN_MACRO                                                            \
311         if (JSVAL_IS_PRIMITIVE(v)) {                                          \
312             CHECK_VOID_TOSTRING(cx, v);                                       \
313             *vp = v;                                                          \
314         } else {                                                              \
315             SAVE_SP(fp);                                                      \
316             CHECK_EAGER_TOSTRING(hint);                                       \
317             ok = OBJ_DEFAULT_VALUE(cx, JSVAL_TO_OBJECT(v), hint, vp);         \
318             if (!ok)                                                          \
319                 goto out;                                                     \
320         }                                                                     \
321     JS_END_MACRO
323 JS_FRIEND_API(jsval *)
324 js_AllocRawStack(JSContext *cx, uintN nslots, void **markp)
326     jsval *sp;
328     if (markp)
329         *markp = JS_ARENA_MARK(&cx->stackPool);
330     JS_ARENA_ALLOCATE_CAST(sp, jsval *, &cx->stackPool, nslots * sizeof(jsval));
331     if (!sp) {
332         JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_STACK_OVERFLOW,
333                              (cx->fp && cx->fp->fun)
334                              ? JS_GetFunctionName(cx->fp->fun)
335                              : "script");
336     }
337     return sp;
340 JS_FRIEND_API(void)
341 js_FreeRawStack(JSContext *cx, void *mark)
343     JS_ARENA_RELEASE(&cx->stackPool, mark);
346 JS_FRIEND_API(jsval *)
347 js_AllocStack(JSContext *cx, uintN nslots, void **markp)
349     jsval *sp, *vp, *end;
350     JSArena *a;
351     JSStackHeader *sh;
352     JSStackFrame *fp;
354     /* Callers don't check for zero nslots: we do to avoid empty segments. */
355     if (nslots == 0) {
356         *markp = NULL;
357         return JS_ARENA_MARK(&cx->stackPool);
358     }
360     /* Allocate 2 extra slots for the stack segment header we'll likely need. */
361     sp = js_AllocRawStack(cx, 2 + nslots, markp);
362     if (!sp)
363         return NULL;
365     /* Try to avoid another header if we can piggyback on the last segment. */
366     a = cx->stackPool.current;
367     sh = cx->stackHeaders;
368     if (sh && JS_STACK_SEGMENT(sh) + sh->nslots == sp) {
369         /* Extend the last stack segment, give back the 2 header slots. */
370         sh->nslots += nslots;
371         a->avail -= 2 * sizeof(jsval);
372     } else {
373         /*
374          * Need a new stack segment, so we must initialize unused slots in the
375          * current frame.  See js_GC, just before marking the "operand" jsvals,
376          * where we scan from fp->spbase to fp->sp or through fp->script->depth
377          * (whichever covers fewer slots).
378          */
379         fp = cx->fp;
380         if (fp && fp->script && fp->spbase) {
381 #ifdef DEBUG
382             jsuword depthdiff = fp->script->depth * sizeof(jsval);
383             JS_ASSERT(JS_UPTRDIFF(fp->sp, fp->spbase) <= depthdiff);
384             JS_ASSERT(JS_UPTRDIFF(*markp, fp->spbase) >= depthdiff);
385 #endif
386             end = fp->spbase + fp->script->depth;
387             for (vp = fp->sp; vp < end; vp++)
388                 *vp = JSVAL_VOID;
389         }
391         /* Allocate and push a stack segment header from the 2 extra slots. */
392         sh = (JSStackHeader *)sp;
393         sh->nslots = nslots;
394         sh->down = cx->stackHeaders;
395         cx->stackHeaders = sh;
396         sp += 2;
397     }
399     return sp;
402 JS_FRIEND_API(void)
403 js_FreeStack(JSContext *cx, void *mark)
405     JSStackHeader *sh;
406     jsuword slotdiff;
408     /* Check for zero nslots allocation special case. */
409     if (!mark)
410         return;
412     /* We can assert because js_FreeStack always balances js_AllocStack. */
413     sh = cx->stackHeaders;
414     JS_ASSERT(sh);
416     /* If mark is in the current segment, reduce sh->nslots, else pop sh. */
417     slotdiff = JS_UPTRDIFF(mark, JS_STACK_SEGMENT(sh)) / sizeof(jsval);
418     if (slotdiff < (jsuword)sh->nslots)
419         sh->nslots = slotdiff;
420     else
421         cx->stackHeaders = sh->down;
423     /* Release the stackPool space allocated since mark was set. */
424     JS_ARENA_RELEASE(&cx->stackPool, mark);
427 /*
428  * To economize on slots space in functions, the compiler records arguments and
429  * local variables as shared (JSPROP_SHARED) properties with well-known getters
430  * and setters: js_{Get,Set}Argument, js_{Get,Set}LocalVariable.  Now, we could
431  * record args and vars in lists or hash tables in function-private data, but
432  * that means more duplication in code, and more data at runtime in the hash
433  * table case due to round-up to powers of two, just to recapitulate the scope
434  * machinery in the function object.
435  *
436  * What's more, for a long time (to the dawn of "Mocha" in 1995), these getters
437  * and setters knew how to search active stack frames in a context to find the
438  * top activation of the function f, in order to satisfy a get or set of f.a,
439  * for argument a, or f.x, for local variable x.  You could use f.a instead of
440  * just a in function f(a) { return f.a }, for example, to return the actual
441  * parameter.
442  *
443  * ECMA requires that we give up on this ancient extension, because it is not
444  * compatible with the standard as used by real-world scripts.  While Chapter
445  * 16 does allow for additional properties to be defined on native objects by
446  * a conforming implementation, these magic getters and setters cause f.a's
447  * meaning to vary unexpectedly.  Real-world scripts set f.A = 42 to define
448  * "class static" (after Java) constants, for example, but if A also names an
449  * arg or var in f, the constant is not available while f is active, and any
450  * non-constant class-static can't be set while f is active.
451  *
452  * So, to label arg and var properties in functions without giving them magic
453  * abilities to affect active frame stack slots, while keeping the properties
454  * shared (slot-less) to save space in the common case (where no assignment
455  * sets a function property with the same name as an arg or var), the setters
456  * for args and vars must handle two special cases here.
457  *
458  * XXX functions tend to have few args and vars, so we risk O(n^2) growth here
459  * XXX ECMA *really* wants args and vars to be stored in function-private data,
460  *     not as function object properties.
461  */
462 static JSBool
463 SetFunctionSlot(JSContext *cx, JSObject *obj, JSPropertyOp setter, jsid id,
464                 jsval v)
466     uintN slot;
467     JSObject *origobj;
468     JSScope *scope;
469     JSScopeProperty *sprop;
470     JSString *str;
471     JSBool ok;
473     slot = (uintN) JSVAL_TO_INT(id);
474     if (OBJ_GET_CLASS(cx, obj) != &js_FunctionClass) {
475         /*
476          * Given a non-function object obj that has a function object in its
477          * prototype chain, where an argument or local variable property named
478          * by (setter, slot) is being set, override the shared property in the
479          * prototype with an unshared property in obj.  This situation arises
480          * in real-world JS due to .prototype setting and collisions among a
481          * function's "static property" names and arg or var names, believe it
482          * or not.
483          */
484         origobj = obj;
485         do {
486             obj = OBJ_GET_PROTO(cx, obj);
487             if (!obj)
488                 return JS_TRUE;
489         } while (OBJ_GET_CLASS(cx, obj) != &js_FunctionClass);
491         JS_LOCK_OBJ(cx, obj);
492         scope = OBJ_SCOPE(obj);
493         for (sprop = SCOPE_LAST_PROP(scope); sprop; sprop = sprop->parent) {
494             if (sprop->setter == setter) {
495                 JS_ASSERT(!JSVAL_IS_INT(sprop->id) &&
496                           ATOM_IS_STRING((JSAtom *)sprop->id) &&
497                           (sprop->flags & SPROP_HAS_SHORTID));
499                 if ((uintN) sprop->shortid == slot) {
500                     str = ATOM_TO_STRING((JSAtom *)sprop->id);
501                     JS_UNLOCK_SCOPE(cx, scope);
503                     return JS_DefineUCProperty(cx, origobj,
504                                                JSSTRING_CHARS(str),
505                                                JSSTRING_LENGTH(str),
506                                                v, NULL, NULL,
507                                                JSPROP_ENUMERATE);
508                 }
509             }
510         }
511         JS_UNLOCK_SCOPE(cx, scope);
512         return JS_TRUE;
513     }
515     /*
516      * Argument and local variable properties of function objects are shared
517      * by default (JSPROP_SHARED), therefore slot-less.  But if for function
518      * f(a) {}, f.a = 42 is evaluated, f.a should be 42 after the assignment,
519      * whether or not f is active.  So js_SetArgument and js_SetLocalVariable
520      * must be prepared to change an arg or var from shared to unshared status,
521      * allocating a slot in obj to hold v.
522      */
523     ok = JS_TRUE;
524     JS_LOCK_OBJ(cx, obj);
525     scope = OBJ_SCOPE(obj);
526     for (sprop = SCOPE_LAST_PROP(scope); sprop; sprop = sprop->parent) {
527         if (sprop->setter == setter && (uintN) sprop->shortid == slot) {
528             if (sprop->attrs & JSPROP_SHARED) {
529                 sprop = js_ChangeScopePropertyAttrs(cx, scope, sprop,
530                                                     0, ~JSPROP_SHARED,
531                                                     sprop->getter, setter);
532                 if (!sprop) {
533                     ok = JS_FALSE;
534                 } else {
535                     /* See js_SetProperty, near the bottom. */
536                     GC_POKE(cx, pval);
537                     LOCKED_OBJ_SET_SLOT(obj, sprop->slot, v);
538                 }
539             }
540             break;
541         }
542     }
543     JS_UNLOCK_SCOPE(cx, scope);
544     return ok;
547 JSBool
548 js_GetArgument(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
550     return JS_TRUE;
553 JSBool
554 js_SetArgument(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
556     return SetFunctionSlot(cx, obj, js_SetArgument, id, *vp);
559 JSBool
560 js_GetLocalVariable(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
562     return JS_TRUE;
565 JSBool
566 js_SetLocalVariable(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
568     return SetFunctionSlot(cx, obj, js_SetLocalVariable, id, *vp);
571 /*
572  * Compute the 'this' parameter and store it in frame as frame.thisp.
573  * Activation objects ("Call" objects not created with "new Call()", i.e.,
574  * "Call" objects that have private data) may not be referred to by 'this',
575  * as dictated by ECMA.
576  *
577  * N.B.: fp->argv must be set, fp->argv[-1] the nominal 'this' paramter as
578  * a jsval, and fp->argv[-2] must be the callee object reference, usually a
579  * function object.  Also, fp->flags must contain JSFRAME_CONSTRUCTING if we
580  * are preparing for a constructor call.
581  */
582 static JSBool
583 ComputeThis(JSContext *cx, JSObject *thisp, JSStackFrame *fp)
585     JSObject *parent;
587     if (thisp && OBJ_GET_CLASS(cx, thisp) != &js_CallClass) {
588         /* Some objects (e.g., With) delegate 'this' to another object. */
589         thisp = OBJ_THIS_OBJECT(cx, thisp);
590         if (!thisp)
591             return JS_FALSE;
593         /* Default return value for a constructor is the new object. */
594         if (fp->flags & JSFRAME_CONSTRUCTING)
595             fp->rval = OBJECT_TO_JSVAL(thisp);
596     } else {
597         /*
598          * ECMA requires "the global object", but in the presence of multiple
599          * top-level objects (windows, frames, or certain layers in the client
600          * object model), we prefer fun's parent.  An example that causes this
601          * code to run:
602          *
603          *   // in window w1
604          *   function f() { return this }
605          *   function g() { return f }
606          *
607          *   // in window w2
608          *   var h = w1.g()
609          *   alert(h() == w1)
610          *
611          * The alert should display "true".
612          */
613         JS_ASSERT(!(fp->flags & JSFRAME_CONSTRUCTING));
614         if (JSVAL_IS_PRIMITIVE(fp->argv[-2]) ||
615             !(parent = OBJ_GET_PARENT(cx, JSVAL_TO_OBJECT(fp->argv[-2])))) {
616             thisp = cx->globalObject;
617         } else {
618             /* walk up to find the top-level object */
619             thisp = parent;
620             while ((parent = OBJ_GET_PARENT(cx, thisp)) != NULL)
621                 thisp = parent;
622         }
623     }
624     fp->thisp = thisp;
625     fp->argv[-1] = OBJECT_TO_JSVAL(thisp);
626     return JS_TRUE;
629 /*
630  * Find a function reference and its 'this' object implicit first parameter
631  * under argc arguments on cx's stack, and call the function.  Push missing
632  * required arguments, allocate declared local variables, and pop everything
633  * when done.  Then push the return value.
634  */
635 JS_FRIEND_API(JSBool)
636 js_Invoke(JSContext *cx, uintN argc, uintN flags)
638     void *mark;
639     JSStackFrame *fp, frame;
640     jsval *sp, *newsp, *limit;
641     jsval *vp, v;
642     JSObject *funobj, *parent, *thisp;
643     JSBool ok;
644     JSClass *clasp;
645     JSObjectOps *ops;
646     JSNative native;
647     JSFunction *fun;
648     JSScript *script;
649     uintN minargs, nvars;
650     intN nslots, nalloc, surplus;
651     JSInterpreterHook hook;
652     void *hookData;
654     /* Mark the top of stack and load frequently-used registers. */
655     mark = JS_ARENA_MARK(&cx->stackPool);
656     fp = cx->fp;
657     sp = fp->sp;
659     /*
660      * Set vp to the callee value's stack slot (it's where rval goes).
661      * Once vp is set, control should flow through label out2: to return.
662      * Set frame.rval early so native class and object ops can throw and
663      * return false, causing a goto out2 with ok set to false.  Also set
664      * frame.flags to flags so that ComputeThis can test bits in it.
665      */
666     vp = sp - (2 + argc);
667     v = *vp;
668     frame.rval = JSVAL_VOID;
669     frame.flags = flags;
670     thisp = JSVAL_TO_OBJECT(vp[1]);
672     /*
673      * A callee must be an object reference, unless its |this| parameter
674      * implements the __noSuchMethod__ method, in which case that method will
675      * be called like so:
676      *
677      *   thisp.__noSuchMethod__(id, args)
678      *
679      * where id is the name of the method that this invocation attempted to
680      * call by name, and args is an Array containing this invocation's actual
681      * parameters.
682      */
683     if (JSVAL_IS_PRIMITIVE(v)) {
684 #if JS_HAS_NO_SUCH_METHOD
685         jsbytecode *pc;
686         jsatomid atomIndex;
687         JSAtom *atom;
688         JSObject *argsobj;
689         JSArena *a;
691         if (!fp->script || (flags & JSINVOKE_INTERNAL))
692             goto bad;
694         /*
695          * We must ComputeThis here to censor Call objects; performance hit,
696          * but at least it's idempotent.
697          *
698          * Normally, we call ComputeThis after all frame members have been
699          * set, and in particular, after any revision of the callee value at
700          * *vp  due to clasp->convert (see below).  This matters because
701          * ComputeThis may access *vp via fp->argv[-2], to follow the parent
702          * chain to a global object to use as the |this| parameter.
703          *
704          * Obviously, here in the JSVAL_IS_PRIMITIVE(v) case, there can't be
705          * any such defaulting of |this| to callee (v, *vp) ancestor.
706          */
707         frame.argv = vp + 2;
708         ok = ComputeThis(cx, thisp, &frame);
709         if (!ok)
710             goto out2;
711         thisp = frame.thisp;
713         ok = OBJ_GET_PROPERTY(cx, thisp,
714                               (jsid)cx->runtime->atomState.noSuchMethodAtom,
715                               &v);
716         if (!ok)
717             goto out2;
718         if (JSVAL_IS_PRIMITIVE(v))
719             goto bad;
721         pc = (jsbytecode *) vp[-(intN)fp->script->depth];
722         switch ((JSOp) *pc) {
723           case JSOP_NAME:
724           case JSOP_GETPROP:
725             atomIndex = GET_ATOM_INDEX(pc);
726             atom = js_GetAtom(cx, &fp->script->atomMap, atomIndex);
727             argsobj = js_NewArrayObject(cx, argc, vp + 2);
728             if (!argsobj) {
729                 ok = JS_FALSE;
730                 goto out2;
731             }
733             sp = vp + 4;
734             if (argc < 2) {
735                 a = cx->stackPool.current;
736                 if ((jsuword)sp > a->limit) {
737                     /*
738                      * Arguments must be contiguous, and must include argv[-1]
739                      * and argv[-2], so allocate more stack, advance sp, and
740                      * set newsp[1] to thisp (vp[1]).  The other argv elements
741                      * will be set below, using negative indexing from sp.
742                      */
743                     newsp = js_AllocRawStack(cx, 4, NULL);
744                     if (!newsp) {
745                         ok = JS_FALSE;
746                         goto out2;
747                     }
748                     newsp[1] = OBJECT_TO_JSVAL(thisp);
749                     sp = newsp + 4;
750                 } else if ((jsuword)sp > a->avail) {
751                     /*
752                      * Inline, optimized version of JS_ARENA_ALLOCATE to claim
753                      * the small number of words not already allocated as part
754                      * of the caller's operand stack.
755                      */
756                     JS_ArenaCountAllocation(pool, (jsuword)sp - a->avail);
757                     a->avail = (jsuword)sp;
758                 }
759             }
761             sp[-4] = v;
762             JS_ASSERT(sp[-3] == OBJECT_TO_JSVAL(thisp));
763             sp[-2] = ATOM_KEY(atom);
764             sp[-1] = OBJECT_TO_JSVAL(argsobj);
765             fp->sp = sp;
766             argc = 2;
767             break;
769           default:
770             goto bad;
771         }
772 #else
773         goto bad;
774 #endif
775     }
777     funobj = JSVAL_TO_OBJECT(v);
778     parent = OBJ_GET_PARENT(cx, funobj);
779     clasp = OBJ_GET_CLASS(cx, funobj);
780     if (clasp != &js_FunctionClass) {
781         /* Function is inlined, all other classes use object ops. */
782         ops = funobj->map->ops;
784         /*
785          * XXX
786          * Try converting to function, for closure and API compatibility.
787          * We attempt the conversion under all circumstances for 1.2, but
788          * only if there is a call op defined otherwise.
789          */
790         if (cx->version == JSVERSION_1_2 ||
791             ((ops == &js_ObjectOps) ? clasp->call : ops->call)) {
792             ok = clasp->convert(cx, funobj, JSTYPE_FUNCTION, &v);
793             if (!ok)
794                 goto out2;
796             if (JSVAL_IS_FUNCTION(cx, v)) {
797                 /* Make vp refer to funobj to keep it available as argv[-2]. */
798                 *vp = v;
799                 funobj = JSVAL_TO_OBJECT(v);
800                 parent = OBJ_GET_PARENT(cx, funobj);
801                 goto have_fun;
802             }
803         }
804         fun = NULL;
805         script = NULL;
806         minargs = nvars = 0;
808         /* Try a call or construct native object op. */
809         native = (flags & JSINVOKE_CONSTRUCT) ? ops->construct : ops->call;
810         if (!native)
811             goto bad;
812     } else {
813 have_fun:
814         /* Get private data and set derived locals from it. */
815         fun = (JSFunction *) JS_GetPrivate(cx, funobj);
816         native = fun->native;
817         script = fun->script;
818         minargs = fun->nargs + fun->extra;
819         nvars = fun->nvars;
821         /* Handle bound method special case. */
822         if (fun->flags & JSFUN_BOUND_METHOD)
823             thisp = parent;
824     }
826     /* Initialize the rest of frame, except for sp (set by SAVE_SP later). */
827     frame.varobj = NULL;
828     frame.callobj = frame.argsobj = NULL;
829     frame.script = script;
830     frame.fun = fun;
831     frame.argc = argc;
832     frame.argv = sp - argc;
833     frame.nvars = nvars;
834     frame.vars = sp;
835     frame.down = fp;
836     frame.annotation = NULL;
837     frame.scopeChain = NULL;    /* set below for real, after cx->fp is set */
838     frame.pc = NULL;
839     frame.spbase = NULL;
840     frame.sharpDepth = 0;
841     frame.sharpArray = NULL;
842     frame.dormantNext = NULL;
843     frame.objAtomMap = NULL;
845     /* Compute the 'this' parameter and store it in frame as frame.thisp. */
846     ok = ComputeThis(cx, thisp, &frame);
847     if (!ok)
848         goto out2;
850     /* From here on, control must flow through label out: to return. */
851     cx->fp = &frame;
853     /* Init these now in case we goto out before first hook call. */
854     hook = cx->runtime->callHook;
855     hookData = NULL;
857     /* Check for missing arguments expected by the function. */
858     nslots = (intN)((argc < minargs) ? minargs - argc : 0);
859     if (nslots) {
860         /* All arguments must be contiguous, so we may have to copy actuals. */
861         nalloc = nslots;
862         limit = (jsval *) cx->stackPool.current->limit;
863         if (sp + nslots > limit) {
864             /* Hit end of arena: we have to copy argv[-2..(argc+nslots-1)]. */
865             nalloc += 2 + argc;
866         } else {
867             /* Take advantage of surplus slots in the caller's frame depth. */
868             surplus = (jsval *)mark - sp;
869             JS_ASSERT(surplus >= 0);
870             nalloc -= surplus;
871         }
873         /* Check whether we have enough space in the caller's frame. */
874         if (nalloc > 0) {
875             /* Need space for actuals plus missing formals minus surplus. */
876             newsp = js_AllocRawStack(cx, (uintN)nalloc, NULL);
877             if (!newsp) {
878                 ok = JS_FALSE;
879                 goto out;
880             }
882             /* If we couldn't allocate contiguous args, copy actuals now. */
883             if (newsp != mark) {
884                 JS_ASSERT(sp + nslots > limit);
885                 JS_ASSERT(2 + argc + nslots == (uintN)nalloc);
886                 *newsp++ = vp[0];
887                 *newsp++ = vp[1];
888                 if (argc)
889                     memcpy(newsp, frame.argv, argc * sizeof(jsval));
890                 frame.argv = newsp;
891                 sp = frame.vars = newsp + argc;
892             }
893         }
895         /* Advance frame.vars to make room for the missing args. */
896         frame.vars += nslots;
898         /* Push void to initialize missing args. */
899         while (--nslots >= 0)
900             PUSH(JSVAL_VOID);
901     }
903     /* Now allocate stack space for local variables. */
904     nslots = (intN)frame.nvars;
905     if (nslots) {
906         surplus = (intN)((jsval *)cx->stackPool.current->avail - frame.vars);
907         if (surplus < nslots) {
908             newsp = js_AllocRawStack(cx, (uintN)nslots, NULL);
909             if (!newsp) {
910                 ok = JS_FALSE;
911                 goto out;
912             }
913             if (newsp != sp) {
914                 /* NB: Discontinuity between argv and vars. */
915                 sp = frame.vars = newsp;
916             }
917         }
919         /* Push void to initialize local variables. */
920         while (--nslots >= 0)
921             PUSH(JSVAL_VOID);
922     }
924     /* Store the current sp in frame before calling fun. */
925     SAVE_SP(&frame);
927     /* call the hook if present */
928     if (hook && (native || script))
929         hookData = hook(cx, &frame, JS_TRUE, 0, cx->runtime->callHookData);
931     /* Call the function, either a native method or an interpreted script. */
932     if (native) {
933 #if JS_HAS_LVALUE_RETURN
934         /* Set by JS_SetCallReturnValue2, used to return reference types. */
935         cx->rval2set = JS_FALSE;
936 #endif
938         /* If native, use caller varobj and scopeChain for eval. */
939         frame.varobj = fp->varobj;
940         frame.scopeChain = fp->scopeChain;
941         ok = native(cx, frame.thisp, argc, frame.argv, &frame.rval);
942         JS_RUNTIME_METER(cx->runtime, nativeCalls);
943     } else if (script) {
944         /* Use parent scope so js_GetCallObject can find the right "Call". */
945         frame.scopeChain = parent;
946         if (fun->flags & JSFUN_HEAVYWEIGHT) {
947 #if JS_HAS_CALL_OBJECT
948             /* Scope with a call object parented by the callee's parent. */
949             if (!js_GetCallObject(cx, &frame, parent)) {
950                 ok = JS_FALSE;
951                 goto out;
952             }
953 #else
954             /* Bad old code used the function as a proxy for all calls to it. */
955             frame.scopeChain = funobj;
956 #endif
957         }
958         ok = js_Interpret(cx, &v);
959     } else {
960         /* fun might be onerror trying to report a syntax error in itself. */
961         frame.scopeChain = NULL;
962         ok = JS_TRUE;
963     }
965 out:
966     if (hookData) {
967         hook = cx->runtime->callHook;
968         if (hook)
969             hook(cx, &frame, JS_FALSE, &ok, hookData);
970     }
971 #if JS_HAS_CALL_OBJECT
972     /* If frame has a call object, sync values and clear back-pointer. */
973     if (frame.callobj)
974         ok &= js_PutCallObject(cx, &frame);
975 #endif
976 #if JS_HAS_ARGS_OBJECT
977     /* If frame has an arguments object, sync values and clear back-pointer. */
978     if (frame.argsobj)
979         ok &= js_PutArgsObject(cx, &frame);
980 #endif
982     /* Restore cx->fp now that we're done releasing frame objects. */
983     cx->fp = fp;
985 out2:
986     /* Pop everything we may have allocated off the stack. */
987     JS_ARENA_RELEASE(&cx->stackPool, mark);
989     /* Store the return value and restore sp just above it. */
990     *vp = frame.rval;
991     fp->sp = vp + 1;
993     /*
994      * Store the location of the JSOP_CALL or JSOP_EVAL that generated the
995      * return value, but only if this is an external (compiled from script
996      * source) call that has stack budget for the generating pc.
997      */
998     if (fp->script && !(flags & JSINVOKE_INTERNAL))
999         vp[-(intN)fp->script->depth] = (jsval)fp->pc;
1000     return ok;
1002 bad:
1003     js_ReportIsNotFunction(cx, vp, flags & JSINVOKE_CONSTRUCT);
1004     ok = JS_FALSE;
1005     goto out2;
1008 JSBool
1009 js_InternalInvoke(JSContext *cx, JSObject *obj, jsval fval, uintN flags,
1010                   uintN argc, jsval *argv, jsval *rval)
1012     JSStackFrame *fp, *oldfp, frame;
1013     jsval *oldsp, *sp;
1014     void *mark;
1015     uintN i;
1016     JSBool ok;
1018     fp = oldfp = cx->fp;
1019     if (!fp) {
1020         memset(&frame, 0, sizeof frame);
1021         cx->fp = fp = &frame;
1022     }
1023     oldsp = fp->sp;
1024     sp = js_AllocStack(cx, 2 + argc, &mark);
1025     if (!sp) {
1026         ok = JS_FALSE;
1027         goto out;
1028     }
1030     PUSH(fval);
1031     PUSH(OBJECT_TO_JSVAL(obj));
1032     for (i = 0; i < argc; i++)
1033         PUSH(argv[i]);
1034     fp->sp = sp;
1035     ok = js_Invoke(cx, argc, flags | JSINVOKE_INTERNAL);
1036     if (ok) {
1037         RESTORE_SP(fp);
1038         *rval = POP_OPND();
1039     }
1041     js_FreeStack(cx, mark);
1042 out:
1043     fp->sp = oldsp;
1044     if (oldfp != fp)
1045         cx->fp = oldfp;
1047     return ok;
1050 JSBool
1051 js_InternalGetOrSet(JSContext *cx, JSObject *obj, jsid id, jsval fval,
1052                     JSAccessMode mode, uintN argc, jsval *argv, jsval *rval)
1054     /*
1055      * Check general (not object-ops/class-specific) access from the running
1056      * script to obj.id only if id has a scripted getter or setter that we're
1057      * about to invoke.  If we don't check this case, nothing else will -- no
1058      * other native code has the chance to check.
1059      *
1060      * Contrast this non-native (scripted) case with native getter and setter
1061      * accesses, where the native itself must do an access check, if security
1062      * policies requires it.  We make a checkAccess or checkObjectAccess call
1063      * back to the embedding program only in those cases where we're not going
1064      * to call an embedding-defined native function, getter, setter, or class
1065      * hook anyway.  Where we do call such a native, there's no need for the
1066      * engine to impose a separate access check callback on all embeddings --
1067      * many embeddings have no security policy at all.
1068      */
1069     JS_ASSERT(mode == JSACC_READ || mode == JSACC_WRITE);
1070     if (cx->runtime->checkObjectAccess &&
1071         JSVAL_IS_FUNCTION(cx, fval) &&
1072         ((JSFunction *) JS_GetPrivate(cx, JSVAL_TO_OBJECT(fval)))->script &&
1073         !cx->runtime->checkObjectAccess(cx, obj, ID_TO_VALUE(id), mode,
1074                                         &fval)) {
1075         return JS_FALSE;
1076     }
1078     return js_InternalCall(cx, obj, fval, argc, argv, rval);
1081 JSBool
1082 js_Execute(JSContext *cx, JSObject *chain, JSScript *script,
1083            JSStackFrame *down, uintN special, jsval *result)
1085     JSStackFrame *oldfp, frame;
1086     JSObject *obj, *tmp;
1087     JSBool ok;
1088     JSInterpreterHook hook;
1089     void *hookData;
1091     hook = cx->runtime->executeHook;
1092     hookData = NULL;
1093     oldfp = cx->fp;
1094     frame.callobj = frame.argsobj = NULL;
1095     frame.script = script;
1096     if (down) {
1097         /* Propagate arg/var state for eval and the debugger API. */
1098         frame.varobj = down->varobj;
1099         frame.fun = down->fun;
1100         frame.thisp = down->thisp;
1101         frame.argc = down->argc;
1102         frame.argv = down->argv;
1103         frame.nvars = down->nvars;
1104         frame.vars = down->vars;
1105         frame.annotation = down->annotation;
1106         frame.sharpArray = down->sharpArray;
1107     } else {
1108         obj = chain;
1109         if (cx->options & JSOPTION_VAROBJFIX) {
1110             while ((tmp = OBJ_GET_PARENT(cx, obj)) != NULL)
1111                 obj = tmp;
1112         }
1113         frame.varobj = obj;
1114         frame.fun = NULL;
1115         frame.thisp = chain;
1116         frame.argc = frame.nvars = 0;
1117         frame.argv = frame.vars = NULL;
1118         frame.annotation = NULL;
1119         frame.sharpArray = NULL;
1120     }
1121     frame.rval = JSVAL_VOID;
1122     frame.down = down;
1123     frame.scopeChain = chain;
1124     frame.pc = NULL;
1125     frame.sp = oldfp ? oldfp->sp : NULL;
1126     frame.spbase = NULL;
1127     frame.sharpDepth = 0;
1128     frame.flags = special;
1129     frame.dormantNext = NULL;
1130     frame.objAtomMap = NULL;
1132     /*
1133      * Here we wrap the call to js_Interpret with code to (conditionally)
1134      * save and restore the old stack frame chain into a chain of 'dormant'
1135      * frame chains.  Since we are replacing cx->fp, we were running into
1136      * the problem that if GC was called under this frame, some of the GC
1137      * things associated with the old frame chain (available here only in
1138      * the C variable 'oldfp') were not rooted and were being collected.
1139      *
1140      * So, now we preserve the links to these 'dormant' frame chains in cx
1141      * before calling js_Interpret and cleanup afterwards.  The GC walks
1142      * these dormant chains and marks objects in the same way that it marks
1143      * objects in the primary cx->fp chain.
1144      */
1145     if (oldfp && oldfp != down) {
1146         JS_ASSERT(!oldfp->dormantNext);
1147         oldfp->dormantNext = cx->dormantFrameChain;
1148         cx->dormantFrameChain = oldfp;
1149     }
1151     cx->fp = &frame;
1152     if (hook)
1153         hookData = hook(cx, &frame, JS_TRUE, 0, cx->runtime->executeHookData);
1155     ok = js_Interpret(cx, result);
1157     if (hookData) {
1158         hook = cx->runtime->executeHook;
1159         if (hook)
1160             hook(cx, &frame, JS_FALSE, &ok, hookData);
1161     }
1162     cx->fp = oldfp;
1164     if (oldfp && oldfp != down) {
1165         JS_ASSERT(cx->dormantFrameChain == oldfp);
1166         cx->dormantFrameChain = oldfp->dormantNext;
1167         oldfp->dormantNext = NULL;
1168     }
1170     return ok;
1173 #if JS_HAS_EXPORT_IMPORT
1174 /*
1175  * If id is JSVAL_VOID, import all exported properties from obj.
1176  */
1177 static JSBool
1178 ImportProperty(JSContext *cx, JSObject *obj, jsid id)
1180     JSBool ok;
1181     JSIdArray *ida;
1182     JSProperty *prop;
1183     JSObject *obj2, *target, *funobj, *closure;
1184     JSString *str;
1185     uintN attrs;
1186     jsint i;
1187     jsval value;
1189     if (JSVAL_IS_VOID(id)) {
1190         ida = JS_Enumerate(cx, obj);
1191         if (!ida)
1192             return JS_FALSE;
1193         ok = JS_TRUE;
1194         if (ida->length == 0)
1195             goto out;
1196     } else {
1197         ida = NULL;
1198         if (!OBJ_LOOKUP_PROPERTY(cx, obj, id, &obj2, &prop))
1199             return JS_FALSE;
1200         if (!prop) {
1201             str = js_DecompileValueGenerator(cx, JSDVG_IGNORE_STACK,
1202                                              ID_TO_VALUE(id), NULL);
1203             if (str)
1204                 js_ReportIsNotDefined(cx, JS_GetStringBytes(str));
1205             return JS_FALSE;
1206         }
1207         ok = OBJ_GET_ATTRIBUTES(cx, obj, id, prop, &attrs);
1208         OBJ_DROP_PROPERTY(cx, obj2, prop);
1209         if (!ok)
1210             return JS_FALSE;
1211         if (!(attrs & JSPROP_EXPORTED)) {
1212             str = js_DecompileValueGenerator(cx, JSDVG_IGNORE_STACK,
1213                                              ID_TO_VALUE(id), NULL);
1214             if (str) {
1215                 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
1216                                      JSMSG_NOT_EXPORTED,
1217                                      JS_GetStringBytes(str));
1218             }
1219             return JS_FALSE;
1220         }
1221     }
1223     target = cx->fp->varobj;
1224     i = 0;
1225     do {
1226         if (ida) {
1227             id = ida->vector[i];
1228             ok = OBJ_GET_ATTRIBUTES(cx, obj, id, NULL, &attrs);
1229             if (!ok)
1230                 goto out;
1231             if (!(attrs & JSPROP_EXPORTED))
1232                 continue;
1233         }
1234         ok = OBJ_CHECK_ACCESS(cx, obj, id, JSACC_IMPORT, &value, &attrs);
1235         if (!ok)
1236             goto out;
1237         if (JSVAL_IS_FUNCTION(cx, value)) {
1238             funobj = JSVAL_TO_OBJECT(value);
1239             closure = js_CloneFunctionObject(cx, funobj, obj);
1240             if (!closure) {
1241                 ok = JS_FALSE;
1242                 goto out;
1243             }
1244             value = OBJECT_TO_JSVAL(closure);
1245         }
1247         /*
1248          * Handle the case of importing a property that refers to a local
1249          * variable or formal parameter of a function activation.  These
1250          * properties are accessed by opcodes using stack slot numbers
1251          * generated by the compiler rather than runtime name-lookup.  These
1252          * local references, therefore, bypass the normal scope chain lookup.
1253          * So, instead of defining a new property in the activation object,
1254          * modify the existing value in the stack slot.
1255          */
1256         if (OBJ_GET_CLASS(cx, target) == &js_CallClass) {
1257             ok = OBJ_LOOKUP_PROPERTY(cx, target, id, &obj2, &prop);
1258             if (!ok)
1259                 goto out;
1260         } else {
1261             prop = NULL;
1262         }
1263         if (prop && target == obj2) {
1264             ok = OBJ_SET_PROPERTY(cx, target, id, &value);
1265         } else {
1266             ok = OBJ_DEFINE_PROPERTY(cx, target, id, value, NULL, NULL,
1267                                      attrs & ~JSPROP_EXPORTED,
1268                                      NULL);
1269         }
1270         if (prop)
1271             OBJ_DROP_PROPERTY(cx, obj2, prop);
1272         if (!ok)
1273             goto out;
1274     } while (ida && ++i < ida->length);
1276 out:
1277     if (ida)
1278         JS_DestroyIdArray(cx, ida);
1279     return ok;
1281 #endif /* JS_HAS_EXPORT_IMPORT */
1283 JSBool
1284 js_CheckRedeclaration(JSContext *cx, JSObject *obj, jsid id, uintN attrs,
1285                       JSBool *foundp)
1287     JSObject *obj2;
1288     JSProperty *prop;
1289     JSBool ok;
1290     uintN oldAttrs, report;
1291     JSBool isFunction;
1292     jsval value;
1293     const char *type, *name;
1295     if (!OBJ_LOOKUP_PROPERTY(cx, obj, id, &obj2, &prop))
1296         return JS_FALSE;
1297     *foundp = (prop != NULL);
1298     if (!prop)
1299         return JS_TRUE;
1300     ok = OBJ_GET_ATTRIBUTES(cx, obj2, id, prop, &oldAttrs);
1301     OBJ_DROP_PROPERTY(cx, obj2, prop);
1302     if (!ok)
1303         return JS_FALSE;
1305     /* If either property is readonly, we have an error. */
1306     report = ((oldAttrs | attrs) & JSPROP_READONLY)
1307              ? JSREPORT_ERROR
1308              : JSREPORT_WARNING | JSREPORT_STRICT;
1310     if (report != JSREPORT_ERROR) {
1311         /*
1312          * Allow redeclaration of variables and functions, but insist that the
1313          * new value is not a getter if the old value was, ditto for setters --
1314          * unless prop is impermanent (in which case anyone could delete it and
1315          * redefine it, willy-nilly).
1316          */
1317         if (!(attrs & (JSPROP_GETTER | JSPROP_SETTER)))
1318             return JS_TRUE;
1319         if ((~(oldAttrs ^ attrs) & (JSPROP_GETTER | JSPROP_SETTER)) == 0)
1320             return JS_TRUE;
1321         if (!(oldAttrs & JSPROP_PERMANENT))
1322             return JS_TRUE;
1323         report = JSREPORT_ERROR;
1324     }
1326     isFunction = (oldAttrs & (JSPROP_GETTER | JSPROP_SETTER)) != 0;
1327     if (!isFunction) {
1328         if (!OBJ_GET_PROPERTY(cx, obj, id, &value))
1329             return JS_FALSE;
1330         isFunction = JSVAL_IS_FUNCTION(cx, value);
1331     }
1332     type = (oldAttrs & attrs & JSPROP_GETTER)
1333            ? js_getter_str
1334            : (oldAttrs & attrs & JSPROP_SETTER)
1335            ? js_setter_str
1336            : (oldAttrs & JSPROP_READONLY)
1337            ? js_const_str
1338            : isFunction
1339            ? js_function_str
1340            : js_var_str;
1341     name = js_AtomToPrintableString(cx, (JSAtom *)id);
1342     if (!name)
1343         return JS_FALSE;
1344     return JS_ReportErrorFlagsAndNumber(cx, report,
1345                                         js_GetErrorMessage, NULL,
1346                                         JSMSG_REDECLARED_VAR,
1347                                         type, name);
1350 #ifndef MAX_INTERP_LEVEL
1351 #if defined(XP_OS2)
1352 #define MAX_INTERP_LEVEL 250
1353 #elif defined _MSC_VER && _MSC_VER <= 800
1354 #define MAX_INTERP_LEVEL 30
1355 #else
1356 #define MAX_INTERP_LEVEL 1000
1357 #endif
1358 #endif
1360 #define MAX_INLINE_CALL_COUNT 1000
1362 JSBool
1363 js_Interpret(JSContext *cx, jsval *result)
1365     JSRuntime *rt;
1366     JSStackFrame *fp;
1367     JSScript *script;
1368     uintN inlineCallCount;
1369     JSObject *obj, *obj2, *proto, *parent;
1370     JSVersion currentVersion, originalVersion;
1371     JSBranchCallback onbranch;
1372     JSBool ok, cond;
1373     JSTrapHandler interruptHandler;
1374     jsint depth, len;
1375     jsval *sp, *newsp;
1376     void *mark;
1377     jsbytecode *pc, *pc2, *endpc;
1378     JSOp op, op2;
1379     const JSCodeSpec *cs;
1380     JSAtom *atom;
1381     uintN argc, slot, attrs;
1382     jsval *vp, lval, rval, ltmp, rtmp;
1383     jsid id;
1384     JSObject *withobj, *origobj, *propobj;
1385     jsval iter_state;
1386     JSProperty *prop;
1387     JSScopeProperty *sprop;
1388     JSString *str, *str2;
1389     jsint i, j;
1390     jsdouble d, d2;
1391     JSClass *clasp, *funclasp;
1392     JSFunction *fun;
1393     JSType type;
1394 #ifdef DEBUG
1395     FILE *tracefp;
1396 #endif
1397 #if JS_HAS_EXPORT_IMPORT
1398     JSIdArray *ida;
1399 #endif
1400 #if JS_HAS_SWITCH_STATEMENT
1401     jsint low, high, off, npairs;
1402     JSBool match;
1403 #endif
1404 #if JS_HAS_GETTER_SETTER
1405     JSPropertyOp getter, setter;
1406 #endif
1407     int stackDummy;
1409     *result = JSVAL_VOID;
1410     rt = cx->runtime;
1412     /* Set registerized frame pointer and derived script pointer. */
1413     fp = cx->fp;
1414     script = fp->script;
1416     /* Count of JS function calls that nest in this C js_Interpret frame. */
1417     inlineCallCount = 0;
1419     /*
1420      * Optimized Get and SetVersion for proper script language versioning.
1421      *
1422      * If any native method or JSClass/JSObjectOps hook calls JS_SetVersion
1423      * and changes cx->version, the effect will "stick" and we will stop
1424      * maintaining currentVersion.  This is relied upon by testsuites, for
1425      * the most part -- web browsers select version before compiling and not
1426      * at run-time.
1427      */
1428     currentVersion = script->version;
1429     originalVersion = cx->version;
1430     if (currentVersion != originalVersion)
1431         JS_SetVersion(cx, currentVersion);
1433     /*
1434      * Prepare to call a user-supplied branch handler, and abort the script
1435      * if it returns false.
1436      */
1437     onbranch = cx->branchCallback;
1438     ok = JS_TRUE;
1439 #define CHECK_BRANCH(len)                                                     \
1440     JS_BEGIN_MACRO                                                            \
1441         if (len <= 0 && onbranch) {                                           \
1442             SAVE_SP(fp);                                                      \
1443             if (!(ok = (*onbranch)(cx, script)))                              \
1444                 goto out;                                                     \
1445         }                                                                     \
1446     JS_END_MACRO
1448     /*
1449      * Load the debugger's interrupt hook here and after calling out to native
1450      * functions (but not to getters, setters, or other native hooks), so we do
1451      * not have to reload it each time through the interpreter loop -- we hope
1452      * the compiler can keep it in a register.
1453      * XXX if it spills, we still lose
1454      */
1455 #define LOAD_INTERRUPT_HANDLER(rt)  (interruptHandler = (rt)->interruptHandler)
1457     LOAD_INTERRUPT_HANDLER(rt);
1459     pc = script->code;
1460     endpc = pc + script->length;
1461     depth = (jsint) script->depth;
1462     len = -1;
1464     /* Check for too much js_Interpret nesting, or too deep a C stack. */
1465     if (++cx->interpLevel == MAX_INTERP_LEVEL ||
1466         !JS_CHECK_STACK_SIZE(cx, stackDummy)) {
1467         JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_OVER_RECURSED);
1468         ok = JS_FALSE;
1469         goto out;
1470     }
1472     /*
1473      * Allocate operand and pc stack slots for the script's worst-case depth.
1474      */
1475     newsp = js_AllocRawStack(cx, (uintN)(2 * depth), &mark);
1476     if (!newsp) {
1477         ok = JS_FALSE;
1478         goto out;
1479     }
1480     sp = newsp + depth;
1481     fp->spbase = sp;
1482     SAVE_SP(fp);
1484     while (pc < endpc) {
1485         fp->pc = pc;
1486         op = (JSOp) *pc;
1487       do_op:
1488         cs = &js_CodeSpec[op];
1489         len = cs->length;
1491 #ifdef DEBUG
1492         tracefp = (FILE *) cx->tracefp;
1493         if (tracefp) {
1494             intN nuses, n;
1496             fprintf(tracefp, "%4u: ", js_PCToLineNumber(cx, script, pc));
1497             js_Disassemble1(cx, script, pc,
1498                             PTRDIFF(pc, script->code, jsbytecode), JS_FALSE,
1499                             tracefp);
1500             nuses = cs->nuses;
1501             if (nuses) {
1502                 SAVE_SP(fp);
1503                 for (n = -nuses; n < 0; n++) {
1504                     str = js_DecompileValueGenerator(cx, n, sp[n], NULL);
1505                     if (str != NULL) {
1506                         fprintf(tracefp, "%s %s",
1507                                 (n == -nuses) ? "  inputs:" : ",",
1508                                 JS_GetStringBytes(str));
1509                     }
1510                 }
1511                 fprintf(tracefp, " @ %d\n", sp - fp->spbase);
1512             }
1513         }
1514 #endif
1516         if (interruptHandler) {
1517             SAVE_SP(fp);
1518             switch (interruptHandler(cx, script, pc, &rval,
1519                                      rt->interruptHandlerData)) {
1520               case JSTRAP_ERROR:
1521                 ok = JS_FALSE;
1522                 goto out;
1523               case JSTRAP_CONTINUE:
1524                 break;
1525               case JSTRAP_RETURN:
1526                 fp->rval = rval;
1527                 goto out;
1528 #if JS_HAS_EXCEPTIONS
1529               case JSTRAP_THROW:
1530                 cx->throwing = JS_TRUE;
1531                 cx->exception = rval;
1532                 ok = JS_FALSE;
1533                 goto out;
1534 #endif /* JS_HAS_EXCEPTIONS */
1535               default:;
1536             }
1537             LOAD_INTERRUPT_HANDLER(rt);
1538         }
1540         switch (op) {
1541           case JSOP_NOP:
1542             break;
1544           case JSOP_GROUP:
1545             obj = NULL;
1546             break;
1548           case JSOP_PUSH:
1549             PUSH_OPND(JSVAL_VOID);
1550             break;
1552           case JSOP_POP:
1553             sp--;
1554             break;
1556           case JSOP_POP2:
1557             sp -= 2;
1558             break;
1560           case JSOP_SWAP:
1561             /*
1562              * N.B. JSOP_SWAP doesn't swap the corresponding generating pcs
1563              * for the operands it swaps.
1564              */
1565             ltmp = sp[-1];
1566             sp[-1] = sp[-2];
1567             sp[-2] = ltmp;
1568             break;
1570           case JSOP_POPV:
1571             *result = POP_OPND();
1572             break;
1574           case JSOP_ENTERWITH:
1575             rval = FETCH_OPND(-1);
1576             VALUE_TO_OBJECT(cx, rval, obj);
1577             withobj = js_NewObject(cx, &js_WithClass, obj, fp->scopeChain);
1578             if (!withobj)
1579                 goto out;
1580             fp->scopeChain = withobj;
1581             STORE_OPND(-1, OBJECT_TO_JSVAL(withobj));
1582             break;
1584           case JSOP_LEAVEWITH:
1585             rval = POP_OPND();
1586             JS_ASSERT(JSVAL_IS_OBJECT(rval));
1587             withobj = JSVAL_TO_OBJECT(rval);
1588             JS_ASSERT(OBJ_GET_CLASS(cx, withobj) == &js_WithClass);
1590             rval = OBJ_GET_SLOT(cx, withobj, JSSLOT_PARENT);
1591             JS_ASSERT(JSVAL_IS_OBJECT(rval));
1592             fp->scopeChain = JSVAL_TO_OBJECT(rval);
1593             break;
1595           case JSOP_SETRVAL:
1596             fp->rval = POP_OPND();
1597             break;
1599           case JSOP_RETURN:
1600             CHECK_BRANCH(-1);
1601             fp->rval = POP_OPND();
1602             /* FALL THROUGH */
1604           case JSOP_RETRVAL:    /* fp->rval already set */
1605             if (inlineCallCount)
1606           inline_return:
1607             {
1608                 JSInlineFrame *ifp = (JSInlineFrame *) fp;
1609                 void *hookData = ifp->hookData;
1611                 if (hookData) {
1612                     JSInterpreterHook hook = cx->runtime->callHook;
1613                     if (hook) {
1614                         hook(cx, fp, JS_FALSE, &ok, hookData);
1615                         LOAD_INTERRUPT_HANDLER(rt);
1616                     }
1617                 }
1618 #if JS_HAS_ARGS_OBJECT
1619                 if (fp->argsobj)
1620                     ok &= js_PutArgsObject(cx, fp);
1621 #endif
1623                 /* Restore context version only if callee hasn't set version. */
1624                 if (cx->version == currentVersion) {
1625                     currentVersion = ifp->callerVersion;
1626                     if (currentVersion != cx->version)
1627                         JS_SetVersion(cx, currentVersion);
1628                 }
1630                 /* Store the return value in the caller's operand frame. */
1631                 vp = fp->argv - 2;
1632                 *vp = fp->rval;
1634                 /* Restore cx->fp and release the inline frame's space. */
1635                 cx->fp = fp = fp->down;
1636                 JS_ARENA_RELEASE(&cx->stackPool, ifp->mark);
1638                 /* Restore sp to point just above the return value. */
1639                 fp->sp = vp + 1;
1640                 RESTORE_SP(fp);
1642                 /* Restore the calling script's interpreter registers. */
1643                 script = fp->script;
1644                 depth = (jsint) script->depth;
1645                 pc = fp->pc;
1646                 endpc = script->code + script->length;
1648                 /* Store the generating pc for the return value. */
1649                 vp[-depth] = (jsval)pc;
1651                 /* Set remaining variables for 'goto advance_pc'. */
1652                 op = (JSOp) *pc;
1653                 cs = &js_CodeSpec[op];
1654                 len = cs->length;
1656                 /* Resume execution in the calling frame. */
1657                 inlineCallCount--;
1658                 if (ok)
1659                     goto advance_pc;
1660             }
1661             goto out;
1663 #if JS_HAS_SWITCH_STATEMENT
1664           case JSOP_DEFAULT:
1665             (void) POP();
1666             /* FALL THROUGH */
1667 #endif
1668           case JSOP_GOTO:
1669             len = GET_JUMP_OFFSET(pc);
1670             CHECK_BRANCH(len);
1671             break;
1673           case JSOP_IFEQ:
1674             POP_BOOLEAN(cx, rval, cond);
1675             if (cond == JS_FALSE) {
1676                 len = GET_JUMP_OFFSET(pc);
1677                 CHECK_BRANCH(len);
1678             }
1679             break;
1681           case JSOP_IFNE:
1682             POP_BOOLEAN(cx, rval, cond);
1683             if (cond != JS_FALSE) {
1684                 len = GET_JUMP_OFFSET(pc);
1685                 CHECK_BRANCH(len);
1686             }
1687             break;
1689           case JSOP_OR:
1690             POP_BOOLEAN(cx, rval, cond);
1691             if (cond == JS_TRUE) {
1692                 len = GET_JUMP_OFFSET(pc);
1693                 PUSH_OPND(rval);
1694             }
1695             break;
1697           case JSOP_AND:
1698             POP_BOOLEAN(cx, rval, cond);
1699             if (cond == JS_FALSE) {
1700                 len = GET_JUMP_OFFSET(pc);
1701                 PUSH_OPND(rval);
1702             }
1703             break;
1706 #if JS_HAS_SWITCH_STATEMENT
1707           case JSOP_DEFAULTX:
1708             (void) POP();
1709             /* FALL THROUGH */
1710 #endif
1711           case JSOP_GOTOX:
1712             len = GET_JUMPX_OFFSET(pc);
1713             CHECK_BRANCH(len);
1714             break;
1716           case JSOP_IFEQX:
1717             POP_BOOLEAN(cx, rval, cond);
1718             if (cond == JS_FALSE) {
1719                 len = GET_JUMPX_OFFSET(pc);
1720                 CHECK_BRANCH(len);
1721             }
1722             break;
1724           case JSOP_IFNEX:
1725             POP_BOOLEAN(cx, rval, cond);
1726             if (cond != JS_FALSE) {
1727                 len = GET_JUMPX_OFFSET(pc);
1728                 CHECK_BRANCH(len);
1729             }
1730             break;
1732           case JSOP_ORX:
1733             POP_BOOLEAN(cx, rval, cond);
1734             if (cond == JS_TRUE) {
1735                 len = GET_JUMPX_OFFSET(pc);
1736                 PUSH_OPND(rval);
1737             }
1738             break;
1740           case JSOP_ANDX:
1741             POP_BOOLEAN(cx, rval, cond);
1742             if (cond == JS_FALSE) {
1743                 len = GET_JUMPX_OFFSET(pc);
1744                 PUSH_OPND(rval);
1745             }
1746             break;
1748           case JSOP_TOOBJECT:
1749             SAVE_SP(fp);
1750             ok = js_ValueToObject(cx, FETCH_OPND(-1), &obj);
1751             if (!ok)
1752                 goto out;
1753             STORE_OPND(-1, OBJECT_TO_JSVAL(obj));
1754             break;
1756 #define FETCH_ELEMENT_ID(n, id)                                               \
1757     JS_BEGIN_MACRO                                                            \
1758         /* If the index is not a jsint, atomize it. */                        \
1759         id = (jsid) FETCH_OPND(n);                                            \
1760         if (JSVAL_IS_INT(id)) {                                               \
1761             atom = NULL;                                                      \
1762         } else {                                                              \
1763             SAVE_SP(fp);                                                      \
1764             atom = js_ValueToStringAtom(cx, (jsval)id);                       \
1765             if (!atom) {                                                      \
1766                 ok = JS_FALSE;                                                \
1767                 goto out;                                                     \
1768             }                                                                 \
1769             id = (jsid)atom;                                                  \
1770         }                                                                     \
1771     JS_END_MACRO
1773 #define POP_ELEMENT_ID(id)                                                    \
1774     JS_BEGIN_MACRO                                                            \
1775         FETCH_ELEMENT_ID(-1, id);                                             \
1776         sp--;                                                                 \
1777     JS_END_MACRO
1779 #if JS_HAS_IN_OPERATOR
1780           case JSOP_IN:
1781             rval = FETCH_OPND(-1);
1782             if (JSVAL_IS_PRIMITIVE(rval)) {
1783                 str = js_DecompileValueGenerator(cx, -1, rval, NULL);
1784                 if (str) {
1785                     JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
1786                                          JSMSG_IN_NOT_OBJECT,
1787                                          JS_GetStringBytes(str));
1788                 }
1789                 ok = JS_FALSE;
1790                 goto out;
1791             }
1792             sp--;
1793             obj = JSVAL_TO_OBJECT(rval);
1794             FETCH_ELEMENT_ID(-1, id);
1795             ok = OBJ_LOOKUP_PROPERTY(cx, obj, id, &obj2, &prop);
1796             if (!ok)
1797                 goto out;
1798             STORE_OPND(-1, BOOLEAN_TO_JSVAL(prop != NULL));
1799             if (prop)
1800                 OBJ_DROP_PROPERTY(cx, obj2, prop);
1801             break;
1802 #endif /* JS_HAS_IN_OPERATOR */
1804           case JSOP_FORPROP:
1805             /*
1806              * Handle JSOP_FORPROP first, so the cost of the goto do_forinloop
1807              * is not paid for the more common cases.
1808              */
1809             lval = FETCH_OPND(-1);
1810             atom = GET_ATOM(cx, script, pc);
1811             id   = (jsid)atom;
1812             i = -2;
1813             goto do_forinloop;
1815           case JSOP_FORNAME:
1816             atom = GET_ATOM(cx, script, pc);
1817             id   = (jsid)atom;
1819             /*
1820              * ECMA 12.6.3 says to eval the LHS after looking for properties
1821              * to enumerate, and bail without LHS eval if there are no props.
1822              * We do Find here to share the most code at label do_forinloop.
1823              * If looking for enumerable properties could have side effects,
1824              * then we'd have to move this into the common code and condition
1825              * it on op == JSOP_FORNAME.
1826              */
1827             SAVE_SP(fp);
1828             ok = js_FindProperty(cx, id, &obj, &obj2, &prop);
1829             if (!ok)
1830                 goto out;
1831             if (prop)
1832                 OBJ_DROP_PROPERTY(cx, obj2, prop);
1833             lval = OBJECT_TO_JSVAL(obj);
1834             /* FALL THROUGH */
1836           case JSOP_FORARG:
1837           case JSOP_FORVAR:
1838             /*
1839              * JSOP_FORARG and JSOP_FORVAR don't require any lval computation
1840              * here, because they address slots on the stack (in fp->args and
1841              * fp->vars, respectively).
1842              */
1843             /* FALL THROUGH */
1845           case JSOP_FORELEM:
1846             /*
1847              * JSOP_FORELEM simply initializes or updates the iteration state
1848              * and leaves the index expression evaluation and assignment to the
1849              * enumerator until after the next property has been acquired, via
1850              * a JSOP_ENUMELEM bytecode.
1851              */
1852             i = -1;
1854           do_forinloop:
1855             /*
1856              * ECMA-compatible for/in evals the object just once, before loop.
1857              * Bad old bytecodes (since removed) did it on every iteration.
1858              */
1859             obj = JSVAL_TO_OBJECT(sp[i]);
1861             /* If the thing to the right of 'in' has no properties, break. */
1862             if (!obj) {
1863                 rval = JSVAL_FALSE;
1864                 goto end_forinloop;
1865             }
1867             /*
1868              * Save the thing to the right of 'in' as origobj.  Later on, we
1869              * use this variable to suppress enumeration of shadowed prototype
1870              * properties.
1871              */
1872             origobj = obj;
1874             /*
1875              * Reach under the top of stack to find our property iterator, a
1876              * JSObject that contains the iteration state.  (An object is used
1877              * rather than a native struct so that the iteration state is
1878              * cleaned up via GC if the for-in loop terminates abruptly.)
1879              */
1880             vp = &sp[i - 1];
1881             rval = *vp;
1883             /* Is this the first iteration ? */
1884             if (JSVAL_IS_VOID(rval)) {
1885                 /* Yes, create a new JSObject to hold the iterator state */
1886                 propobj = js_NewObject(cx, &prop_iterator_class, NULL, obj);
1887                 if (!propobj) {
1888                     ok = JS_FALSE;
1889                     goto out;
1890                 }
1891                 propobj->slots[JSSLOT_ITER_STATE] = JSVAL_NULL;
1893                 /*
1894                  * Root the parent slot so we can get it even in our finalizer
1895                  * (otherwise, it would live as long as we do, but it might be
1896                  * finalized first).
1897                  */
1898                 ok = js_AddRoot(cx, &propobj->slots[JSSLOT_PARENT],
1899                                 "propobj->parent");
1900                 if (!ok)
1901                     goto out;
1903                 /*
1904                  * Rewrite the iterator so we know to do the next case.
1905                  * Do this before calling the enumerator, which could
1906                  * displace cx->newborn and cause GC.
1907                  */
1908                 *vp = OBJECT_TO_JSVAL(propobj);
1910                 ok = OBJ_ENUMERATE(cx, obj, JSENUMERATE_INIT, &iter_state, 0);
1912                 /*
1913                  * Stash private iteration state into property iterator object.
1914                  * We do this before checking 'ok' to ensure that propobj is
1915                  * in a valid state even if OBJ_ENUMERATE returned JS_FALSE.
1916                  * NB: This code knows that the first slots are pre-allocated.
1917                  */
1918 #if JS_INITIAL_NSLOTS < 5
1919 #error JS_INITIAL_NSLOTS must be greater than or equal to 5.
1920 #endif
1921                 propobj->slots[JSSLOT_ITER_STATE] = iter_state;
1922                 if (!ok)
1923                     goto out;
1924             } else {
1925                 /* This is not the first iteration. Recover iterator state. */
1926                 propobj = JSVAL_TO_OBJECT(rval);
1927                 obj = JSVAL_TO_OBJECT(propobj->slots[JSSLOT_PARENT]);
1928                 iter_state = propobj->slots[JSSLOT_ITER_STATE];
1929             }
1931           enum_next_property:
1932             /* Get the next jsid to be enumerated and store it in rval. */
1933             OBJ_ENUMERATE(cx, obj, JSENUMERATE_NEXT, &iter_state, &rval);
1934             propobj->slots[JSSLOT_ITER_STATE] = iter_state;
1936             /* No more jsids to iterate in obj? */
1937             if (iter_state == JSVAL_NULL) {
1938                 /* Enumerate the properties on obj's prototype chain. */
1939                 obj = OBJ_GET_PROTO(cx, obj);
1940                 if (!obj) {
1941                     /* End of property list -- terminate loop. */
1942                     rval = JSVAL_FALSE;
1943                     goto end_forinloop;
1944                 }
1946                 ok = OBJ_ENUMERATE(cx, obj, JSENUMERATE_INIT, &iter_state, 0);
1948                 /*
1949                  * Stash private iteration state into property iterator object.
1950                  * We do this before checking 'ok' to ensure that propobj is
1951                  * in a valid state even if OBJ_ENUMERATE returned JS_FALSE.
1952                  * NB: This code knows that the first slots are pre-allocated.
1953                  */
1954                 propobj->slots[JSSLOT_ITER_STATE] = iter_state;
1955                 if (!ok)
1956                     goto out;
1958                 /*
1959                  * Update the iterator JSObject's parent link to refer to the
1960                  * current object. This is used in the iterator JSObject's
1961                  * finalizer.
1962                  */
1963                 propobj->slots[JSSLOT_PARENT] = OBJECT_TO_JSVAL(obj);
1964                 goto enum_next_property;
1965             }
1967             /* Skip properties not owned by obj, and leave next id in rval. */
1968             ok = OBJ_LOOKUP_PROPERTY(cx, origobj, rval, &obj2, &prop);
1969             if (!ok)
1970                 goto out;
1971             if (prop) {
1972                 OBJ_DROP_PROPERTY(cx, obj2, prop);
1974                 /* Yes, don't enumerate again.  Go to the next property. */
1975                 if (obj2 != obj)
1976                     goto enum_next_property;
1977             }
1979             /* Make sure rval is a string for uniformity and compatibility. */
1980             if (!JSVAL_IS_INT(rval)) {
1981                 rval = ATOM_KEY((JSAtom *)rval);
1982             } else if (cx->version != JSVERSION_1_2) {
1983                 str = js_NumberToString(cx, (jsdouble) JSVAL_TO_INT(rval));
1984                 if (!str) {
1985                     ok = JS_FALSE;
1986                     goto out;
1987                 }
1989                 rval = STRING_TO_JSVAL(str);
1990             }
1992             switch (op) {
1993               case JSOP_FORARG:
1994                 slot = GET_ARGNO(pc);
1995                 JS_ASSERT(slot < fp->fun->nargs);
1996                 fp->argv[slot] = rval;
1997                 break;
1999               case JSOP_FORVAR:
2000                 slot = GET_VARNO(pc);
2001                 JS_ASSERT(slot < fp->fun->nvars);
2002                 fp->vars[slot] = rval;
2003                 break;
2005               case JSOP_FORELEM:
2006                 /* FORELEM is not a SET operation, it's more like BINDNAME. */
2007                 PUSH_OPND(rval);
2008                 break;
2010               default:
2011                 /* Convert lval to a non-null object containing id. */
2012                 VALUE_TO_OBJECT(cx, lval, obj);
2014                 /* Set the variable obj[id] to refer to rval. */
2015                 fp->flags |= JSFRAME_ASSIGNING;
2016                 ok = OBJ_SET_PROPERTY(cx, obj, id, &rval);
2017                 fp->flags &= ~JSFRAME_ASSIGNING;
2018                 if (!ok)
2019                     goto out;
2020                 break;
2021             }
2023             /* Push true to keep looping through properties. */
2024             rval = JSVAL_TRUE;
2026           end_forinloop:
2027             sp += i + 1;
2028             PUSH_OPND(rval);
2029             break;
2031           case JSOP_DUP:
2032             JS_ASSERT(sp > fp->spbase);
2033             rval = sp[-1];
2034             PUSH_OPND(rval);
2035             break;
2037           case JSOP_DUP2:
2038             JS_ASSERT(sp - 1 > fp->spbase);
2039             lval = FETCH_OPND(-2);
2040             rval = FETCH_OPND(-1);
2041             PUSH_OPND(lval);
2042             PUSH_OPND(rval);
2043             break;
2045 #define PROPERTY_OP(n, call)                                                  \
2046     JS_BEGIN_MACRO                                                            \
2047         /* Pop the left part and resolve it to a non-null object. */          \
2048         lval = FETCH_OPND(n);                                                 \
2049         VALUE_TO_OBJECT(cx, lval, obj);                                       \
2050                                                                               \
2051         /* Get or set the property, set ok false if error, true if success. */\
2052         SAVE_SP(fp);                                                          \
2053         call;                                                                 \
2054         if (!ok)                                                              \
2055             goto out;                                                         \
2056     JS_END_MACRO
2058 #define ELEMENT_OP(n, call)                                                   \
2059     JS_BEGIN_MACRO                                                            \
2060         FETCH_ELEMENT_ID(n, id);                                              \
2061         PROPERTY_OP(n-1, call);                                               \
2062     JS_END_MACRO
2064 /*
2065  * Direct callers, i.e. those who do not wrap CACHED_GET and CACHED_SET calls
2066  * in PROPERTY_OP or ELEMENT_OP macro calls must SAVE_SP(fp); beforehand, just
2067  * in case a getter or setter function is invoked.
2068  */
2069 #define CACHED_GET(call)                                                      \
2070     JS_BEGIN_MACRO                                                            \
2071         if (!OBJ_IS_NATIVE(obj)) {                                            \
2072             ok = call;                                                        \
2073         } else {                                                              \
2074             JS_LOCK_OBJ(cx, obj);                                             \
2075             PROPERTY_CACHE_TEST(&rt->propertyCache, obj, id, sprop);          \
2076             if (sprop) {                                                      \
2077                 JSScope *scope_ = OBJ_SCOPE(obj);                             \
2078                 slot = (uintN)sprop->slot;                                    \
2079                 rval = (slot != SPROP_INVALID_SLOT)                           \
2080                        ? LOCKED_OBJ_GET_SLOT(obj, slot)                       \
2081                        : JSVAL_VOID;                                          \
2082                 JS_UNLOCK_SCOPE(cx, scope_);                                  \
2083                 ok = SPROP_GET(cx, sprop, obj, obj, &rval);                   \
2084                 JS_LOCK_SCOPE(cx, scope_);                                    \
2085                 if (ok && SPROP_HAS_VALID_SLOT(sprop, scope_))                \
2086                     LOCKED_OBJ_SET_SLOT(obj, slot, rval);                     \
2087                 JS_UNLOCK_SCOPE(cx, scope_);                                  \
2088             } else {                                                          \
2089                 JS_UNLOCK_OBJ(cx, obj);                                       \
2090                 ok = call;                                                    \
2091                 /* No fill here: js_GetProperty fills the cache. */           \
2092             }                                                                 \
2093         }                                                                     \
2094     JS_END_MACRO
2096 #define CACHED_SET(call)                                                      \
2097     JS_BEGIN_MACRO                                                            \
2098         if (!OBJ_IS_NATIVE(obj)) {                                            \
2099             ok = call;                                                        \
2100         } else {                                                              \
2101             JSScope *scope_;                                                  \
2102             JS_LOCK_OBJ(cx, obj);                                             \
2103             PROPERTY_CACHE_TEST(&rt->propertyCache, obj, id, sprop);          \
2104             if (sprop &&                                                      \
2105                 !(sprop->attrs & JSPROP_READONLY) &&                          \
2106                 (scope_ = OBJ_SCOPE(obj), !SCOPE_IS_SEALED(scope_))) {        \
2107                 JS_UNLOCK_SCOPE(cx, scope_);                                  \
2108                 ok = SPROP_SET(cx, sprop, obj, obj, &rval);                   \
2109                 JS_LOCK_SCOPE(cx, scope_);                                    \
2110                 if (ok && SPROP_HAS_VALID_SLOT(sprop, scope_)) {              \
2111                     LOCKED_OBJ_SET_SLOT(obj, sprop->slot, rval);              \
2112                     GC_POKE(cx, JSVAL_NULL);  /* XXX second arg ignored */    \
2113                 }                                                             \
2114                 JS_UNLOCK_SCOPE(cx, scope_);                                  \
2115             } else {                                                          \
2116                 JS_UNLOCK_OBJ(cx, obj);                                       \
2117                 ok = call;                                                    \
2118                 /* No fill here: js_SetProperty writes through the cache. */  \
2119             }                                                                 \
2120         }                                                                     \
2121     JS_END_MACRO
2123           case JSOP_SETCONST:
2124             obj = fp->varobj;
2125             atom = GET_ATOM(cx, script, pc);
2126             rval = FETCH_OPND(-1);
2127             ok = OBJ_DEFINE_PROPERTY(cx, obj, (jsid)atom, rval, NULL, NULL,
2128                                      JSPROP_ENUMERATE | JSPROP_PERMANENT |
2129                                      JSPROP_READONLY,
2130                                      NULL);
2131             if (!ok)
2132                 goto out;
2133             STORE_OPND(-1, rval);
2134             break;
2136           case JSOP_BINDNAME:
2137             atom = GET_ATOM(cx, script, pc);
2138             SAVE_SP(fp);
2139             obj = js_FindIdentifierBase(cx, (jsid)atom);
2140             if (!obj) {
2141                 ok = JS_FALSE;
2142                 goto out;
2143             }
2144             PUSH_OPND(OBJECT_TO_JSVAL(obj));
2145             break;
2147           case JSOP_SETNAME:
2148             atom = GET_ATOM(cx, script, pc);
2149             id   = (jsid)atom;
2150             rval = FETCH_OPND(-1);
2151             lval = FETCH_OPND(-2);
2152             JS_ASSERT(!JSVAL_IS_PRIMITIVE(lval));
2153             obj  = JSVAL_TO_OBJECT(lval);
2154             SAVE_SP(fp);
2155             CACHED_SET(OBJ_SET_PROPERTY(cx, obj, id, &rval));
2156             if (!ok)
2157                 goto out;
2158             sp--;
2159             STORE_OPND(-1, rval);
2160             break;
2162 #define INTEGER_OP(OP, EXTRA_CODE)                                            \
2163     JS_BEGIN_MACRO                                                            \
2164         FETCH_INT(cx, -1, j);                                                 \
2165         FETCH_INT(cx, -2, i);                                                 \
2166         if (!ok)                                                              \
2167             goto out;                                                         \
2168         EXTRA_CODE                                                            \
2169         d = i OP j;                                                           \
2170         sp--;                                                                 \
2171         STORE_NUMBER(cx, -1, d);                                              \
2172     JS_END_MACRO
2174 #define BITWISE_OP(OP)          INTEGER_OP(OP, (void) 0;)
2175 #define SIGNED_SHIFT_OP(OP)     INTEGER_OP(OP, j &= 31;)
2177           case JSOP_BITOR:
2178             BITWISE_OP(|);
2179             break;
2181           case JSOP_BITXOR:
2182             BITWISE_OP(^);
2183             break;
2185           case JSOP_BITAND:
2186             BITWISE_OP(&);
2187             break;
2189 #if defined(XP_WIN)
2190 #define COMPARE_DOUBLES(LVAL, OP, RVAL, IFNAN)                                \
2191     ((JSDOUBLE_IS_NaN(LVAL) || JSDOUBLE_IS_NaN(RVAL))                         \
2192      ? (IFNAN)                                                                \
2193      : (LVAL) OP (RVAL))
2194 #else
2195 #define COMPARE_DOUBLES(LVAL, OP, RVAL, IFNAN) ((LVAL) OP (RVAL))
2196 #endif
2198 #define RELATIONAL_OP(OP)                                                     \
2199     JS_BEGIN_MACRO                                                            \
2200         rval = FETCH_OPND(-1);                                                \
2201         lval = FETCH_OPND(-2);                                                \
2202         /* Optimize for two int-tagged operands (typical loop control). */    \
2203         if ((lval & rval) & JSVAL_INT) {                                      \
2204             ltmp = lval ^ JSVAL_VOID;                                         \
2205             rtmp = rval ^ JSVAL_VOID;                                         \
2206             if (ltmp && rtmp) {                                               \
2207                 cond = JSVAL_TO_INT(lval) OP JSVAL_TO_INT(rval);              \
2208             } else {                                                          \
2209                 d  = ltmp ? JSVAL_TO_INT(lval) : *rt->jsNaN;                  \
2210                 d2 = rtmp ? JSVAL_TO_INT(rval) : *rt->jsNaN;                  \
2211                 cond = COMPARE_DOUBLES(d, OP, d2, JS_FALSE);                  \
2212             }                                                                 \
2213         } else {                                                              \
2214             VALUE_TO_PRIMITIVE(cx, lval, JSTYPE_NUMBER, &lval);               \
2215             VALUE_TO_PRIMITIVE(cx, rval, JSTYPE_NUMBER, &rval);               \
2216             if (JSVAL_IS_STRING(lval) && JSVAL_IS_STRING(rval)) {             \
2217                 str  = JSVAL_TO_STRING(lval);                                 \
2218                 str2 = JSVAL_TO_STRING(rval);                                 \
2219                 cond = js_CompareStrings(str, str2) OP 0;                     \
2220             } else {                                                          \
2221                 VALUE_TO_NUMBER(cx, lval, d);                                 \
2222                 VALUE_TO_NUMBER(cx, rval, d2);                                \
2223                 cond = COMPARE_DOUBLES(d, OP, d2, JS_FALSE);                  \
2224             }                                                                 \
2225         }                                                                     \
2226         sp--;                                                                 \
2227         STORE_OPND(-1, BOOLEAN_TO_JSVAL(cond));                               \
2228     JS_END_MACRO
2230 #define EQUALITY_OP(OP, IFNAN)                                                \
2231     JS_BEGIN_MACRO                                                            \
2232         rval = FETCH_OPND(-1);                                                \
2233         lval = FETCH_OPND(-2);                                                \
2234         ltmp = JSVAL_TAG(lval);                                               \
2235         rtmp = JSVAL_TAG(rval);                                               \
2236         if (ltmp == rtmp) {                                                   \
2237             if (ltmp == JSVAL_STRING) {                                       \
2238                 str  = JSVAL_TO_STRING(lval);                                 \
2239                 str2 = JSVAL_TO_STRING(rval);                                 \
2240                 cond = js_CompareStrings(str, str2) OP 0;                     \
2241             } else if (ltmp == JSVAL_DOUBLE) {                                \
2242                 d  = *JSVAL_TO_DOUBLE(lval);                                  \
2243                 d2 = *JSVAL_TO_DOUBLE(rval);                                  \
2244                 cond = COMPARE_DOUBLES(d, OP, d2, IFNAN);                     \
2245             } else {                                                          \
2246                 /* Handle all undefined (=>NaN) and int combinations. */      \
2247                 cond = lval OP rval;                                          \
2248             }                                                                 \
2249         } else {                                                              \
2250             if (JSVAL_IS_NULL(lval) || JSVAL_IS_VOID(lval)) {                 \
2251                 cond = (JSVAL_IS_NULL(rval) || JSVAL_IS_VOID(rval)) OP 1;     \
2252             } else if (JSVAL_IS_NULL(rval) || JSVAL_IS_VOID(rval)) {          \
2253                 cond = 1 OP 0;                                                \
2254             } else {                                                          \
2255                 if (ltmp == JSVAL_OBJECT) {                                   \
2256                     VALUE_TO_PRIMITIVE(cx, lval, JSTYPE_VOID, &lval);         \
2257                     ltmp = JSVAL_TAG(lval);                                   \
2258                 } else if (rtmp == JSVAL_OBJECT) {                            \
2259                     VALUE_TO_PRIMITIVE(cx, rval, JSTYPE_VOID, &rval);         \
2260                     rtmp = JSVAL_TAG(rval);                                   \
2261                 }                                                             \
2262                 if (ltmp == JSVAL_STRING && rtmp == JSVAL_STRING) {           \
2263                     str  = JSVAL_TO_STRING(lval);                             \
2264                     str2 = JSVAL_TO_STRING(rval);                             \
2265                     cond = js_CompareStrings(str, str2) OP 0;                 \
2266                 } else {                                                      \
2267                     VALUE_TO_NUMBER(cx, lval, d);                             \
2268                     VALUE_TO_NUMBER(cx, rval, d2);                            \
2269                     cond = COMPARE_DOUBLES(d, OP, d2, IFNAN);                 \
2270                 }                                                             \
2271             }                                                                 \
2272         }                                                                     \
2273         sp--;                                                                 \
2274         STORE_OPND(-1, BOOLEAN_TO_JSVAL(cond));                               \
2275     JS_END_MACRO
2277           case JSOP_EQ:
2278             EQUALITY_OP(==, JS_FALSE);
2279             break;
2281           case JSOP_NE:
2282             EQUALITY_OP(!=, JS_TRUE);
2283             break;
2285 #if !JS_BUG_FALLIBLE_EQOPS
2286 #define NEW_EQUALITY_OP(OP, IFNAN)                                            \
2287     JS_BEGIN_MACRO                                                            \
2288         rval = FETCH_OPND(-1);                                                \
2289         lval = FETCH_OPND(-2);                                                \
2290         ltmp = JSVAL_TAG(lval);                                               \
2291         rtmp = JSVAL_TAG(rval);                                               \
2292         if (ltmp == rtmp) {                                                   \
2293             if (ltmp == JSVAL_STRING) {                                       \
2294                 str  = JSVAL_TO_STRING(lval);                                 \
2295                 str2 = JSVAL_TO_STRING(rval);                                 \
2296                 cond = js_CompareStrings(str, str2) OP 0;                     \
2297             } else if (ltmp == JSVAL_DOUBLE) {                                \
2298                 d  = *JSVAL_TO_DOUBLE(lval);                                  \
2299                 d2 = *JSVAL_TO_DOUBLE(rval);                                  \
2300                 cond = COMPARE_DOUBLES(d, OP, d2, IFNAN);                     \
2301             } else {                                                          \
2302                 cond = lval OP rval;                                          \
2303             }                                                                 \
2304         } else {                                                              \
2305             if (ltmp == JSVAL_DOUBLE && JSVAL_IS_INT(rval)) {                 \
2306                 d  = *JSVAL_TO_DOUBLE(lval);                                  \
2307                 d2 = JSVAL_TO_INT(rval);                                      \
2308                 cond = COMPARE_DOUBLES(d, OP, d2, IFNAN);                     \
2309             } else if (JSVAL_IS_INT(lval) && rtmp == JSVAL_DOUBLE) {          \
2310                 d  = JSVAL_TO_INT(lval);                                      \
2311                 d2 = *JSVAL_TO_DOUBLE(rval);                                  \
2312                 cond = COMPARE_DOUBLES(d, OP, d2, IFNAN);                     \
2313             } else {                                                          \
2314                 cond = lval OP rval;                                          \
2315             }                                                                 \
2316         }                                                                     \
2317         sp--;                                                                 \
2318         STORE_OPND(-1, BOOLEAN_TO_JSVAL(cond));                               \
2319     JS_END_MACRO
2321           case JSOP_NEW_EQ:
2322             NEW_EQUALITY_OP(==, JS_FALSE);
2323             break;
2325           case JSOP_NEW_NE:
2326             NEW_EQUALITY_OP(!=, JS_TRUE);
2327             break;
2329 #if JS_HAS_SWITCH_STATEMENT
2330           case JSOP_CASE:
2331             NEW_EQUALITY_OP(==, JS_FALSE);
2332             (void) POP();
2333             if (cond) {
2334                 len = GET_JUMP_OFFSET(pc);
2335                 CHECK_BRANCH(len);
2336             } else {
2337                 PUSH(lval);
2338             }
2339             break;
2341           case JSOP_CASEX:
2342             NEW_EQUALITY_OP(==, JS_FALSE);
2343             (void) POP();
2344             if (cond) {
2345                 len = GET_JUMPX_OFFSET(pc);
2346                 CHECK_BRANCH(len);
2347             } else {
2348                 PUSH(lval);
2349             }
2350             break;
2351 #endif
2353 #endif /* !JS_BUG_FALLIBLE_EQOPS */
2355           case JSOP_LT:
2356             RELATIONAL_OP(<);
2357             break;
2359           case JSOP_LE:
2360             RELATIONAL_OP(<=);
2361             break;
2363           case JSOP_GT:
2364             RELATIONAL_OP(>);
2365             break;
2367           case JSOP_GE:
2368             RELATIONAL_OP(>=);
2369             break;
2371 #undef EQUALITY_OP
2372 #undef RELATIONAL_OP
2374           case JSOP_LSH:
2375             SIGNED_SHIFT_OP(<<);
2376             break;
2378           case JSOP_RSH:
2379             SIGNED_SHIFT_OP(>>);
2380             break;
2382           case JSOP_URSH:
2383           {
2384             uint32 u;
2386             FETCH_INT(cx, -1, j);
2387             FETCH_UINT(cx, -2, u);
2388             j &= 31;
2389             d = u >> j;
2390             sp--;
2391             STORE_NUMBER(cx, -1, d);
2392             break;
2393           }
2395 #undef INTEGER_OP
2396 #undef BITWISE_OP
2397 #undef SIGNED_SHIFT_OP
2399           case JSOP_ADD:
2400             rval = FETCH_OPND(-1);
2401             lval = FETCH_OPND(-2);
2402             VALUE_TO_PRIMITIVE(cx, lval, JSTYPE_VOID, &ltmp);
2403             VALUE_TO_PRIMITIVE(cx, rval, JSTYPE_VOID, &rtmp);
2404             if ((cond = JSVAL_IS_STRING(ltmp)) || JSVAL_IS_STRING(rtmp)) {
2405                 if (cond) {
2406                     str = JSVAL_TO_STRING(ltmp);
2407                     SAVE_SP(fp);
2408                     ok = (str2 = js_ValueToString(cx, rtmp)) != NULL;
2409                 } else {
2410                     str2 = JSVAL_TO_STRING(rtmp);
2411                     SAVE_SP(fp);
2412                     ok = (str = js_ValueToString(cx, ltmp)) != NULL;
2413                 }
2414                 if (!ok)
2415                     goto out;
2416                 str = js_ConcatStrings(cx, str, str2);
2417                 if (!str) {
2418                     ok = JS_FALSE;
2419                     goto out;
2420                 }
2421                 sp--;
2422                 STORE_OPND(-1, STRING_TO_JSVAL(str));
2423             } else {
2424                 VALUE_TO_NUMBER(cx, lval, d);
2425                 VALUE_TO_NUMBER(cx, rval, d2);
2426                 d += d2;
2427                 sp--;
2428                 STORE_NUMBER(cx, -1, d);
2429             }
2430             break;
2432 #define BINARY_OP(OP)                                                         \
2433     JS_BEGIN_MACRO                                                            \
2434         FETCH_NUMBER(cx, -1, d2);                                             \
2435         FETCH_NUMBER(cx, -2, d);                                              \
2436         d = d OP d2;                                                          \
2437         sp--;                                                                 \
2438         STORE_NUMBER(cx, -1, d);                                              \
2439     JS_END_MACRO
2441           case JSOP_SUB:
2442             BINARY_OP(-);
2443             break;
2445           case JSOP_MUL:
2446             BINARY_OP(*);
2447             break;
2449           case JSOP_DIV:
2450             FETCH_NUMBER(cx, -1, d2);
2451             FETCH_NUMBER(cx, -2, d);
2452             sp--;
2453             if (d2 == 0) {
2454 #if defined(XP_WIN)
2455                 /* XXX MSVC miscompiles such that (NaN == 0) */
2456                 if (JSDOUBLE_IS_NaN(d2))
2457                     rval = DOUBLE_TO_JSVAL(rt->jsNaN);
2458                 else
2459 #endif
2460                 if (d == 0 || JSDOUBLE_IS_NaN(d))
2461                     rval = DOUBLE_TO_JSVAL(rt->jsNaN);
2462                 else if ((JSDOUBLE_HI32(d) ^ JSDOUBLE_HI32(d2)) >> 31)
2463                     rval = DOUBLE_TO_JSVAL(rt->jsNegativeInfinity);
2464                 else
2465                     rval = DOUBLE_TO_JSVAL(rt->jsPositiveInfinity);
2466                 STORE_OPND(-1, rval);
2467             } else {
2468                 d /= d2;
2469                 STORE_NUMBER(cx, -1, d);
2470             }
2471             break;
2473           case JSOP_MOD:
2474             FETCH_NUMBER(cx, -1, d2);
2475             FETCH_NUMBER(cx, -2, d);
2476             sp--;
2477             if (d2 == 0) {
2478                 STORE_OPND(-1, DOUBLE_TO_JSVAL(rt->jsNaN));
2479             } else {
2480 #if defined(XP_WIN)
2481               /* Workaround MS fmod bug where 42 % (1/0) => NaN, not 42. */
2482               if (!(JSDOUBLE_IS_FINITE(d) && JSDOUBLE_IS_INFINITE(d2)))
2483 #endif
2484                 d = fmod(d, d2);
2485                 STORE_NUMBER(cx, -1, d);
2486             }
2487             break;
2489           case JSOP_NOT:
2490             POP_BOOLEAN(cx, rval, cond);
2491             PUSH_OPND(BOOLEAN_TO_JSVAL(!cond));
2492             break;
2494           case JSOP_BITNOT:
2495             FETCH_INT(cx, -1, i);
2496             d = (jsdouble) ~i;
2497             STORE_NUMBER(cx, -1, d);
2498             break;
2500           case JSOP_NEG:
2501             FETCH_NUMBER(cx, -1, d);
2502 #ifdef HPUX
2503             /*
2504              * Negation of a zero doesn't produce a negative
2505              * zero on HPUX. Perform the operation by bit
2506              * twiddling.
2507              */
2508             JSDOUBLE_HI32(d) ^= JSDOUBLE_HI32_SIGNBIT;
2509 #else
2510             d = -d;
2511 #endif
2512             STORE_NUMBER(cx, -1, d);
2513             break;
2515           case JSOP_POS:
2516             FETCH_NUMBER(cx, -1, d);
2517             STORE_NUMBER(cx, -1, d);
2518             break;
2520           case JSOP_NEW:
2521             /* Get immediate argc and find the constructor function. */
2522             argc = GET_ARGC(pc);
2524 #if JS_HAS_INITIALIZERS
2525           do_new:
2526 #endif
2527             vp = sp - (2 + argc);
2528             JS_ASSERT(vp >= fp->spbase);
2530             fun = NULL;
2531             obj2 = NULL;
2532             lval = *vp;
2533             if (!JSVAL_IS_OBJECT(lval) ||
2534                 (obj2 = JSVAL_TO_OBJECT(lval)) == NULL ||
2535                 /* XXX clean up to avoid special cases above ObjectOps layer */
2536                 OBJ_GET_CLASS(cx, obj2) == &js_FunctionClass ||
2537                 !obj2->map->ops->construct)
2538             {
2539                 SAVE_SP(fp);
2540                 fun = js_ValueToFunction(cx, vp, JSV2F_CONSTRUCT);
2541                 if (!fun) {
2542                     ok = JS_FALSE;
2543                     goto out;
2544                 }
2545             }
2547             clasp = &js_ObjectClass;
2548             if (!obj2) {
2549                 proto = parent = NULL;
2550                 fun = NULL;
2551             } else {
2552                 /* Get the constructor prototype object for this function. */
2553                 ok = OBJ_GET_PROPERTY(cx, obj2,
2554                                       (jsid)rt->atomState.classPrototypeAtom,
2555                                       &rval);
2556                 if (!ok)
2557                     goto out;
2558                 proto = JSVAL_IS_OBJECT(rval) ? JSVAL_TO_OBJECT(rval) : NULL;
2559                 parent = OBJ_GET_PARENT(cx, obj2);
2561                 if (OBJ_GET_CLASS(cx, obj2) == &js_FunctionClass) {
2562                     funclasp = ((JSFunction *)JS_GetPrivate(cx, obj2))->clasp;
2563                     if (funclasp)
2564                         clasp = funclasp;
2565                 }
2566             }
2567             obj = js_NewObject(cx, clasp, proto, parent);
2568             if (!obj) {
2569                 ok = JS_FALSE;
2570                 goto out;
2571             }
2573             /* Now we have an object with a constructor method; call it. */
2574             vp[1] = OBJECT_TO_JSVAL(obj);
2575             SAVE_SP(fp);
2576             ok = js_Invoke(cx, argc, JSINVOKE_CONSTRUCT);
2577             RESTORE_SP(fp);
2578             LOAD_INTERRUPT_HANDLER(rt);
2579             if (!ok) {
2580                 cx->newborn[GCX_OBJECT] = NULL;
2581                 goto out;
2582             }
2584             /* Check the return value and update obj from it. */
2585             rval = *vp;
2586             if (JSVAL_IS_PRIMITIVE(rval)) {
2587                 if (fun || !JSVERSION_IS_ECMA(cx->version)) {
2588                     *vp = OBJECT_TO_JSVAL(obj);
2589                     break;
2590                 }
2591                 /* native [[Construct]] returning primitive is error */
2592                 str = js_ValueToString(cx, rval);
2593                 if (str) {
2594                     JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
2595                                          JSMSG_BAD_NEW_RESULT,
2596                                          JS_GetStringBytes(str));
2597                 }
2598                 ok = JS_FALSE;
2599                 goto out;
2600             }
2601             obj = JSVAL_TO_OBJECT(rval);
2602             JS_RUNTIME_METER(rt, constructs);
2603             break;
2605           case JSOP_DELNAME:
2606             atom = GET_ATOM(cx, script, pc);
2607             id   = (jsid)atom;
2609             SAVE_SP(fp);
2610             ok = js_FindProperty(cx, id, &obj, &obj2, &prop);
2611             if (!ok)
2612                 goto out;
2614             /* ECMA says to return true if name is undefined or inherited. */
2615             rval = JSVAL_TRUE;
2616             if (prop) {
2617                 OBJ_DROP_PROPERTY(cx, obj2, prop);
2618                 ok = OBJ_DELETE_PROPERTY(cx, obj, id, &rval);
2619                 if (!ok)
2620                     goto out;
2621             }
2622             PUSH_OPND(rval);
2623             break;
2625           case JSOP_DELPROP:
2626             atom = GET_ATOM(cx, script, pc);
2627             id   = (jsid)atom;
2628             PROPERTY_OP(-1, ok = OBJ_DELETE_PROPERTY(cx, obj, id, &rval));
2629             STORE_OPND(-1, rval);
2630             break;
2632           case JSOP_DELELEM:
2633             ELEMENT_OP(-1, ok = OBJ_DELETE_PROPERTY(cx, obj, id, &rval));
2634             sp--;
2635             STORE_OPND(-1, rval);
2636             break;
2638           case JSOP_TYPEOF:
2639             rval = POP_OPND();
2640             type = JS_TypeOfValue(cx, rval);
2641             atom = rt->atomState.typeAtoms[type];
2642             str  = ATOM_TO_STRING(atom);
2643             PUSH_OPND(STRING_TO_JSVAL(str));
2644             break;
2646           case JSOP_VOID:
2647             (void) POP_OPND();
2648             PUSH_OPND(JSVAL_VOID);
2649             break;
2651           case JSOP_INCNAME:
2652           case JSOP_DECNAME:
2653           case JSOP_NAMEINC:
2654           case JSOP_NAMEDEC:
2655             atom = GET_ATOM(cx, script, pc);
2656             id   = (jsid)atom;
2658             SAVE_SP(fp);
2659             ok = js_FindProperty(cx, id, &obj, &obj2, &prop);
2660             if (!ok)
2661                 goto out;
2662             if (!prop)
2663                 goto atom_not_defined;
2665             OBJ_DROP_PROPERTY(cx, obj2, prop);
2666             lval = OBJECT_TO_JSVAL(obj);
2667             goto do_incop;
2669           case JSOP_INCPROP:
2670           case JSOP_DECPROP:
2671           case JSOP_PROPINC:
2672           case JSOP_PROPDEC:
2673             atom = GET_ATOM(cx, script, pc);
2674             id   = (jsid)atom;
2675             lval = POP_OPND();
2676             goto do_incop;
2678           case JSOP_INCELEM:
2679           case JSOP_DECELEM:
2680           case JSOP_ELEMINC:
2681           case JSOP_ELEMDEC:
2682             POP_ELEMENT_ID(id);
2683             lval = POP_OPND();
2685           do_incop:
2686             VALUE_TO_OBJECT(cx, lval, obj);
2688             /* The operand must contain a number. */
2689             SAVE_SP(fp);
2690             CACHED_GET(OBJ_GET_PROPERTY(cx, obj, id, &rval));
2691             if (!ok)
2692                 goto out;
2694             /* The expression result goes in rtmp, the updated value in rval. */
2695             if (JSVAL_IS_INT(rval) &&
2696                 rval != INT_TO_JSVAL(JSVAL_INT_MIN) &&
2697                 rval != INT_TO_JSVAL(JSVAL_INT_MAX)) {
2698                 if (cs->format & JOF_POST) {
2699                     rtmp = rval;
2700                     (cs->format & JOF_INC) ? (rval += 2) : (rval -= 2);
2701                 } else {
2702                     (cs->format & JOF_INC) ? (rval += 2) : (rval -= 2);
2703                     rtmp = rval;
2704                 }
2705             } else {
2707 /*
2708  * Initially, rval contains the value to increment or decrement, which is not
2709  * yet converted.  As above, the expression result goes in rtmp, the updated
2710  * value goes in rval.
2711  */
2712 #define NONINT_INCREMENT_OP()                                                 \
2713     JS_BEGIN_MACRO                                                            \
2714         VALUE_TO_NUMBER(cx, rval, d);                                         \
2715         if (cs->format & JOF_POST) {                                          \
2716             rtmp = rval;                                                      \
2717             if (!JSVAL_IS_NUMBER(rtmp)) {                                     \
2718                 ok = js_NewNumberValue(cx, d, &rtmp);                         \
2719                 if (!ok)                                                      \
2720                     goto out;                                                 \
2721             }                                                                 \
2722             (cs->format & JOF_INC) ? d++ : d--;                               \
2723             ok = js_NewNumberValue(cx, d, &rval);                             \
2724         } else {                                                              \
2725             (cs->format & JOF_INC) ? ++d : --d;                               \
2726             ok = js_NewNumberValue(cx, d, &rval);                             \
2727             rtmp = rval;                                                      \
2728         }                                                                     \
2729         if (!ok)                                                              \
2730             goto out;                                                         \
2731     JS_END_MACRO
2733                 NONINT_INCREMENT_OP();
2734             }
2736             CACHED_SET(OBJ_SET_PROPERTY(cx, obj, id, &rval));
2737             if (!ok)
2738                 goto out;
2739             PUSH_OPND(rtmp);
2740             break;
2742 /*
2743  * NB: This macro can't use JS_BEGIN_MACRO/JS_END_MACRO around its body because
2744  * it must break from the switch case that calls it, not from the do...while(0)
2745  * loop created by the JS_BEGIN/END_MACRO brackets.
2746  */
2747 #define FAST_INCREMENT_OP(SLOT,COUNT,BASE,PRE,OP,MINMAX)                      \
2748     slot = (uintN)SLOT;                                                       \
2749     JS_ASSERT(slot < fp->fun->COUNT);                                         \
2750     vp = fp->BASE + slot;                                                     \
2751     rval = *vp;                                                               \
2752     if (JSVAL_IS_INT(rval) &&                                                 \
2753         rval != INT_TO_JSVAL(JSVAL_INT_##MINMAX)) {                           \
2754         PRE = rval;                                                           \
2755         rval OP 2;                                                            \
2756         *vp = rval;                                                           \
2757         PUSH_OPND(PRE);                                                       \
2758         break;                                                                \
2759     }                                                                         \
2760     goto do_nonint_fast_incop;
2762           case JSOP_INCARG:
2763             FAST_INCREMENT_OP(GET_ARGNO(pc), nargs, argv, rval, +=, MAX);
2764           case JSOP_DECARG:
2765             FAST_INCREMENT_OP(GET_ARGNO(pc), nargs, argv, rval, -=, MIN);
2766           case JSOP_ARGINC:
2767             FAST_INCREMENT_OP(GET_ARGNO(pc), nargs, argv, rtmp, +=, MAX);
2768           case JSOP_ARGDEC:
2769             FAST_INCREMENT_OP(GET_ARGNO(pc), nargs, argv, rtmp, -=, MIN);
2771           case JSOP_INCVAR:
2772             FAST_INCREMENT_OP(GET_VARNO(pc), nvars, vars, rval, +=, MAX);
2773           case JSOP_DECVAR:
2774             FAST_INCREMENT_OP(GET_VARNO(pc), nvars, vars, rval, -=, MIN);
2775           case JSOP_VARINC:
2776             FAST_INCREMENT_OP(GET_VARNO(pc), nvars, vars, rtmp, +=, MAX);
2777           case JSOP_VARDEC:
2778             FAST_INCREMENT_OP(GET_VARNO(pc), nvars, vars, rtmp, -=, MIN);
2780 #undef FAST_INCREMENT_OP
2782           do_nonint_fast_incop:
2783             NONINT_INCREMENT_OP();
2784             *vp = rval;
2785             PUSH_OPND(rtmp);
2786             break;
2788           case JSOP_GETPROP:
2789             /* Get an immediate atom naming the property. */
2790             atom = GET_ATOM(cx, script, pc);
2791             id   = (jsid)atom;
2792             PROPERTY_OP(-1, CACHED_GET(OBJ_GET_PROPERTY(cx, obj, id, &rval)));
2793             STORE_OPND(-1, rval);
2794             break;
2796           case JSOP_SETPROP:
2797             /* Pop the right-hand side into rval for OBJ_SET_PROPERTY. */
2798             rval = FETCH_OPND(-1);
2800             /* Get an immediate atom naming the property. */
2801             atom = GET_ATOM(cx, script, pc);
2802             id   = (jsid)atom;
2803             PROPERTY_OP(-2, CACHED_SET(OBJ_SET_PROPERTY(cx, obj, id, &rval)));
2804             sp--;
2805             STORE_OPND(-1, rval);
2806             break;
2808           case JSOP_GETELEM:
2809             ELEMENT_OP(-1, CACHED_GET(OBJ_GET_PROPERTY(cx, obj, id, &rval)));
2810             sp--;
2811             STORE_OPND(-1, rval);
2812             break;
2814           case JSOP_SETELEM:
2815             rval = FETCH_OPND(-1);
2816             ELEMENT_OP(-2, CACHED_SET(OBJ_SET_PROPERTY(cx, obj, id, &rval)));
2817             sp -= 2;
2818             STORE_OPND(-1, rval);
2819             break;
2821           case JSOP_ENUMELEM:
2822             /* Funky: the value to set is under the [obj, id] pair. */
2823             FETCH_ELEMENT_ID(-1, id);
2824             lval = FETCH_OPND(-2);
2825             VALUE_TO_OBJECT(cx, lval, obj);
2826             rval = FETCH_OPND(-3);
2827             SAVE_SP(fp);
2828             ok = OBJ_SET_PROPERTY(cx, obj, id, &rval);
2829             if (!ok)
2830                 goto out;
2831             sp -= 3;
2832             break;
2834 /*
2835  * LAZY_ARGS_THISP allows the JSOP_ARGSUB bytecode to defer creation of the
2836  * arguments object until it is truly needed.  JSOP_ARGSUB optimizes away
2837  * arguments objects when the only uses of the 'arguments' parameter are to
2838  * fetch individual actual parameters.  But if such a use were then invoked,
2839  * e.g., arguments[i](), the 'this' parameter would and must bind to the
2840  * caller's arguments object.  So JSOP_ARGSUB sets obj to LAZY_ARGS_THISP.
2841  */
2842 #define LAZY_ARGS_THISP ((JSObject *) 1)
2844           case JSOP_PUSHOBJ:
2845             if (obj == LAZY_ARGS_THISP && !(obj = js_GetArgsObject(cx, fp))) {
2846                 ok = JS_FALSE;
2847                 goto out;
2848             }
2849             PUSH_OPND(OBJECT_TO_JSVAL(obj));
2850             break;
2852           case JSOP_CALL:
2853           case JSOP_EVAL:
2854             argc = GET_ARGC(pc);
2855             vp = sp - (argc + 2);
2856             lval = *vp;
2857             SAVE_SP(fp);
2859             if (JSVAL_IS_FUNCTION(cx, lval) &&
2860                 (obj = JSVAL_TO_OBJECT(lval),
2861                  fun = (JSFunction *) JS_GetPrivate(cx, obj),
2862                  !fun->native &&
2863                  !(fun->flags & (JSFUN_HEAVYWEIGHT | JSFUN_BOUND_METHOD)) &&
2864                  argc >= (uintN)(fun->nargs + fun->extra)))
2865           /* inline_call: */
2866             {
2867                 uintN nframeslots, nvars;
2868                 void *newmark;
2869                 JSInlineFrame *newifp;
2870                 JSInterpreterHook hook;
2872                 /* Restrict recursion of lightweight functions. */
2873                 if (inlineCallCount == MAX_INLINE_CALL_COUNT) {
2874                     JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
2875                                          JSMSG_OVER_RECURSED);
2876                     ok = JS_FALSE;
2877                     goto out;
2878                 }
2880 #if JS_HAS_JIT
2881                 /* ZZZbe should do this only if interpreted often enough. */
2882                 ok = jsjit_Compile(cx, fun);
2883                 if (!ok)
2884                     goto out;
2885 #endif
2887                 /* Compute the number of stack slots needed for fun. */
2888                 nframeslots = (sizeof(JSInlineFrame) + sizeof(jsval) - 1)
2889                               / sizeof(jsval);
2890                 nvars = fun->nvars;
2891                 script = fun->script;
2892                 depth = (jsint) script->depth;
2894                 /* Allocate the frame and space for vars and operands. */
2895                 newsp = js_AllocRawStack(cx, nframeslots + nvars + 2 * depth,
2896                                          &newmark);
2897                 if (!newsp) {
2898                     ok = JS_FALSE;
2899                     goto bad_inline_call;
2900                 }
2901                 newifp = (JSInlineFrame *) newsp;
2902                 newsp += nframeslots;
2904                 /* Initialize the stack frame. */
2905                 memset(newifp, 0, sizeof(JSInlineFrame));
2906                 newifp->frame.script = script;
2907                 newifp->frame.fun = fun;
2908                 newifp->frame.argc = argc;
2909                 newifp->frame.argv = vp + 2;
2910                 newifp->frame.rval = JSVAL_VOID;
2911                 newifp->frame.nvars = nvars;
2912                 newifp->frame.vars = newsp;
2913                 newifp->frame.down = fp;
2914                 newifp->frame.scopeChain = OBJ_GET_PARENT(cx, obj);
2915                 newifp->mark = newmark;
2917                 /* Compute the 'this' parameter now that argv is set. */
2918                 ok = ComputeThis(cx, JSVAL_TO_OBJECT(vp[1]), &newifp->frame);
2919                 if (!ok) {
2920                     js_FreeRawStack(cx, newmark);
2921                     goto bad_inline_call;
2922                 }
2924                 /* Push void to initialize local variables. */
2925                 sp = newsp;
2926                 while (nvars--)
2927                     PUSH(JSVAL_VOID);
2928                 sp += depth;
2929                 newifp->frame.spbase = sp;
2930                 SAVE_SP(&newifp->frame);
2932                 /* Call the debugger hook if present. */
2933                 hook = cx->runtime->callHook;
2934                 if (hook) {
2935                     newifp->hookData = hook(cx, &newifp->frame, JS_TRUE, 0,
2936                                             cx->runtime->callHookData);
2937                     LOAD_INTERRUPT_HANDLER(rt);
2938                 }
2940                 /* Switch to new version if currentVersion wasn't overridden. */
2941                 newifp->callerVersion = cx->version;
2942                 if (cx->version == currentVersion) {
2943                     currentVersion = script->version;
2944                     if (currentVersion != cx->version)
2945                         JS_SetVersion(cx, currentVersion);
2946                 }
2948                 /* Push the frame and set interpreter registers. */
2949                 cx->fp = fp = &newifp->frame;
2950                 pc = script->code;
2951                 endpc = pc + script->length;
2952                 inlineCallCount++;
2953                 JS_RUNTIME_METER(rt, inlineCalls);
2954                 continue;
2956               bad_inline_call:
2957                 script = fp->script;
2958                 depth = (jsint) script->depth;
2959                 goto out;
2960             }
2962             ok = js_Invoke(cx, argc, 0);
2963             RESTORE_SP(fp);
2964             LOAD_INTERRUPT_HANDLER(rt);
2965             if (!ok)
2966                 goto out;
2967             JS_RUNTIME_METER(rt, nonInlineCalls);
2968 #if JS_HAS_LVALUE_RETURN
2969             if (cx->rval2set) {
2970                 /*
2971                  * Sneaky: use the stack depth we didn't claim in our budget,
2972                  * but that we know is there on account of [fun, this] already
2973                  * having been pushed, at a minimum (if no args).  Those two
2974                  * slots have been popped and [rval] has been pushed, which
2975                  * leaves one more slot for rval2 before we might overflow.
2976                  *
2977                  * NB: rval2 must be the property identifier, and rval the
2978                  * object from which to get the property.  The pair form an
2979                  * ECMA "reference type", which can be used on the right- or
2980                  * left-hand side of assignment ops.  Only native methods can
2981                  * return reference types.  See JSOP_SETCALL just below for
2982                  * the left-hand-side case.
2983                  */
2984                 PUSH_OPND(cx->rval2);
2985                 cx->rval2set = JS_FALSE;
2986                 ELEMENT_OP(-1, ok = OBJ_GET_PROPERTY(cx, obj, id, &rval));
2987                 sp--;
2988                 STORE_OPND(-1, rval);
2989             }
2990 #endif
2991             obj = NULL;
2992             break;
2994 #if JS_HAS_LVALUE_RETURN
2995           case JSOP_SETCALL:
2996             argc = GET_ARGC(pc);
2997             SAVE_SP(fp);
2998             ok = js_Invoke(cx, argc, 0);
2999             RESTORE_SP(fp);
3000             LOAD_INTERRUPT_HANDLER(rt);
3001             if (!ok)
3002                 goto out;
3003             if (!cx->rval2set) {
3004                 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
3005                                      JSMSG_BAD_LEFTSIDE_OF_ASS);
3006                 ok = JS_FALSE;
3007                 goto out;
3008             }
3009             PUSH_OPND(cx->rval2);
3010             cx->rval2set = JS_FALSE;
3011             obj = NULL;
3012             break;
3013 #endif
3015           case JSOP_NAME:
3016             atom = GET_ATOM(cx, script, pc);
3017             id   = (jsid)atom;
3019             SAVE_SP(fp);
3020             ok = js_FindProperty(cx, id, &obj, &obj2, &prop);
3021             if (!ok)
3022                 goto out;
3023             if (!prop) {
3024                 /* Kludge to allow (typeof foo == "undefined") tests. */
3025                 for (pc2 = pc + len; pc2 < endpc; pc2++) {
3026                     op2 = (JSOp)*pc2;
3027                     if (op2 == JSOP_TYPEOF) {
3028                         PUSH_OPND(JSVAL_VOID);
3029                         goto advance_pc;
3030                     }
3031                     if (op2 != JSOP_GROUP)
3032                         break;
3033                 }
3034                 goto atom_not_defined;
3035             }
3037             /* Take the slow path if prop was not found in a native object. */
3038             if (!OBJ_IS_NATIVE(obj) || !OBJ_IS_NATIVE(obj2)) {
3039                 OBJ_DROP_PROPERTY(cx, obj2, prop);
3040                 ok = OBJ_GET_PROPERTY(cx, obj, id, &rval);
3041                 if (!ok)
3042                     goto out;
3043                 PUSH_OPND(rval);
3044                 break;
3045             }
3047             /* Get and push the obj[id] property's value. */
3048             sprop = (JSScopeProperty *)prop;
3049             slot = (uintN)sprop->slot;
3050             rval = (slot != SPROP_INVALID_SLOT)
3051                    ? LOCKED_OBJ_GET_SLOT(obj2, slot)
3052                    : JSVAL_VOID;
3053             JS_UNLOCK_OBJ(cx, obj2);
3054             ok = SPROP_GET(cx, sprop, obj, obj2, &rval);
3055             JS_LOCK_OBJ(cx, obj2);
3056             if (!ok) {
3057                 OBJ_DROP_PROPERTY(cx, obj2, prop);
3058                 goto out;
3059             }
3060             if (SPROP_HAS_VALID_SLOT(sprop, OBJ_SCOPE(obj2)))
3061                 LOCKED_OBJ_SET_SLOT(obj2, slot, rval);
3062             OBJ_DROP_PROPERTY(cx, obj2, prop);
3063             PUSH_OPND(rval);
3064             break;
3066           case JSOP_UINT16:
3067             i = (jsint) GET_ATOM_INDEX(pc);
3068             rval = INT_TO_JSVAL(i);
3069             PUSH_OPND(rval);
3070             obj = NULL;
3071             break;
3073           case JSOP_NUMBER:
3074           case JSOP_STRING:
3075             atom = GET_ATOM(cx, script, pc);
3076             PUSH_OPND(ATOM_KEY(atom));
3077             obj = NULL;
3078             break;
3080           case JSOP_OBJECT:
3081           {
3082 #if 0
3083             jsatomid atomIndex;
3084             JSAtomMap *atomMap;
3086             /*
3087              * Get a suitable object from an atom mapped by the bytecode at pc.
3088              *
3089              * We must handle the case where a regexp object literal is used in
3090              * a different global at execution time from the global with which
3091              * it was scanned at compile time, in order to rewrap the JSRegExp
3092              * struct with a new object having the right prototype and parent.
3093              *
3094              * Unlike JSOP_DEFFUN and other prolog bytecodes, we don't want to
3095              * pay a script prolog execution price for all regexp literals in a
3096              * script (many may not be used by a particular execution of that
3097              * script, depending on control flow), so we do all fp->objAtomMap
3098              * initialization lazily, here under JSOP_OBJECT.
3099              *
3100              * XXX This code is specific to regular expression objects.  If we
3101              * need JSOP_OBJECT for other kinds of object literals, we should
3102              * push cloning down under JSObjectOps.  Also, fp->objAtomMap is
3103              * used only for object atoms, so it's sparse (wasting some stack
3104              * space) and as its name implies, you can't get non-object atoms
3105              * from it.
3106              */
3107             atomIndex = GET_ATOM_INDEX(pc);
3108             atomMap = fp->objAtomMap;
3109             atom = atomMap ? atomMap->vector[atomIndex] : NULL;
3110             if (!atom) {
3111                 /* Let atom and obj denote the regexp (object) mapped by pc. */
3112                 atom = js_GetAtom(cx, &script->atomMap, atomIndex);
3113                 JS_ASSERT(ATOM_IS_OBJECT(atom));
3114                 obj = ATOM_TO_OBJECT(atom);
3115                 JS_ASSERT(OBJ_GET_CLASS(cx, obj) == &js_RegExpClass);
3117                 /* Compute the current global object in obj2. */
3118                 obj2 = fp->scopeChain;
3119                 while ((parent = OBJ_GET_PARENT(cx, obj2)) != NULL)
3120                     obj2 = parent;
3122                 /*
3123                  * If obj's parent is not obj2, we must clone obj so that it
3124                  * has the right parent, and therefore, the right prototype.
3125                  *
3126                  * Yes, this means we assume that the correct RegExp.prototype
3127                  * to which regexp instances (including literals) delegate can
3128                  * be distinguished solely by the instance's parent, which was
3129                  * set to the parent of the RegExp constructor function object
3130                  * when the instance was created.  In other words,
3131                  *
3132                  *   (/x/.__parent__ == RegExp.__parent__) implies
3133                  *   (/x/.__proto__ == RegExp.prototype)
3134                  *
3135                  * (unless you assign a different object to RegExp.prototype
3136                  * at runtime, in which case, ECMA doesn't specify operation,
3137                  * and you get what you deserve).
3138                  *
3139                  * This same coupling between instance parent and constructor
3140                  * parent turns up elsewhere (see jsobj.c's FindConstructor,
3141                  * js_ConstructObject, and js_NewObject).  It's fundamental.
3142                  */
3143                 if (OBJ_GET_PARENT(cx, obj) != obj2) {
3144                     obj = js_CloneRegExpObject(cx, obj, obj2);
3145                     if (!obj) {
3146                         ok = JS_FALSE;
3147                         goto out;
3148                     }
3150                     atom = js_AtomizeObject(cx, obj, 0);
3151                     if (!atom) {
3152                         ok = JS_FALSE;
3153                         goto out;
3154                     }
3155                 }
3157                 /*
3158                  * If fp->objAtomMap is null, initialize it now so we can map
3159                  * atom (whether atom is newly created for a cloned object, or
3160                  * the original atom mapped by script) for faster performance
3161                  * next time through JSOP_OBJECT.
3162                  */
3163                 if (!atomMap) {
3164                     jsatomid mapLength = script->atomMap.length;
3165                     size_t vectorBytes = mapLength * sizeof(JSAtom *);
3167                     /* Allocate an override atom map from cx->stackPool. */
3168                     JS_ARENA_ALLOCATE_CAST(atomMap, JSAtomMap *,
3169                                            &cx->stackPool,
3170                                            sizeof(JSAtomMap) + vectorBytes);
3171                     if (!atomMap) {
3172                         JS_ReportOutOfMemory(cx);
3173                         ok = JS_FALSE;
3174                         goto out;
3175                     }
3177                     atomMap->length = mapLength;
3178                     atomMap->vector = (JSAtom **)(atomMap + 1);
3179                     memset(atomMap->vector, 0, vectorBytes);
3180                     fp->objAtomMap = atomMap;
3181                 }
3182                 atomMap->vector[atomIndex] = atom;
3183             }
3184 #else
3185             atom = GET_ATOM(cx, script, pc);
3186             JS_ASSERT(ATOM_IS_OBJECT(atom));
3187 #endif
3188             rval = ATOM_KEY(atom);
3189             PUSH_OPND(rval);
3190             obj = NULL;
3191             break;
3192           }
3194           case JSOP_ZERO:
3195             PUSH_OPND(JSVAL_ZERO);
3196             obj = NULL;
3197             break;
3199           case JSOP_ONE:
3200             PUSH_OPND(JSVAL_ONE);
3201             obj = NULL;
3202             break;
3204           case JSOP_NULL:
3205             PUSH_OPND(JSVAL_NULL);
3206             obj = NULL;
3207             break;
3209           case JSOP_THIS:
3210             PUSH_OPND(OBJECT_TO_JSVAL(fp->thisp));
3211             obj = NULL;
3212             break;
3214           case JSOP_FALSE:
3215             PUSH_OPND(JSVAL_FALSE);
3216             obj = NULL;
3217             break;
3219           case JSOP_TRUE:
3220             PUSH_OPND(JSVAL_TRUE);
3221             obj = NULL;
3222             break;
3224 #if JS_HAS_SWITCH_STATEMENT
3225           case JSOP_TABLESWITCH:
3226             pc2 = pc;
3227             len = GET_JUMP_OFFSET(pc2);
3229             /*
3230              * ECMAv2 forbids conversion of discriminant, so we will skip to
3231              * the default case if the discriminant isn't already an int jsval.
3232              * (This opcode is emitted only for dense jsint-domain switches.)
3233              */
3234             if (cx->version == JSVERSION_DEFAULT ||
3235                 cx->version >= JSVERSION_1_4) {
3236                 rval = POP_OPND();
3237                 if (!JSVAL_IS_INT(rval))
3238                     break;
3239                 i = JSVAL_TO_INT(rval);
3240             } else {
3241                 FETCH_INT(cx, -1, i);
3242                 sp--;
3243             }
3245             pc2 += JUMP_OFFSET_LEN;
3246             low = GET_JUMP_OFFSET(pc2);
3247             pc2 += JUMP_OFFSET_LEN;
3248             high = GET_JUMP_OFFSET(pc2);
3250             i -= low;
3251             if ((jsuint)i < (jsuint)(high - low + 1)) {
3252                 pc2 += JUMP_OFFSET_LEN + JUMP_OFFSET_LEN * i;
3253                 off = (jsint) GET_JUMP_OFFSET(pc2);
3254                 if (off)
3255                     len = off;
3256             }
3257             break;
3259           case JSOP_LOOKUPSWITCH:
3260             lval = POP_OPND();
3261             pc2 = pc;
3262             len = GET_JUMP_OFFSET(pc2);
3264             if (!JSVAL_IS_NUMBER(lval) &&
3265                 !JSVAL_IS_STRING(lval) &&
3266                 !JSVAL_IS_BOOLEAN(lval)) {
3267                 goto advance_pc;
3268             }
3270             pc2 += JUMP_OFFSET_LEN;
3271             npairs = (jsint) GET_ATOM_INDEX(pc2);
3272             pc2 += ATOM_INDEX_LEN;
3274 #define SEARCH_PAIRS(MATCH_CODE)                                              \
3275     while (npairs) {                                                          \
3276         atom = GET_ATOM(cx, script, pc2);                                     \
3277         rval = ATOM_KEY(atom);                                                \
3278         MATCH_CODE                                                            \
3279         if (match) {                                                          \
3280             pc2 += ATOM_INDEX_LEN;                                            \
3281             len = GET_JUMP_OFFSET(pc2);                                       \
3282             goto advance_pc;                                                  \
3283         }                                                                     \
3284         pc2 += ATOM_INDEX_LEN + JUMP_OFFSET_LEN;                              \
3285         npairs--;                                                             \
3286     }
3287             if (JSVAL_IS_STRING(lval)) {
3288                 str  = JSVAL_TO_STRING(lval);
3289                 SEARCH_PAIRS(
3290                     match = (JSVAL_IS_STRING(rval) &&
3291                              ((str2 = JSVAL_TO_STRING(rval)) == str ||
3292                               !js_CompareStrings(str2, str)));
3293                 )
3294             } else if (JSVAL_IS_DOUBLE(lval)) {
3295                 d = *JSVAL_TO_DOUBLE(lval);
3296                 SEARCH_PAIRS(
3297                     match = (JSVAL_IS_DOUBLE(rval) &&
3298                              *JSVAL_TO_DOUBLE(rval) == d);
3299                 )
3300             } else {
3301                 SEARCH_PAIRS(
3302                     match = (lval == rval);
3303                 )
3304             }
3305 #undef SEARCH_PAIRS
3306             break;
3308           case JSOP_TABLESWITCHX:
3309             pc2 = pc;
3310             len = GET_JUMPX_OFFSET(pc2);
3312             /*
3313              * ECMAv2 forbids conversion of discriminant, so we will skip to
3314              * the default case if the discriminant isn't already an int jsval.
3315              * (This opcode is emitted only for dense jsint-domain switches.)
3316              */
3317             if (cx->version == JSVERSION_DEFAULT ||
3318                 cx->version >= JSVERSION_1_4) {
3319                 rval = POP_OPND();
3320                 if (!JSVAL_IS_INT(rval))
3321                     break;
3322                 i = JSVAL_TO_INT(rval);
3323             } else {
3324                 FETCH_INT(cx, -1, i);
3325                 sp--;
3326             }
3328             pc2 += JUMPX_OFFSET_LEN;
3329             low = GET_JUMP_OFFSET(pc2);
3330             pc2 += JUMP_OFFSET_LEN;
3331             high = GET_JUMP_OFFSET(pc2);
3333             i -= low;
3334             if ((jsuint)i < (jsuint)(high - low + 1)) {
3335                 pc2 += JUMP_OFFSET_LEN + JUMPX_OFFSET_LEN * i;
3336                 off = (jsint) GET_JUMPX_OFFSET(pc2);
3337                 if (off)
3338                     len = off;
3339             }
3340             break;
3342           case JSOP_LOOKUPSWITCHX:
3343             lval = POP_OPND();
3344             pc2 = pc;
3345             len = GET_JUMPX_OFFSET(pc2);
3347             if (!JSVAL_IS_NUMBER(lval) &&
3348                 !JSVAL_IS_STRING(lval) &&
3349                 !JSVAL_IS_BOOLEAN(lval)) {
3350                 goto advance_pc;
3351             }
3353             pc2 += JUMPX_OFFSET_LEN;
3354             npairs = (jsint) GET_ATOM_INDEX(pc2);
3355             pc2 += ATOM_INDEX_LEN;
3357 #define SEARCH_EXTENDED_PAIRS(MATCH_CODE)                                     \
3358     while (npairs) {                                                          \
3359         atom = GET_ATOM(cx, script, pc2);                                     \
3360         rval = ATOM_KEY(atom);                                                \
3361         MATCH_CODE                                                            \
3362         if (match) {                                                          \
3363             pc2 += ATOM_INDEX_LEN;                                            \
3364             len = GET_JUMPX_OFFSET(pc2);                                      \
3365             goto advance_pc;                                                  \
3366         }                                                                     \
3367         pc2 += ATOM_INDEX_LEN + JUMPX_OFFSET_LEN;                             \
3368         npairs--;                                                             \
3369     }
3370             if (JSVAL_IS_STRING(lval)) {
3371                 str  = JSVAL_TO_STRING(lval);
3372                 SEARCH_EXTENDED_PAIRS(
3373                     match = (JSVAL_IS_STRING(rval) &&
3374                              ((str2 = JSVAL_TO_STRING(rval)) == str ||
3375                               !js_CompareStrings(str2, str)));
3376                 )
3377             } else if (JSVAL_IS_DOUBLE(lval)) {
3378                 d = *JSVAL_TO_DOUBLE(lval);
3379                 SEARCH_EXTENDED_PAIRS(
3380                     match = (JSVAL_IS_DOUBLE(rval) &&
3381                              *JSVAL_TO_DOUBLE(rval) == d);
3382                 )
3383             } else {
3384                 SEARCH_EXTENDED_PAIRS(
3385                     match = (lval == rval);
3386                 )
3387             }
3388 #undef SEARCH_EXTENDED_PAIRS
3389             break;
3391           case JSOP_CONDSWITCH:
3392             break;
3394 #endif /* JS_HAS_SWITCH_STATEMENT */
3396 #if JS_HAS_EXPORT_IMPORT
3397           case JSOP_EXPORTALL:
3398             obj = fp->varobj;
3399             ida = JS_Enumerate(cx, obj);
3400             if (!ida) {
3401                 ok = JS_FALSE;
3402             } else {
3403                 for (i = 0, j = ida->length; i < j; i++) {
3404                     id = ida->vector[i];
3405                     ok = OBJ_LOOKUP_PROPERTY(cx, obj, id, &obj2, &prop);
3406                     if (!ok)
3407                         break;
3408                     if (!prop)
3409                         continue;
3410                     ok = OBJ_GET_ATTRIBUTES(cx, obj, id, prop, &attrs);
3411                     if (ok) {
3412                         attrs |= JSPROP_EXPORTED;
3413                         ok = OBJ_SET_ATTRIBUTES(cx, obj, id, prop, &attrs);
3414                     }
3415                     OBJ_DROP_PROPERTY(cx, obj2, prop);
3416                     if (!ok)
3417                         break;
3418                 }
3419                 JS_DestroyIdArray(cx, ida);
3420             }
3421             break;
3423           case JSOP_EXPORTNAME:
3424             atom = GET_ATOM(cx, script, pc);
3425             id   = (jsid)atom;
3426             obj  = fp->varobj;
3427             ok = OBJ_LOOKUP_PROPERTY(cx, obj, id, &obj2, &prop);
3428             if (!ok)
3429                 goto out;
3430             if (!prop) {
3431                 ok = OBJ_DEFINE_PROPERTY(cx, obj, id, JSVAL_VOID, NULL, NULL,
3432                                          JSPROP_EXPORTED, NULL);
3433             } else {
3434                 ok = OBJ_GET_ATTRIBUTES(cx, obj, id, prop, &attrs);
3435                 if (ok) {
3436                     attrs |= JSPROP_EXPORTED;
3437                     ok = OBJ_SET_ATTRIBUTES(cx, obj, id, prop, &attrs);
3438                 }
3439                 OBJ_DROP_PROPERTY(cx, obj2, prop);
3440             }
3441             if (!ok)
3442                 goto out;
3443             break;
3445           case JSOP_IMPORTALL:
3446             id = (jsid)JSVAL_VOID;
3447             PROPERTY_OP(-1, ok = ImportProperty(cx, obj, id));
3448             sp--;
3449             break;
3451           case JSOP_IMPORTPROP:
3452             /* Get an immediate atom naming the property. */
3453             atom = GET_ATOM(cx, script, pc);
3454             id   = (jsid)atom;
3455             PROPERTY_OP(-1, ok = ImportProperty(cx, obj, id));
3456             sp--;
3457             break;
3459           case JSOP_IMPORTELEM:
3460             ELEMENT_OP(-1, ok = ImportProperty(cx, obj, id));
3461             sp -= 2;
3462             break;
3463 #endif /* JS_HAS_EXPORT_IMPORT */
3465           case JSOP_TRAP:
3466             switch (JS_HandleTrap(cx, script, pc, &rval)) {
3467               case JSTRAP_ERROR:
3468                 ok = JS_FALSE;
3469                 goto out;
3470               case JSTRAP_CONTINUE:
3471                 JS_ASSERT(JSVAL_IS_INT(rval));
3472                 op = (JSOp) JSVAL_TO_INT(rval);
3473                 JS_ASSERT((uintN)op < (uintN)JSOP_LIMIT);
3474                 LOAD_INTERRUPT_HANDLER(rt);
3475                 goto do_op;
3476               case JSTRAP_RETURN:
3477                 fp->rval = rval;
3478                 goto out;
3479 #if JS_HAS_EXCEPTIONS
3480               case JSTRAP_THROW:
3481                 cx->throwing = JS_TRUE;
3482                 cx->exception = rval;
3483                 ok = JS_FALSE;
3484                 goto out;
3485 #endif /* JS_HAS_EXCEPTIONS */
3486               default:;
3487             }
3488             LOAD_INTERRUPT_HANDLER(rt);
3489             break;
3491           case JSOP_ARGUMENTS:
3492             SAVE_SP(fp);
3493             ok = js_GetArgsValue(cx, fp, &rval);
3494             if (!ok)
3495                 goto out;
3496             PUSH_OPND(rval);
3497             break;
3499           case JSOP_ARGSUB:
3500             id = (jsid) INT_TO_JSVAL(GET_ARGNO(pc));
3501             SAVE_SP(fp);
3502             ok = js_GetArgsProperty(cx, fp, id, &obj, &rval);
3503             if (!ok)
3504                 goto out;
3505             if (!obj) {
3506                 /*
3507                  * If arguments was not overridden by eval('arguments = ...'),
3508                  * set obj to the magic cookie respected by JSOP_PUSHOBJ, just
3509                  * in case this bytecode is part of an 'arguments[i](j, k)' or
3510                  * similar such invocation sequence, where the function that
3511                  * is invoked expects its 'this' parameter to be the caller's
3512                  * arguments object.
3513                  */
3514                 obj = LAZY_ARGS_THISP;
3515             }
3516             PUSH_OPND(rval);
3517             break;
3519 #undef LAZY_ARGS_THISP
3521           case JSOP_ARGCNT:
3522             id = (jsid) rt->atomState.lengthAtom;
3523             SAVE_SP(fp);
3524             ok = js_GetArgsProperty(cx, fp, id, &obj, &rval);
3525             if (!ok)
3526                 goto out;
3527             PUSH_OPND(rval);
3528             break;
3530           case JSOP_GETARG:
3531             slot = GET_ARGNO(pc);
3532             JS_ASSERT(slot < fp->fun->nargs);
3533             PUSH_OPND(fp->argv[slot]);
3534             obj = NULL;
3535             break;
3537           case JSOP_SETARG:
3538             slot = GET_ARGNO(pc);
3539             JS_ASSERT(slot < fp->fun->nargs);
3540             vp = &fp->argv[slot];
3541             GC_POKE(cx, *vp);
3542             *vp = FETCH_OPND(-1);
3543             obj = NULL;
3544             break;
3546           case JSOP_GETVAR:
3547             slot = GET_VARNO(pc);
3548             JS_ASSERT(slot < fp->fun->nvars);
3549             PUSH_OPND(fp->vars[slot]);
3550             obj = NULL;
3551             break;
3553           case JSOP_SETVAR:
3554             slot = GET_VARNO(pc);
3555             JS_ASSERT(slot < fp->fun->nvars);
3556             vp = &fp->vars[slot];
3557             GC_POKE(cx, *vp);
3558             *vp = FETCH_OPND(-1);
3559             obj = NULL;
3560             break;
3562           case JSOP_DEFCONST:
3563           case JSOP_DEFVAR:
3564           {
3565             JSBool defined;
3567             atom = GET_ATOM(cx, script, pc);
3568             obj = fp->varobj;
3569             attrs = JSPROP_ENUMERATE;
3570             if (!(fp->flags & JSFRAME_EVAL))
3571                 attrs |= JSPROP_PERMANENT;
3572             if (op == JSOP_DEFCONST)
3573                 attrs |= JSPROP_READONLY;
3575             /* Lookup id in order to check for redeclaration problems. */
3576             id = (jsid)atom;
3577             ok = js_CheckRedeclaration(cx, obj, id, attrs, &defined);
3578             if (!ok)
3579                 goto out;
3581             /* Bind a variable only if it's not yet defined. */
3582             if (!defined) {
3583                 ok = OBJ_DEFINE_PROPERTY(cx, obj, id, JSVAL_VOID, NULL, NULL,
3584                                          attrs, NULL);
3585                 if (!ok)
3586                     goto out;
3587             }
3588             break;
3589           }
3591           case JSOP_DEFFUN:
3592           {
3593             uintN flags;
3595             atom = GET_ATOM(cx, script, pc);
3596             obj = ATOM_TO_OBJECT(atom);
3597             fun = (JSFunction *) JS_GetPrivate(cx, obj);
3598             id = (jsid) fun->atom;
3600             /*
3601              * We must be at top-level (either outermost block that forms a
3602              * function's body, or a global) scope, not inside an expression
3603              * (JSOP_{ANON,NAMED}FUNOBJ) or compound statement (JSOP_CLOSURE)
3604              * in the same compilation unit (ECMA Program).
3605              *
3606              * However, we could be in a Program being eval'd from inside a
3607              * with statement, so we need to distinguish variables object from
3608              * scope chain head.  Hence the two assignments to parent below.
3609              * First we make sure the function object we're defining has the
3610              * right scope chain.  Then we define its name in fp->varobj.
3611              *
3612              * If static link is not current scope, clone fun's object to link
3613              * to the current scope via parent.  This clause exists to enable
3614              * sharing of compiled functions among multiple equivalent scopes,
3615              * splitting the cost of compilation evenly among the scopes and
3616              * amortizing it over a number of executions.  Examples include XUL
3617              * scripts and event handlers shared among Mozilla chrome windows,
3618              * and server-side JS user-defined functions shared among requests.
3619              *
3620              * NB: The Script object exposes compile and exec in the language,
3621              * such that this clause introduces an incompatible change from old
3622              * JS versions that supported Script.  Such a JS version supported
3623              * executing a script that defined and called functions scoped by
3624              * the compile-time static link, not by the exec-time scope chain.
3625              *
3626              * We sacrifice compatibility, breaking such scripts, in order to
3627              * promote compile-cost sharing and amortizing, and because Script
3628              * is not and will not be standardized.
3629              */
3630             parent = fp->scopeChain;
3631             if (OBJ_GET_PARENT(cx, obj) != parent) {
3632                 obj = js_CloneFunctionObject(cx, obj, parent);
3633                 if (!obj) {
3634                     ok = JS_FALSE;
3635                     goto out;
3636                 }
3637             }
3639             /*
3640              * ECMA requires functions defined when entering Global code to be
3641              * permanent, and functions defined when entering Eval code to be
3642              * impermanent.
3643              */
3644             attrs = JSPROP_ENUMERATE;
3645             if (!(fp->flags & JSFRAME_EVAL))
3646                 attrs |= JSPROP_PERMANENT;
3648             /*
3649              * Load function flags that are also property attributes.  Getters
3650              * and setters do not need a slot, their value is stored elsewhere
3651              * in the property itself, not in obj->slots.
3652              */
3653             flags = fun->flags & (JSFUN_GETTER | JSFUN_SETTER);
3654             if (flags)
3655                 attrs |= flags | JSPROP_SHARED;
3657             /*
3658              * Check for a const property of the same name -- or any kind
3659              * of property if executing with the strict option.  We check
3660              * here at runtime as well as at compile-time, to handle eval
3661              * as well as multiple HTML script tags.
3662              */
3663             parent = fp->varobj;
3664             ok = js_CheckRedeclaration(cx, parent, id, attrs, &cond);
3665             if (!ok)
3666                 goto out;
3668             ok = OBJ_DEFINE_PROPERTY(cx, parent, id,
3669                                      flags ? JSVAL_VOID : OBJECT_TO_JSVAL(obj),
3670                                      (flags & JSFUN_GETTER)
3671                                      ? (JSPropertyOp) obj
3672                                      : NULL,
3673                                      (flags & JSFUN_SETTER)
3674                                      ? (JSPropertyOp) obj
3675                                      : NULL,
3676                                      attrs,
3677                                      NULL);
3678             if (!ok)
3679                 goto out;
3680             break;
3681           }
3683 #if JS_HAS_LEXICAL_CLOSURE
3684           case JSOP_DEFLOCALFUN:
3685             /*
3686              * Define a local function (i.e., one nested at the top level of
3687              * another function), parented by the current scope chain, and
3688              * stored in a local variable slot that the compiler allocated.
3689              * This is an optimization over JSOP_DEFFUN that avoids requiring
3690              * a call object for the outer function's activation.
3691              */
3692             pc2 = pc;
3693             slot = GET_VARNO(pc2);
3694             pc2 += VARNO_LEN;
3695             atom = GET_ATOM(cx, script, pc2);
3696             obj = ATOM_TO_OBJECT(atom);
3697             fun = (JSFunction *) JS_GetPrivate(cx, obj);
3699             parent = fp->scopeChain;
3700             if (OBJ_GET_PARENT(cx, obj) != parent) {
3701                 obj = js_CloneFunctionObject(cx, obj, parent);
3702                 if (!obj) {
3703                     ok = JS_FALSE;
3704                     goto out;
3705                 }
3706             }
3707             fp->vars[slot] = OBJECT_TO_JSVAL(obj);
3708             break;
3710           case JSOP_ANONFUNOBJ:
3711             /* Push the specified function object literal. */
3712             atom = GET_ATOM(cx, script, pc);
3713             obj = ATOM_TO_OBJECT(atom);
3715             /* If re-parenting, push a clone of the function object. */
3716             parent = fp->scopeChain;
3717             if (OBJ_GET_PARENT(cx, obj) != parent) {
3718                 obj = js_CloneFunctionObject(cx, obj, parent);
3719                 if (!obj) {
3720                     ok = JS_FALSE;
3721                     goto out;
3722                 }
3723             }
3724             PUSH_OPND(OBJECT_TO_JSVAL(obj));
3725             break;
3727           case JSOP_NAMEDFUNOBJ:
3728             /* ECMA ed. 3 FunctionExpression: function Identifier [etc.]. */
3729             atom = GET_ATOM(cx, script, pc);
3730             rval = ATOM_KEY(atom);
3731             JS_ASSERT(JSVAL_IS_FUNCTION(cx, rval));
3733             /*
3734              * 1. Create a new object as if by the expression new Object().
3735              * 2. Add Result(1) to the front of the scope chain.
3736              *
3737              * Step 2 is achieved by making the new object's parent be the
3738              * current scope chain, and then making the new object the parent
3739              * of the Function object clone.
3740              */
3741             SAVE_SP(fp);
3742             parent = js_ConstructObject(cx, &js_ObjectClass, NULL,
3743                                         fp->scopeChain, 0, NULL);
3744             if (!parent) {
3745                 ok = JS_FALSE;
3746                 goto out;
3747             }
3749             /*
3750              * 3. Create a new Function object as specified in section 13.2
3751              * with [parameters and body specified by the function expression
3752              * that was parsed by the compiler into a Function object, and
3753              * saved in the script's atom map].
3754              */
3755             obj = js_CloneFunctionObject(cx, JSVAL_TO_OBJECT(rval), parent);
3756             if (!obj) {
3757                 ok = JS_FALSE;
3758                 goto out;
3759             }
3761             /*
3762              * 4. Create a property in the object Result(1).  The property's
3763              * name is [fun->atom, the identifier parsed by the compiler],
3764              * value is Result(3), and attributes are { DontDelete, ReadOnly }.
3765              */
3766             fun = (JSFunction *) JS_GetPrivate(cx, obj);
3767             attrs = fun->flags & (JSFUN_GETTER | JSFUN_SETTER);
3768             if (attrs)
3769                 attrs |= JSPROP_SHARED;
3770             ok = OBJ_DEFINE_PROPERTY(cx, parent, (jsid)fun->atom,
3771                                      attrs ? JSVAL_VOID : OBJECT_TO_JSVAL(obj),
3772                                      (attrs & JSFUN_GETTER)
3773                                      ? (JSPropertyOp) obj
3774                                      : NULL,
3775                                      (attrs & JSFUN_SETTER)
3776                                      ? (JSPropertyOp) obj
3777                                      : NULL,
3778                                      attrs |
3779                                      JSPROP_ENUMERATE | JSPROP_PERMANENT |
3780                                      JSPROP_READONLY,
3781                                      NULL);
3782             if (!ok) {
3783                 cx->newborn[GCX_OBJECT] = NULL;
3784                 goto out;
3785             }
3787             /*
3788              * 5. Remove Result(1) from the front of the scope chain [no-op].
3789              * 6. Return Result(3).
3790              */
3791             PUSH_OPND(OBJECT_TO_JSVAL(obj));
3792             break;
3794           case JSOP_CLOSURE:
3795             /*
3796              * ECMA ed. 3 extension: a named function expression in a compound
3797              * statement (not at the top statement level of global code, or at
3798              * the top level of a function body).
3799              *
3800              * Get immediate operand atom, which is a function object literal.
3801              * From it, get the function to close.
3802              */
3803             atom = GET_ATOM(cx, script, pc);
3804             JS_ASSERT(JSVAL_IS_FUNCTION(cx, ATOM_KEY(atom)));
3805             obj = ATOM_TO_OBJECT(atom);
3807             /*
3808              * Clone the function object with the current scope chain as the
3809              * clone's parent.  The original function object is the prototype
3810              * of the clone.  Do this only if re-parenting; the compiler may
3811              * have seen the right parent already and created a sufficiently
3812              * well-scoped function object.
3813              */
3814             parent = fp->scopeChain;
3815             if (OBJ_GET_PARENT(cx, obj) != parent) {
3816                 obj = js_CloneFunctionObject(cx, obj, parent);
3817                 if (!obj) {
3818                     ok = JS_FALSE;
3819                     goto out;
3820                 }
3821             }
3823             /*
3824              * Make a property in fp->varobj with id fun->atom and value obj,
3825              * unless fun is a getter or setter (in which case, obj is cast to
3826              * a JSPropertyOp and passed accordingly).
3827              */
3828             fun = (JSFunction *) JS_GetPrivate(cx, obj);
3829             attrs = fun->flags & (JSFUN_GETTER | JSFUN_SETTER);
3830             if (attrs)
3831                 attrs |= JSPROP_SHARED;
3832             ok = OBJ_DEFINE_PROPERTY(cx, fp->varobj, (jsid)fun->atom,
3833                                      attrs ? JSVAL_VOID : OBJECT_TO_JSVAL(obj),
3834                                      (attrs & JSFUN_GETTER)
3835                                      ? (JSPropertyOp) obj
3836                                      : NULL,
3837                                      (attrs & JSFUN_SETTER)
3838                                      ? (JSPropertyOp) obj
3839                                      : NULL,
3840                                      attrs | JSPROP_ENUMERATE,
3841                                      NULL);
3842             if (!ok) {
3843                 cx->newborn[GCX_OBJECT] = NULL;
3844                 goto out;
3845             }
3846             break;
3847 #endif /* JS_HAS_LEXICAL_CLOSURE */
3849 #if JS_HAS_GETTER_SETTER
3850           case JSOP_GETTER:
3851           case JSOP_SETTER:
3852             JS_ASSERT(len == 1);
3853             op2 = (JSOp) *++pc;
3854             cs = &js_CodeSpec[op2];
3855             len = cs->length;
3856             switch (op2) {
3857               case JSOP_SETNAME:
3858               case JSOP_SETPROP:
3859                 atom = GET_ATOM(cx, script, pc);
3860                 id   = (jsid)atom;
3861                 i = -1;
3862                 rval = FETCH_OPND(i);
3863                 goto gs_pop_lval;
3865               case JSOP_SETELEM:
3866                 rval = FETCH_OPND(-1);
3867                 i = -2;
3868                 FETCH_ELEMENT_ID(i, id);
3869               gs_pop_lval:
3870                 lval = FETCH_OPND(i-1);
3871                 VALUE_TO_OBJECT(cx, lval, obj);
3872                 break;
3874 #if JS_HAS_INITIALIZERS
3875               case JSOP_INITPROP:
3876                 JS_ASSERT(sp - fp->spbase >= 2);
3877                 i = -1;
3878                 rval = FETCH_OPND(i);
3879                 atom = GET_ATOM(cx, script, pc);
3880                 id   = (jsid)atom;
3881                 goto gs_get_lval;
3883               case JSOP_INITELEM:
3884                 JS_ASSERT(sp - fp->spbase >= 3);
3885                 rval = FETCH_OPND(-1);
3886                 i = -2;
3887                 FETCH_ELEMENT_ID(i, id);
3888               gs_get_lval:
3889                 lval = FETCH_OPND(i-1);
3890                 JS_ASSERT(JSVAL_IS_OBJECT(lval));
3891                 obj = JSVAL_TO_OBJECT(lval);
3892                 break;
3893 #endif /* JS_HAS_INITIALIZERS */
3895               default:
3896                 JS_ASSERT(0);
3897             }
3899             if (JS_TypeOfValue(cx, rval) != JSTYPE_FUNCTION) {
3900                 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
3901                                      JSMSG_BAD_GETTER_OR_SETTER,
3902                                      (op == JSOP_GETTER)
3903                                      ? js_getter_str
3904                                      : js_setter_str);
3905                 ok = JS_FALSE;
3906                 goto out;
3907             }
3909             /*
3910              * Getters and setters are just like watchpoints from an access
3911              * control point of view.
3912              */
3913             ok = OBJ_CHECK_ACCESS(cx, obj, id, JSACC_WATCH, &rtmp, &attrs);
3914             if (!ok)
3915                 goto out;
3917             if (op == JSOP_GETTER) {
3918                 getter = (JSPropertyOp) JSVAL_TO_OBJECT(rval);
3919                 setter = NULL;
3920                 attrs = JSPROP_GETTER;
3921             } else {
3922                 getter = NULL;
3923                 setter = (JSPropertyOp) JSVAL_TO_OBJECT(rval);
3924                 attrs = JSPROP_SETTER;
3925             }
3926             attrs |= JSPROP_ENUMERATE | JSPROP_SHARED;
3928             /* Check for a readonly or permanent property of the same name. */
3929             ok = js_CheckRedeclaration(cx, obj, id, attrs, &cond);
3930             if (!ok)
3931                 goto out;
3933             ok = OBJ_DEFINE_PROPERTY(cx, obj, id, JSVAL_VOID, getter, setter,
3934                                      attrs, NULL);
3935             if (!ok)
3936                 goto out;
3938             sp += i;
3939             if (cs->ndefs)
3940                 STORE_OPND(-1, rval);
3941             break;
3942 #endif /* JS_HAS_GETTER_SETTER */
3944 #if JS_HAS_INITIALIZERS
3945           case JSOP_NEWINIT:
3946             argc = 0;
3947             fp->sharpDepth++;
3948             goto do_new;
3950           case JSOP_ENDINIT:
3951             if (--fp->sharpDepth == 0)
3952                 fp->sharpArray = NULL;
3954             /* Re-set the newborn root to the top of this object tree. */
3955             JS_ASSERT(sp - fp->spbase >= 1);
3956             lval = FETCH_OPND(-1);
3957             JS_ASSERT(JSVAL_IS_OBJECT(lval));
3958             cx->newborn[GCX_OBJECT] = JSVAL_TO_GCTHING(lval);
3959             break;
3961           case JSOP_INITPROP:
3962             /* Pop the property's value into rval. */
3963             JS_ASSERT(sp - fp->spbase >= 2);
3964             rval = FETCH_OPND(-1);
3966             /* Get the immediate property name into id. */
3967             atom = GET_ATOM(cx, script, pc);
3968             id   = (jsid)atom;
3969             i = -1;
3970             goto do_init;
3972           case JSOP_INITELEM:
3973             /* Pop the element's value into rval. */
3974             JS_ASSERT(sp - fp->spbase >= 3);
3975             rval = FETCH_OPND(-1);
3977             /* Pop and conditionally atomize the element id. */
3978             FETCH_ELEMENT_ID(-2, id);
3979             i = -2;
3981           do_init:
3982             /* Find the object being initialized at top of stack. */
3983             lval = FETCH_OPND(i-1);
3984             JS_ASSERT(JSVAL_IS_OBJECT(lval));
3985             obj = JSVAL_TO_OBJECT(lval);
3987             /* Set the property named by obj[id] to rval. */
3988             ok = OBJ_SET_PROPERTY(cx, obj, id, &rval);
3989             if (!ok)
3990                 goto out;
3991             sp += i;
3992             break;
3994 #if JS_HAS_SHARP_VARS
3995           case JSOP_DEFSHARP:
3996             obj = fp->sharpArray;
3997             if (!obj) {
3998                 obj = js_NewArrayObject(cx, 0, NULL);
3999                 if (!obj) {
4000                     ok = JS_FALSE;
4001                     goto out;
4002                 }
4003                 fp->sharpArray = obj;
4004             }
4005             i = (jsint) GET_ATOM_INDEX(pc);
4006             id = (jsid) INT_TO_JSVAL(i);
4007             rval = FETCH_OPND(-1);
4008             if (JSVAL_IS_PRIMITIVE(rval)) {
4009                 char numBuf[12];
4010                 JS_snprintf(numBuf, sizeof numBuf, "%u", (unsigned) i);
4011                 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
4012                                      JSMSG_BAD_SHARP_DEF, numBuf);
4013                 ok = JS_FALSE;
4014                 goto out;
4015             }
4016             ok = OBJ_SET_PROPERTY(cx, obj, id, &rval);
4017             if (!ok)
4018                 goto out;
4019             break;
4021           case JSOP_USESHARP:
4022             i = (jsint) GET_ATOM_INDEX(pc);
4023             id = (jsid) INT_TO_JSVAL(i);
4024             obj = fp->sharpArray;
4025             if (!obj) {
4026                 rval = JSVAL_VOID;
4027             } else {
4028                 ok = OBJ_GET_PROPERTY(cx, obj, id, &rval);
4029                 if (!ok)
4030                     goto out;
4031             }
4032             if (!JSVAL_IS_OBJECT(rval)) {
4033                 char numBuf[12];
4034                 JS_snprintf(numBuf, sizeof numBuf, "%u", (unsigned) i);
4035                 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
4036                                      JSMSG_BAD_SHARP_USE, numBuf);
4037                 ok = JS_FALSE;
4038                 goto out;
4039             }
4040             PUSH_OPND(rval);
4041             break;
4042 #endif /* JS_HAS_SHARP_VARS */
4043 #endif /* JS_HAS_INITIALIZERS */
4045 #if JS_HAS_EXCEPTIONS
4046           /* No-ops for ease of decompilation and jit'ing. */
4047           case JSOP_TRY:
4048           case JSOP_FINALLY:
4049             break;
4051           /* Reset the stack to the given depth. */
4052           case JSOP_SETSP:
4053             i = (jsint) GET_ATOM_INDEX(pc);
4054             JS_ASSERT(i >= 0);
4055             sp = fp->spbase + i;
4056             break;
4058           case JSOP_GOSUB:
4059             i = PTRDIFF(pc, script->main, jsbytecode) + len;
4060             len = GET_JUMP_OFFSET(pc);
4061             PUSH(INT_TO_JSVAL(i));
4062             break;
4064           case JSOP_GOSUBX:
4065             i = PTRDIFF(pc, script->main, jsbytecode) + len;
4066             len = GET_JUMPX_OFFSET(pc);
4067             PUSH(INT_TO_JSVAL(i));
4068             break;
4070           case JSOP_RETSUB:
4071             rval = POP();
4072             JS_ASSERT(JSVAL_IS_INT(rval));
4073             i = JSVAL_TO_INT(rval);
4074             pc = script->main + i;
4075             len = 0;
4076             break;
4078           case JSOP_EXCEPTION:
4079             PUSH(cx->exception);
4080             break;
4082           case JSOP_THROW:
4083             cx->throwing = JS_TRUE;
4084             cx->exception = POP_OPND();
4085             ok = JS_FALSE;
4086             /* let the code at out try to catch the exception. */
4087             goto out;
4089           case JSOP_INITCATCHVAR:
4090             /* Pop the property's value into rval. */
4091             JS_ASSERT(sp - fp->spbase >= 2);
4092             rval = POP_OPND();
4094             /* Get the immediate catch variable name into id. */
4095             atom = GET_ATOM(cx, script, pc);
4096             id   = (jsid)atom;
4098             /* Find the object being initialized at top of stack. */
4099             lval = FETCH_OPND(-1);
4100             JS_ASSERT(JSVAL_IS_OBJECT(lval));
4101             obj = JSVAL_TO_OBJECT(lval);
4103             /* Define obj[id] to contain rval and to be permanent. */
4104             ok = OBJ_DEFINE_PROPERTY(cx, obj, id, rval, NULL, NULL,
4105                                      JSPROP_PERMANENT, NULL);
4106             if (!ok)
4107                 goto out;
4108             break;
4109 #endif /* JS_HAS_EXCEPTIONS */
4111 #if JS_HAS_INSTANCEOF
4112           case JSOP_INSTANCEOF:
4113             rval = FETCH_OPND(-1);
4114             if (JSVAL_IS_PRIMITIVE(rval)) {
4115                 SAVE_SP(fp);
4116                 str = js_DecompileValueGenerator(cx, -1, rval, NULL);
4117                 if (str) {
4118                     JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
4119                                          JSMSG_BAD_INSTANCEOF_RHS,
4120                                          JS_GetStringBytes(str));
4121                 }
4122                 ok = JS_FALSE;
4123                 goto out;
4124             }
4125             obj = JSVAL_TO_OBJECT(rval);
4126             lval = FETCH_OPND(-2);
4127             cond = JS_FALSE;
4128             if (obj->map->ops->hasInstance) {
4129                 SAVE_SP(fp);
4130                 ok = obj->map->ops->hasInstance(cx, obj, lval, &cond);
4131                 if (!ok)
4132                     goto out;
4133             }
4134             sp--;
4135             STORE_OPND(-1, BOOLEAN_TO_JSVAL(cond));
4136             break;
4137 #endif /* JS_HAS_INSTANCEOF */
4139 #if JS_HAS_DEBUGGER_KEYWORD
4140           case JSOP_DEBUGGER:
4141           {
4142             JSTrapHandler handler = rt->debuggerHandler;
4143             if (handler) {
4144                 SAVE_SP(fp);
4145                 switch (handler(cx, script, pc, &rval,
4146                                 rt->debuggerHandlerData)) {
4147                   case JSTRAP_ERROR:
4148                     ok = JS_FALSE;
4149                     goto out;
4150                   case JSTRAP_CONTINUE:
4151                     break;
4152                   case JSTRAP_RETURN:
4153                     fp->rval = rval;
4154                     goto out;
4155 #if JS_HAS_EXCEPTIONS
4156                   case JSTRAP_THROW:
4157                     cx->throwing = JS_TRUE;
4158                     cx->exception = rval;
4159                     ok = JS_FALSE;
4160                     goto out;
4161 #endif /* JS_HAS_EXCEPTIONS */
4162                   default:;
4163                 }
4164                 LOAD_INTERRUPT_HANDLER(rt);
4165             }
4166             break;
4167           }
4168 #endif /* JS_HAS_DEBUGGER_KEYWORD */
4170           default: {
4171             char numBuf[12];
4172             JS_snprintf(numBuf, sizeof numBuf, "%d", op);
4173             JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
4174                                  JSMSG_BAD_BYTECODE, numBuf);
4175             ok = JS_FALSE;
4176             goto out;
4177           }
4178         }
4180     advance_pc:
4181         pc += len;
4183 #ifdef DEBUG
4184         if (tracefp) {
4185             intN ndefs, n;
4186             jsval *siter;
4188             ndefs = cs->ndefs;
4189             if (ndefs) {
4190                 SAVE_SP(fp);
4191                 for (n = -ndefs; n < 0; n++) {
4192                     str = js_DecompileValueGenerator(cx, n, sp[n], NULL);
4193                     if (str) {
4194                         fprintf(tracefp, "%s %s",
4195                                 (n == -ndefs) ? "  output:" : ",",
4196                                 JS_GetStringBytes(str));
4197                     }
4198                 }
4199                 fprintf(tracefp, " @ %d\n", sp - fp->spbase);
4200             }
4201             fprintf(tracefp, "  stack: ");
4202             for (siter = fp->spbase; siter < sp; siter++) {
4203                 str = js_ValueToSource(cx, *siter);
4204                 fprintf(tracefp, "%s ",
4205                         str ? JS_GetStringBytes(str) : "<null>");
4206             }
4207             fputc('\n', tracefp);
4208         }
4209 #endif
4210     }
4211 out:
4213 #if JS_HAS_EXCEPTIONS
4214     /*
4215      * Has an exception been raised?
4216      */
4217     if (!ok && cx->throwing) {
4218         /*
4219          * Call debugger throw hook if set (XXX thread safety?).
4220          */
4221         JSTrapHandler handler = rt->throwHook;
4222         if (handler) {
4223             SAVE_SP(fp);
4224             switch (handler(cx, script, pc, &rval, rt->throwHookData)) {
4225               case JSTRAP_ERROR:
4226                 cx->throwing = JS_FALSE;
4227                 goto no_catch;
4228               case JSTRAP_RETURN:
4229                 ok = JS_TRUE;
4230                 cx->throwing = JS_FALSE;
4231                 fp->rval = rval;
4232                 goto no_catch;
4233               case JSTRAP_THROW:
4234                 cx->exception = rval;
4235               case JSTRAP_CONTINUE:
4236               default:;
4237             }
4238             LOAD_INTERRUPT_HANDLER(rt);
4239         }
4241         /*
4242          * Look for a try block within this frame that can catch the exception.
4243          */
4244         SCRIPT_FIND_CATCH_START(script, pc, pc);
4245         if (pc) {
4246             len = 0;
4247             cx->throwing = JS_FALSE;    /* caught */
4248             ok = JS_TRUE;
4249             goto advance_pc;
4250         }
4251     }
4252 no_catch:
4253 #endif
4255     /*
4256      * Check whether control fell off the end of a lightweight function, or an
4257      * exception thrown under such a function was not caught by it.  If so, go
4258      * to the inline code under JSOP_RETURN.
4259      */
4260     if (inlineCallCount)
4261         goto inline_return;
4263     /*
4264      * Reset sp before freeing stack slots, because our caller may GC soon.
4265      * Clear spbase to indicate that we've popped the 2 * depth operand slots.
4266      * Restore the previous frame's execution state.
4267      */
4268     fp->sp = fp->spbase;
4269     fp->spbase = NULL;
4270     js_FreeRawStack(cx, mark);
4271     if (cx->version == currentVersion && currentVersion != originalVersion)
4272         JS_SetVersion(cx, originalVersion);
4273     cx->interpLevel--;
4274     return ok;
4276 atom_not_defined:
4277     {
4278         const char *printable = js_AtomToPrintableString(cx, atom);
4279         if (printable)
4280             js_ReportIsNotDefined(cx, printable);
4281         ok = JS_FALSE;
4282         goto out;
4283     }