Debian Codegraph @

rhino/src/org/mozilla/javascript/Interpreter.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript;
8
9 import java.io.PrintStream;
10 import java.io.Serializable;
11 import java.util.List;
12 import java.util.ArrayList;
13
14 import org.mozilla.javascript.ast.FunctionNode;
15 import org.mozilla.javascript.ast.ScriptNode;
16 import org.mozilla.javascript.ScriptRuntime.NoSuchMethodShim;
17 import org.mozilla.javascript.debug.DebugFrame;
18
19 import static org.mozilla.javascript.UniqueTag.DOUBLE_MARK;
20
21 public final class Interpreter extends Icode implements Evaluator
22 {
23 // data for parsing
24 InterpreterData itsData;
25
26 static final int EXCEPTION_TRY_START_SLOT = 0;
27 static final int EXCEPTION_TRY_END_SLOT = 1;
28 static final int EXCEPTION_HANDLER_SLOT = 2;
29 static final int EXCEPTION_TYPE_SLOT = 3;
30 static final int EXCEPTION_LOCAL_SLOT = 4;
31 static final int EXCEPTION_SCOPE_SLOT = 5;
32 // SLOT_SIZE: space for try start/end, handler, start, handler type,
33 // exception local and scope local
34 static final int EXCEPTION_SLOT_SIZE = 6;
35
36 /**
37 * Class to hold data corresponding to one interpreted call stack frame.
38 */
39 private static class CallFrame implements Cloneable, Serializable
40 {
41 static final long serialVersionUID = -2843792508994958978L;
42
43 CallFrame parentFrame;
44 // amount of stack frames before this one on the interpretation stack
45 int frameIndex;
46 // If true indicates read-only frame that is a part of continuation
47 boolean frozen;
48
49 InterpretedFunction fnOrScript;
50 InterpreterData idata;
51
52 // Stack structure
53 // stack[0 <= i < localShift]: arguments and local variables
54 // stack[localShift <= i <= emptyStackTop]: used for local temporaries
55 // stack[emptyStackTop < i < stack.length]: stack data
56 // sDbl[i]: if stack[i] is UniqueTag.DOUBLE_MARK, sDbl[i] holds the number value
57
58 Object[] stack;
59 int[] stackAttributes;
60 double[] sDbl;
61 CallFrame varSource; // defaults to this unless continuation frame
62 int localShift;
63 int emptyStackTop;
64
65 DebugFrame debuggerFrame;
66 boolean useActivation;
67 boolean isContinuationsTopFrame;
68
69 Scriptable thisObj;
70
71 // The values that change during interpretation
72
73 Object result;
74 double resultDbl;
75 int pc;
76 int pcPrevBranch;
77 int pcSourceLineStart;
78 Scriptable scope;
79
80 int savedStackTop;
81 int savedCallOp;
82 Object throwable;
83
84 CallFrame cloneFrozen()
85 {
86 if (!frozen) Kit.codeBug();
87
88 CallFrame copy;
89 try {
90 copy = (CallFrame)clone();
91 } catch (CloneNotSupportedException ex) {
92 throw new IllegalStateException();
93 }
94
95 // clone stack but keep varSource to point to values
96 // from this frame to share variables.
97
98 copy.stack = stack.clone();
99 copy.stackAttributes = stackAttributes.clone();
100 copy.sDbl = sDbl.clone();
101
102 copy.frozen = false;
103 return copy;
104 }
105 }
106
107 private static final class ContinuationJump implements Serializable
108 {
109 static final long serialVersionUID = 7687739156004308247L;
110
111 CallFrame capturedFrame;
112 CallFrame branchFrame;
113 Object result;
114 double resultDbl;
115
116 ContinuationJump(NativeContinuation c, CallFrame current)
117 {
118 this.capturedFrame = (CallFrame)c.getImplementation();
119 if (this.capturedFrame == null || current == null) {
120 // Continuation and current execution does not share
121 // any frames if there is nothing to capture or
122 // if there is no currently executed frames
123 this.branchFrame = null;
124 } else {
125 // Search for branch frame where parent frame chains starting
126 // from captured and current meet.
127 CallFrame chain1 = this.capturedFrame;
128 CallFrame chain2 = current;
129
130 // First work parents of chain1 or chain2 until the same
131 // frame depth.
132 int diff = chain1.frameIndex - chain2.frameIndex;
133 if (diff != 0) {
134 if (diff < 0) {
135 // swap to make sure that
136 // chain1.frameIndex > chain2.frameIndex and diff > 0
137 chain1 = current;
138 chain2 = this.capturedFrame;
139 diff = -diff;
140 }
141 do {
142 chain1 = chain1.parentFrame;
143 } while (--diff != 0);
144 if (chain1.frameIndex != chain2.frameIndex) Kit.codeBug();
145 }
146
147 // Now walk parents in parallel until a shared frame is found
148 // or until the root is reached.
149 while (chain1 != chain2 && chain1 != null) {
150 chain1 = chain1.parentFrame;
151 chain2 = chain2.parentFrame;
152 }
153
154 this.branchFrame = chain1;
155 if (this.branchFrame != null && !this.branchFrame.frozen)
156 Kit.codeBug();
157 }
158 }
159 }
160
161 private static CallFrame captureFrameForGenerator(CallFrame frame) {
162 frame.frozen = true;
163 CallFrame result = frame.cloneFrozen();
164 frame.frozen = false;
165
166 // now isolate this frame from its previous context
167 result.parentFrame = null;
168 result.frameIndex = 0;
169
170 return result;
171 }
172
173 static {
174 // Checks for byte code consistencies, good compiler can eliminate them
175
176 if (Token.LAST_BYTECODE_TOKEN > 127) {
177 String str = "Violation of Token.LAST_BYTECODE_TOKEN <= 127";
178 System.err.println(str);
179 throw new IllegalStateException(str);
180 }
181 if (MIN_ICODE < -128) {
182 String str = "Violation of Interpreter.MIN_ICODE >= -128";
183 System.err.println(str);
184 throw new IllegalStateException(str);
185 }
186 }
187
188 public Object compile(CompilerEnvirons compilerEnv,
189 ScriptNode tree,
190 String encodedSource,
191 boolean returnFunction)
192 {
193 CodeGenerator cgen = new CodeGenerator();
194 itsData = cgen.compile(compilerEnv, tree, encodedSource, returnFunction);
195 return itsData;
196 }
197
198 public Script createScriptObject(Object bytecode, Object staticSecurityDomain)
199 {
200 if(bytecode != itsData)
201 {
202 Kit.codeBug();
203 }
204 return InterpretedFunction.createScript(itsData,
205 staticSecurityDomain);
206 }
207
208 public void setEvalScriptFlag(Script script) {
209 ((InterpretedFunction)script).idata.evalScriptFlag = true;
210 }
211
212
213 public Function createFunctionObject(Context cx, Scriptable scope,
214 Object bytecode, Object staticSecurityDomain)
215 {
216 if(bytecode != itsData)
217 {
218 Kit.codeBug();
219 }
220 return InterpretedFunction.createFunction(cx, scope, itsData,
221 staticSecurityDomain);
222 }
223
224 private static int getShort(byte[] iCode, int pc) {
225 return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF);
226 }
227
228 private static int getIndex(byte[] iCode, int pc) {
229 return ((iCode[pc] & 0xFF) << 8) | (iCode[pc + 1] & 0xFF);
230 }
231
232 private static int getInt(byte[] iCode, int pc) {
233 return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16)
234 | ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF);
235 }
236
237 private static int getExceptionHandler(CallFrame frame,
238 boolean onlyFinally)
239 {
240 int[] exceptionTable = frame.idata.itsExceptionTable;
241 if (exceptionTable == null) {
242 // No exception handlers
243 return -1;
244 }
245
246 // Icode switch in the interpreter increments PC immediately
247 // and it is necessary to subtract 1 from the saved PC
248 // to point it before the start of the next instruction.
249 int pc = frame.pc - 1;
250
251 // OPT: use binary search
252 int best = -1, bestStart = 0, bestEnd = 0;
253 for (int i = 0; i != exceptionTable.length; i += EXCEPTION_SLOT_SIZE) {
254 int start = exceptionTable[i + EXCEPTION_TRY_START_SLOT];
255 int end = exceptionTable[i + EXCEPTION_TRY_END_SLOT];
256 if (!(start <= pc && pc < end)) {
257 continue;
258 }
259 if (onlyFinally && exceptionTable[i + EXCEPTION_TYPE_SLOT] != 1) {
260 continue;
261 }
262 if (best >= 0) {
263 // Since handlers always nest and they never have shared end
264 // although they can share start it is sufficient to compare
265 // handlers ends
266 if (bestEnd < end) {
267 continue;
268 }
269 // Check the above assumption
270 if (bestStart > start) Kit.codeBug(); // should be nested
271 if (bestEnd == end) Kit.codeBug(); // no ens sharing
272 }
273 best = i;
274 bestStart = start;
275 bestEnd = end;
276 }
277 return best;
278 }
279
280 static void dumpICode(InterpreterData idata)
281 {
282 if (!Token.printICode) {
283 return;
284 }
285
286 byte iCode[] = idata.itsICode;
287 int iCodeLength = iCode.length;
288 String[] strings = idata.itsStringTable;
289 PrintStream out = System.out;
290 out.println("ICode dump, for " + idata.itsName
291 + ", length = " + iCodeLength);
292 out.println("MaxStack = " + idata.itsMaxStack);
293
294 int indexReg = 0;
295 for (int pc = 0; pc < iCodeLength; ) {
296 out.flush();
297 out.print(" [" + pc + "] ");
298 int token = iCode[pc];
299 int icodeLength = bytecodeSpan(token);
300 String tname = Icode.bytecodeName(token);
301 int old_pc = pc;
302 ++pc;
303 switch (token) {
304 default:
305 if (icodeLength != 1) Kit.codeBug();
306 out.println(tname);
307 break;
308
309 case Icode_GOSUB :
310 case Token.GOTO :
311 case Token.IFEQ :
312 case Token.IFNE :
313 case Icode_IFEQ_POP :
314 case Icode_LEAVEDQ : {
315 int newPC = pc + getShort(iCode, pc) - 1;
316 out.println(tname + " " + newPC);
317 pc += 2;
318 break;
319 }
320 case Icode_VAR_INC_DEC :
321 case Icode_NAME_INC_DEC :
322 case Icode_PROP_INC_DEC :
323 case Icode_ELEM_INC_DEC :
324 case Icode_REF_INC_DEC: {
325 int incrDecrType = iCode[pc];
326 out.println(tname + " " + incrDecrType);
327 ++pc;
328 break;
329 }
330
331 case Icode_CALLSPECIAL : {
332 int callType = iCode[pc] & 0xFF;
333 boolean isNew = (iCode[pc + 1] != 0);
334 int line = getIndex(iCode, pc+2);
335 out.println(tname+" "+callType+" "+isNew+" "+indexReg+" "+line);
336 pc += 4;
337 break;
338 }
339
340 case Token.CATCH_SCOPE:
341 {
342 boolean afterFisrtFlag = (iCode[pc] != 0);
343 out.println(tname+" "+afterFisrtFlag);
344 ++pc;
345 }
346 break;
347 case Token.REGEXP :
348 out.println(tname+" "+idata.itsRegExpLiterals[indexReg]);
349 break;
350 case Token.OBJECTLIT :
351 case Icode_SPARE_ARRAYLIT :
352 out.println(tname+" "+idata.literalIds[indexReg]);
353 break;
354 case Icode_CLOSURE_EXPR :
355 case Icode_CLOSURE_STMT :
356 out.println(tname+" "+idata.itsNestedFunctions[indexReg]);
357 break;
358 case Token.CALL :
359 case Icode_TAIL_CALL :
360 case Token.REF_CALL :
361 case Token.NEW :
362 out.println(tname+' '+indexReg);
363 break;
364 case Token.THROW :
365 case Token.YIELD :
366 case Icode_GENERATOR :
367 case Icode_GENERATOR_END :
368 {
369 int line = getIndex(iCode, pc);
370 out.println(tname + " : " + line);
371 pc += 2;
372 break;
373 }
374 case Icode_SHORTNUMBER : {
375 int value = getShort(iCode, pc);
376 out.println(tname + " " + value);
377 pc += 2;
378 break;
379 }
380 case Icode_INTNUMBER : {
381 int value = getInt(iCode, pc);
382 out.println(tname + " " + value);
383 pc += 4;
384 break;
385 }
386 case Token.NUMBER : {
387 double value = idata.itsDoubleTable[indexReg];
388 out.println(tname + " " + value);
389 break;
390 }
391 case Icode_LINE : {
392 int line = getIndex(iCode, pc);
393 out.println(tname + " : " + line);
394 pc += 2;
395 break;
396 }
397 case Icode_REG_STR1: {
398 String str = strings[0xFF & iCode[pc]];
399 out.println(tname + " \"" + str + '"');
400 ++pc;
401 break;
402 }
403 case Icode_REG_STR2: {
404 String str = strings[getIndex(iCode, pc)];
405 out.println(tname + " \"" + str + '"');
406 pc += 2;
407 break;
408 }
409 case Icode_REG_STR4: {
410 String str = strings[getInt(iCode, pc)];
411 out.println(tname + " \"" + str + '"');
412 pc += 4;
413 break;
414 }
415 case Icode_REG_IND_C0:
416 indexReg = 0;
417 out.println(tname);
418 break;
419 case Icode_REG_IND_C1:
420 indexReg = 1;
421 out.println(tname);
422 break;
423 case Icode_REG_IND_C2:
424 indexReg = 2;
425 out.println(tname);
426 break;
427 case Icode_REG_IND_C3:
428 indexReg = 3;
429 out.println(tname);
430 break;
431 case Icode_REG_IND_C4:
432 indexReg = 4;
433 out.println(tname);
434 break;
435 case Icode_REG_IND_C5:
436 indexReg = 5;
437 out.println(tname);
438 break;
439 case Icode_REG_IND1: {
440 indexReg = 0xFF & iCode[pc];
441 out.println(tname+" "+indexReg);
442 ++pc;
443 break;
444 }
445 case Icode_REG_IND2: {
446 indexReg = getIndex(iCode, pc);
447 out.println(tname+" "+indexReg);
448 pc += 2;
449 break;
450 }
451 case Icode_REG_IND4: {
452 indexReg = getInt(iCode, pc);
453 out.println(tname+" "+indexReg);
454 pc += 4;
455 break;
456 }
457 case Icode_GETVAR1:
458 case Icode_SETVAR1:
459 case Icode_SETCONSTVAR1:
460 indexReg = iCode[pc];
461 out.println(tname+" "+indexReg);
462 ++pc;
463 break;
464 }
465 if (old_pc + icodeLength != pc) Kit.codeBug();
466 }
467
468 int[] table = idata.itsExceptionTable;
469 if (table != null) {
470 out.println("Exception handlers: "
471 +table.length / EXCEPTION_SLOT_SIZE);
472 for (int i = 0; i != table.length;
473 i += EXCEPTION_SLOT_SIZE)
474 {
475 int tryStart = table[i + EXCEPTION_TRY_START_SLOT];
476 int tryEnd = table[i + EXCEPTION_TRY_END_SLOT];
477 int handlerStart = table[i + EXCEPTION_HANDLER_SLOT];
478 int type = table[i + EXCEPTION_TYPE_SLOT];
479 int exceptionLocal = table[i + EXCEPTION_LOCAL_SLOT];
480 int scopeLocal = table[i + EXCEPTION_SCOPE_SLOT];
481
482 out.println(" tryStart="+tryStart+" tryEnd="+tryEnd
483 +" handlerStart="+handlerStart
484 +" type="+(type == 0 ? "catch" : "finally")
485 +" exceptionLocal="+exceptionLocal);
486 }
487 }
488 out.flush();
489 }
490
491 private static int bytecodeSpan(int bytecode)
492 {
493 switch (bytecode) {
494 case Token.THROW :
495 case Token.YIELD:
496 case Icode_GENERATOR:
497 case Icode_GENERATOR_END:
498 // source line
499 return 1 + 2;
500
501 case Icode_GOSUB :
502 case Token.GOTO :
503 case Token.IFEQ :
504 case Token.IFNE :
505 case Icode_IFEQ_POP :
506 case Icode_LEAVEDQ :
507 // target pc offset
508 return 1 + 2;
509
510 case Icode_CALLSPECIAL :
511 // call type
512 // is new
513 // line number
514 return 1 + 1 + 1 + 2;
515
516 case Token.CATCH_SCOPE:
517 // scope flag
518 return 1 + 1;
519
520 case Icode_VAR_INC_DEC:
521 case Icode_NAME_INC_DEC:
522 case Icode_PROP_INC_DEC:
523 case Icode_ELEM_INC_DEC:
524 case Icode_REF_INC_DEC:
525 // type of ++/--
526 return 1 + 1;
527
528 case Icode_SHORTNUMBER :
529 // short number
530 return 1 + 2;
531
532 case Icode_INTNUMBER :
533 // int number
534 return 1 + 4;
535
536 case Icode_REG_IND1:
537 // ubyte index
538 return 1 + 1;
539
540 case Icode_REG_IND2:
541 // ushort index
542 return 1 + 2;
543
544 case Icode_REG_IND4:
545 // int index
546 return 1 + 4;
547
548 case Icode_REG_STR1:
549 // ubyte string index
550 return 1 + 1;
551
552 case Icode_REG_STR2:
553 // ushort string index
554 return 1 + 2;
555
556 case Icode_REG_STR4:
557 // int string index
558 return 1 + 4;
559
560 case Icode_GETVAR1:
561 case Icode_SETVAR1:
562 case Icode_SETCONSTVAR1:
563 // byte var index
564 return 1 + 1;
565
566 case Icode_LINE :
567 // line number
568 return 1 + 2;
569 }
570 if (!validBytecode(bytecode)) throw Kit.codeBug();
571 return 1;
572 }
573
574 static int[] getLineNumbers(InterpreterData data)
575 {
576 UintMap presentLines = new UintMap();
577
578 byte[] iCode = data.itsICode;
579 int iCodeLength = iCode.length;
580 for (int pc = 0; pc != iCodeLength;) {
581 int bytecode = iCode[pc];
582 int span = bytecodeSpan(bytecode);
583 if (bytecode == Icode_LINE) {
584 if (span != 3) Kit.codeBug();
585 int line = getIndex(iCode, pc + 1);
586 presentLines.put(line, 0);
587 }
588 pc += span;
589 }
590
591 return presentLines.getKeys();
592 }
593
594 public void captureStackInfo(RhinoException ex)
595 {
596 Context cx = Context.getCurrentContext();
597 if (cx == null || cx.lastInterpreterFrame == null) {
598 // No interpreter invocations
599 ex.interpreterStackInfo = null;
600 ex.interpreterLineData = null;
601 return;
602 }
603 // has interpreter frame on the stack
604 CallFrame[] array;
605 if (cx.previousInterpreterInvocations == null
606 || cx.previousInterpreterInvocations.size() == 0)
607 {
608 array = new CallFrame[1];
609 } else {
610 int previousCount = cx.previousInterpreterInvocations.size();
611 if (cx.previousInterpreterInvocations.peek()
612 == cx.lastInterpreterFrame)
613 {
614 // It can happen if exception was generated after
615 // frame was pushed to cx.previousInterpreterInvocations
616 // but before assignment to cx.lastInterpreterFrame.
617 // In this case frames has to be ignored.
618 --previousCount;
619 }
620 array = new CallFrame[previousCount + 1];
621 cx.previousInterpreterInvocations.toArray(array);
622 }
623 array[array.length - 1] = (CallFrame)cx.lastInterpreterFrame;
624
625 int interpreterFrameCount = 0;
626 for (int i = 0; i != array.length; ++i) {
627 interpreterFrameCount += 1 + array[i].frameIndex;
628 }
629
630 int[] linePC = new int[interpreterFrameCount];
631 // Fill linePC with pc positions from all interpreter frames.
632 // Start from the most nested frame
633 int linePCIndex = interpreterFrameCount;
634 for (int i = array.length; i != 0;) {
635 --i;
636 CallFrame frame = array[i];
637 while (frame != null) {
638 --linePCIndex;
639 linePC[linePCIndex] = frame.pcSourceLineStart;
640 frame = frame.parentFrame;
641 }
642 }
643 if (linePCIndex != 0) Kit.codeBug();
644
645 ex.interpreterStackInfo = array;
646 ex.interpreterLineData = linePC;
647 }
648
649 public String getSourcePositionFromStack(Context cx, int[] linep)
650 {
651 CallFrame frame = (CallFrame)cx.lastInterpreterFrame;
652 InterpreterData idata = frame.idata;
653 if (frame.pcSourceLineStart >= 0) {
654 linep[0] = getIndex(idata.itsICode, frame.pcSourceLineStart);
655 } else {
656 linep[0] = 0;
657 }
658 return idata.itsSourceFile;
659 }
660
661 public String getPatchedStack(RhinoException ex,
662 String nativeStackTrace)
663 {
664 String tag = "org.mozilla.javascript.Interpreter.interpretLoop";
665 StringBuilder sb = new StringBuilder(nativeStackTrace.length() + 1000);
666 String lineSeparator = SecurityUtilities.getSystemProperty("line.separator");
667
668 CallFrame[] array = (CallFrame[])ex.interpreterStackInfo;
669 int[] linePC = ex.interpreterLineData;
670 int arrayIndex = array.length;
671 int linePCIndex = linePC.length;
672 int offset = 0;
673 while (arrayIndex != 0) {
674 --arrayIndex;
675 int pos = nativeStackTrace.indexOf(tag, offset);
676 if (pos < 0) {
677 break;
678 }
679
680 // Skip tag length
681 pos += tag.length();
682 // Skip until the end of line
683 for (; pos != nativeStackTrace.length(); ++pos) {
684 char c = nativeStackTrace.charAt(pos);
685 if (c == '\n' || c == '\r') {
686 break;
687 }
688 }
689 sb.append(nativeStackTrace.substring(offset, pos));
690 offset = pos;
691
692 CallFrame frame = array[arrayIndex];
693 while (frame != null) {
694 if (linePCIndex == 0) Kit.codeBug();
695 --linePCIndex;
696 InterpreterData idata = frame.idata;
697 sb.append(lineSeparator);
698 sb.append("\tat script");
699 if (idata.itsName != null && idata.itsName.length() != 0) {
700 sb.append('.');
701 sb.append(idata.itsName);
702 }
703 sb.append('(');
704 sb.append(idata.itsSourceFile);
705 int pc = linePC[linePCIndex];
706 if (pc >= 0) {
707 // Include line info only if available
708 sb.append(':');
709 sb.append(getIndex(idata.itsICode, pc));
710 }
711 sb.append(')');
712 frame = frame.parentFrame;
713 }
714 }
715 sb.append(nativeStackTrace.substring(offset));
716
717 return sb.toString();
718 }
719
720 public List<String> getScriptStack(RhinoException ex) {
721 ScriptStackElement[][] stack = getScriptStackElements(ex);
722 List<String> list = new ArrayList<String>(stack.length);
723 String lineSeparator =
724 SecurityUtilities.getSystemProperty("line.separator");
725 for (ScriptStackElement[] group : stack) {
726 StringBuilder sb = new StringBuilder();
727 for (ScriptStackElement elem : group) {
728 elem.renderJavaStyle(sb);
729 sb.append(lineSeparator);
730 }
731 list.add(sb.toString());
732 }
733 return list;
734 }
735
736 public ScriptStackElement[][] getScriptStackElements(RhinoException ex)
737 {
738 if (ex.interpreterStackInfo == null) {
739 return null;
740 }
741
742 List<ScriptStackElement[]> list = new ArrayList<ScriptStackElement[]>();
743
744 CallFrame[] array = (CallFrame[])ex.interpreterStackInfo;
745 int[] linePC = ex.interpreterLineData;
746 int arrayIndex = array.length;
747 int linePCIndex = linePC.length;
748 while (arrayIndex != 0) {
749 --arrayIndex;
750 CallFrame frame = array[arrayIndex];
751 List<ScriptStackElement> group = new ArrayList<ScriptStackElement>();
752 while (frame != null) {
753 if (linePCIndex == 0) Kit.codeBug();
754 --linePCIndex;
755 InterpreterData idata = frame.idata;
756 String fileName = idata.itsSourceFile;
757 String functionName = null;
758 int lineNumber = -1;
759 int pc = linePC[linePCIndex];
760 if (pc >= 0) {
761 lineNumber = getIndex(idata.itsICode, pc);
762 }
763 if (idata.itsName != null && idata.itsName.length() != 0) {
764 functionName = idata.itsName;
765 }
766 frame = frame.parentFrame;
767 group.add(new ScriptStackElement(fileName, functionName, lineNumber));
768 }
769 list.add(group.toArray(new ScriptStackElement[group.size()]));
770 }
771 return list.toArray(new ScriptStackElement[list.size()][]);
772 }
773
774 static String getEncodedSource(InterpreterData idata)
775 {
776 if (idata.encodedSource == null) {
777 return null;
778 }
779 return idata.encodedSource.substring(idata.encodedSourceStart,
780 idata.encodedSourceEnd);
781 }
782
783 private static void initFunction(Context cx, Scriptable scope,
784 InterpretedFunction parent, int index)
785 {
786 InterpretedFunction fn;
787 fn = InterpretedFunction.createFunction(cx, scope, parent, index);
788 ScriptRuntime.initFunction(cx, scope, fn, fn.idata.itsFunctionType,
789 parent.idata.evalScriptFlag);
790 }
791
792 static Object interpret(InterpretedFunction ifun,
793 Context cx, Scriptable scope,
794 Scriptable thisObj, Object[] args)
795 {
796 if (!ScriptRuntime.hasTopCall(cx)) Kit.codeBug();
797
798 if (cx.interpreterSecurityDomain != ifun.securityDomain) {
799 Object savedDomain = cx.interpreterSecurityDomain;
800 cx.interpreterSecurityDomain = ifun.securityDomain;
801 try {
802 return ifun.securityController.callWithDomain(
803 ifun.securityDomain, cx, ifun, scope, thisObj, args);
804 } finally {
805 cx.interpreterSecurityDomain = savedDomain;
806 }
807 }
808
809 CallFrame frame = new CallFrame();
810 initFrame(cx, scope, thisObj, args, null, 0, args.length,
811 ifun, null, frame);
812 frame.isContinuationsTopFrame = cx.isContinuationsTopCall;
813 cx.isContinuationsTopCall = false;
814
815 return interpretLoop(cx, frame, null);
816 }
817
818 static class GeneratorState {
819 GeneratorState(int operation, Object value) {
820 this.operation = operation;
821 this.value = value;
822 }
823 int operation;
824 Object value;
825 RuntimeException returnedException;
826 }
827
828 public static Object resumeGenerator(Context cx,
829 Scriptable scope,
830 int operation,
831 Object savedState,
832 Object value)
833 {
834 CallFrame frame = (CallFrame) savedState;
835 GeneratorState generatorState = new GeneratorState(operation, value);
836 if (operation == NativeGenerator.GENERATOR_CLOSE) {
837 try {
838 return interpretLoop(cx, frame, generatorState);
839 } catch (RuntimeException e) {
840 // Only propagate exceptions other than closingException
841 if (e != value)
842 throw e;
843 }
844 return Undefined.instance;
845 }
846 Object result = interpretLoop(cx, frame, generatorState);
847 if (generatorState.returnedException != null)
848 throw generatorState.returnedException;
849 return result;
850 }
851
852 public static Object restartContinuation(NativeContinuation c, Context cx,
853 Scriptable scope, Object[] args)
854 {
855 if (!ScriptRuntime.hasTopCall(cx)) {
856 return ScriptRuntime.doTopCall(c, cx, scope, null, args, cx.isTopLevelStrict);
857 }
858
859 Object arg;
860 if (args.length == 0) {
861 arg = Undefined.instance;
862 } else {
863 arg = args[0];
864 }
865
866 CallFrame capturedFrame = (CallFrame)c.getImplementation();
867 if (capturedFrame == null) {
868 // No frames to restart
869 return arg;
870 }
871
872 ContinuationJump cjump = new ContinuationJump(c, null);
873
874 cjump.result = arg;
875 return interpretLoop(cx, null, cjump);
876 }
877
878 private static Object interpretLoop(Context cx, CallFrame frame,
879 Object throwable)
880 {
881 // throwable holds exception object to rethrow or catch
882 // It is also used for continuation restart in which case
883 // it holds ContinuationJump
884
885 final Object DBL_MRK = DOUBLE_MARK;
886 final Object undefined = Undefined.instance;
887
888 final boolean instructionCounting = (cx.instructionThreshold != 0);
889 // arbitrary number to add to instructionCount when calling
890 // other functions
891 final int INVOCATION_COST = 100;
892 // arbitrary exception cost for instruction counting
893 final int EXCEPTION_COST = 100;
894
895 String stringReg = null;
896 int indexReg = -1;
897
898 if (cx.lastInterpreterFrame != null) {
899 // save the top frame from the previous interpretLoop
900 // invocation on the stack
901 if (cx.previousInterpreterInvocations == null) {
902 cx.previousInterpreterInvocations = new ObjArray();
903 }
904 cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame);
905 }
906
907 // When restarting continuation throwable is not null and to jump
908 // to the code that rewind continuation state indexReg should be set
909 // to -1.
910 // With the normal call throwable == null and indexReg == -1 allows to
911 // catch bugs with using indeReg to access array elements before
912 // initializing indexReg.
913
914 GeneratorState generatorState = null;
915 if (throwable != null) {
916 if (throwable instanceof GeneratorState) {
917 generatorState = (GeneratorState) throwable;
918
919 // reestablish this call frame
920 enterFrame(cx, frame, ScriptRuntime.emptyArgs, true);
921 throwable = null;
922 } else if (!(throwable instanceof ContinuationJump)) {
923 // It should be continuation
924 Kit.codeBug();
925 }
926 }
927
928 Object interpreterResult = null;
929 double interpreterResultDbl = 0.0;
930
931 StateLoop: for (;;) {
932 withoutExceptions: try {
933
934 if (throwable != null) {
935 // Need to return both 'frame' and 'throwable' from
936 // 'processThrowable', so just added a 'throwable'
937 // member in 'frame'.
938 frame = processThrowable(cx, throwable, frame, indexReg,
939 instructionCounting);
940 throwable = frame.throwable;
941 frame.throwable = null;
942 } else {
943 if (generatorState == null && frame.frozen) Kit.codeBug();
944 }
945
946 // Use local variables for constant values in frame
947 // for faster access
948 Object[] stack = frame.stack;
949 double[] sDbl = frame.sDbl;
950 Object[] vars = frame.varSource.stack;
951 double[] varDbls = frame.varSource.sDbl;
952 int[] varAttributes = frame.varSource.stackAttributes;
953 byte[] iCode = frame.idata.itsICode;
954 String[] strings = frame.idata.itsStringTable;
955
956 // Use local for stackTop as well. Since execption handlers
957 // can only exist at statement level where stack is empty,
958 // it is necessary to save/restore stackTop only across
959 // function calls and normal returns.
960 int stackTop = frame.savedStackTop;
961
962 // Store new frame in cx which is used for error reporting etc.
963 cx.lastInterpreterFrame = frame;
964
965 Loop: for (;;) {
966
967 // Exception handler assumes that PC is already incremented
968 // pass the instruction start when it searches the
969 // exception handler
970 int op = iCode[frame.pc++];
971 jumplessRun: {
972
973 // Back indent to ease implementation reading
974 switch (op) {
975 case Icode_GENERATOR: {
976 if (!frame.frozen) {
977 // First time encountering this opcode: create new generator
978 // object and return
979 frame.pc--; // we want to come back here when we resume
980 CallFrame generatorFrame = captureFrameForGenerator(frame);
981 generatorFrame.frozen = true;
982 NativeGenerator generator = new NativeGenerator(frame.scope,
983 generatorFrame.fnOrScript, generatorFrame);
984 frame.result = generator;
985 break Loop;
986 } else {
987 // We are now resuming execution. Fall through to YIELD case.
988 }
989 }
990 // fall through...
991 case Token.YIELD: {
992 if (!frame.frozen) {
993 return freezeGenerator(cx, frame, stackTop, generatorState);
994 } else {
995 Object obj = thawGenerator(frame, stackTop, generatorState, op);
996 if (obj != Scriptable.NOT_FOUND) {
997 throwable = obj;
998 break withoutExceptions;
999 }
1000 continue Loop;
1001 }
1002 }
1003 case Icode_GENERATOR_END: {
1004 // throw StopIteration
1005 frame.frozen = true;
1006 int sourceLine = getIndex(iCode, frame.pc);
1007 generatorState.returnedException = new JavaScriptException(
1008 NativeIterator.getStopIterationObject(frame.scope),
1009 frame.idata.itsSourceFile, sourceLine);
1010 break Loop;
1011 }
1012 case Token.THROW: {
1013 Object value = stack[stackTop];
1014 if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1015 --stackTop;
1016
1017 int sourceLine = getIndex(iCode, frame.pc);
1018 throwable = new JavaScriptException(value,
1019 frame.idata.itsSourceFile,
1020 sourceLine);
1021 break withoutExceptions;
1022 }
1023 case Token.RETHROW: {
1024 indexReg += frame.localShift;
1025 throwable = stack[indexReg];
1026 break withoutExceptions;
1027 }
1028 case Token.GE :
1029 case Token.LE :
1030 case Token.GT :
1031 case Token.LT : {
1032 stackTop = doCompare(frame, op, stack, sDbl, stackTop);
1033 continue Loop;
1034 }
1035 case Token.IN :
1036 case Token.INSTANCEOF : {
1037 stackTop = doInOrInstanceof(cx, op, stack, sDbl, stackTop);
1038 continue Loop;
1039 }
1040 case Token.EQ :
1041 case Token.NE : {
1042 --stackTop;
1043 boolean valBln = doEquals(stack, sDbl, stackTop);
1044 valBln ^= (op == Token.NE);
1045 stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
1046 continue Loop;
1047 }
1048 case Token.SHEQ :
1049 case Token.SHNE : {
1050 --stackTop;
1051 boolean valBln = doShallowEquals(stack, sDbl, stackTop);
1052 valBln ^= (op == Token.SHNE);
1053 stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
1054 continue Loop;
1055 }
1056 case Token.IFNE :
1057 if (stack_boolean(frame, stackTop--)) {
1058 frame.pc += 2;
1059 continue Loop;
1060 }
1061 break jumplessRun;
1062 case Token.IFEQ :
1063 if (!stack_boolean(frame, stackTop--)) {
1064 frame.pc += 2;
1065 continue Loop;
1066 }
1067 break jumplessRun;
1068 case Icode_IFEQ_POP :
1069 if (!stack_boolean(frame, stackTop--)) {
1070 frame.pc += 2;
1071 continue Loop;
1072 }
1073 stack[stackTop--] = null;
1074 break jumplessRun;
1075 case Token.GOTO :
1076 break jumplessRun;
1077 case Icode_GOSUB :
1078 ++stackTop;
1079 stack[stackTop] = DBL_MRK;
1080 sDbl[stackTop] = frame.pc + 2;
1081 break jumplessRun;
1082 case Icode_STARTSUB :
1083 if (stackTop == frame.emptyStackTop + 1) {
1084 // Call from Icode_GOSUB: store return PC address in the local
1085 indexReg += frame.localShift;
1086 stack[indexReg] = stack[stackTop];
1087 sDbl[indexReg] = sDbl[stackTop];
1088 --stackTop;
1089 } else {
1090 // Call from exception handler: exception object is already stored
1091 // in the local
1092 if (stackTop != frame.emptyStackTop) Kit.codeBug();
1093 }
1094 continue Loop;
1095 case Icode_RETSUB : {
1096 // indexReg: local to store return address
1097 if (instructionCounting) {
1098 addInstructionCount(cx, frame, 0);
1099 }
1100 indexReg += frame.localShift;
1101 Object value = stack[indexReg];
1102 if (value != DBL_MRK) {
1103 // Invocation from exception handler, restore object to rethrow
1104 throwable = value;
1105 break withoutExceptions;
1106 }
1107 // Normal return from GOSUB
1108 frame.pc = (int)sDbl[indexReg];
1109 if (instructionCounting) {
1110 frame.pcPrevBranch = frame.pc;
1111 }
1112 continue Loop;
1113 }
1114 case Icode_POP :
1115 stack[stackTop] = null;
1116 stackTop--;
1117 continue Loop;
1118 case Icode_POP_RESULT :
1119 frame.result = stack[stackTop];
1120 frame.resultDbl = sDbl[stackTop];
1121 stack[stackTop] = null;
1122 --stackTop;
1123 continue Loop;
1124 case Icode_DUP :
1125 stack[stackTop + 1] = stack[stackTop];
1126 sDbl[stackTop + 1] = sDbl[stackTop];
1127 stackTop++;
1128 continue Loop;
1129 case Icode_DUP2 :
1130 stack[stackTop + 1] = stack[stackTop - 1];
1131 sDbl[stackTop + 1] = sDbl[stackTop - 1];
1132 stack[stackTop + 2] = stack[stackTop];
1133 sDbl[stackTop + 2] = sDbl[stackTop];
1134 stackTop += 2;
1135 continue Loop;
1136 case Icode_SWAP : {
1137 Object o = stack[stackTop];
1138 stack[stackTop] = stack[stackTop - 1];
1139 stack[stackTop - 1] = o;
1140 double d = sDbl[stackTop];
1141 sDbl[stackTop] = sDbl[stackTop - 1];
1142 sDbl[stackTop - 1] = d;
1143 continue Loop;
1144 }
1145 case Token.RETURN :
1146 frame.result = stack[stackTop];
1147 frame.resultDbl = sDbl[stackTop];
1148 --stackTop;
1149 break Loop;
1150 case Token.RETURN_RESULT :
1151 break Loop;
1152 case Icode_RETUNDEF :
1153 frame.result = undefined;
1154 break Loop;
1155 case Token.BITNOT : {
1156 int rIntValue = stack_int32(frame, stackTop);
1157 stack[stackTop] = DBL_MRK;
1158 sDbl[stackTop] = ~rIntValue;
1159 continue Loop;
1160 }
1161 case Token.BITAND :
1162 case Token.BITOR :
1163 case Token.BITXOR :
1164 case Token.LSH :
1165 case Token.RSH : {
1166 stackTop = doBitOp(frame, op, stack, sDbl, stackTop);
1167 continue Loop;
1168 }
1169 case Token.URSH : {
1170 double lDbl = stack_double(frame, stackTop - 1);
1171 int rIntValue = stack_int32(frame, stackTop) & 0x1F;
1172 stack[--stackTop] = DBL_MRK;
1173 sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
1174 continue Loop;
1175 }
1176 case Token.NEG :
1177 case Token.POS : {
1178 double rDbl = stack_double(frame, stackTop);
1179 stack[stackTop] = DBL_MRK;
1180 if (op == Token.NEG) {
1181 rDbl = -rDbl;
1182 }
1183 sDbl[stackTop] = rDbl;
1184 continue Loop;
1185 }
1186 case Token.ADD :
1187 --stackTop;
1188 doAdd(stack, sDbl, stackTop, cx);
1189 continue Loop;
1190 case Token.SUB :
1191 case Token.MUL :
1192 case Token.DIV :
1193 case Token.MOD : {
1194 stackTop = doArithmetic(frame, op, stack, sDbl, stackTop);
1195 continue Loop;
1196 }
1197 case Token.NOT :
1198 stack[stackTop] = ScriptRuntime.wrapBoolean(
1199 !stack_boolean(frame, stackTop));
1200 continue Loop;
1201 case Token.BINDNAME :
1202 stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg);
1203 continue Loop;
1204 case Token.STRICT_SETNAME:
1205 case Token.SETNAME : {
1206 Object rhs = stack[stackTop];
1207 if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1208 --stackTop;
1209 Scriptable lhs = (Scriptable)stack[stackTop];
1210 stack[stackTop] = op == Token.SETNAME ?
1211 ScriptRuntime.setName(lhs, rhs, cx,
1212 frame.scope, stringReg) :
1213 ScriptRuntime.strictSetName(lhs, rhs, cx,
1214 frame.scope, stringReg);
1215 continue Loop;
1216 }
1217 case Icode_SETCONST: {
1218 Object rhs = stack[stackTop];
1219 if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1220 --stackTop;
1221 Scriptable lhs = (Scriptable)stack[stackTop];
1222 stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg);
1223 continue Loop;
1224 }
1225 case Token.DELPROP :
1226 case Icode_DELNAME : {
1227 stackTop = doDelName(cx, frame, op, stack, sDbl, stackTop);
1228 continue Loop;
1229 }
1230 case Token.GETPROPNOWARN : {
1231 Object lhs = stack[stackTop];
1232 if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1233 stack[stackTop] = ScriptRuntime.getObjectPropNoWarn(lhs, stringReg,
1234 cx, frame.scope);
1235 continue Loop;
1236 }
1237 case Token.GETPROP : {
1238 Object lhs = stack[stackTop];
1239 if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1240 stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg,
1241 cx, frame.scope);
1242 continue Loop;
1243 }
1244 case Token.SETPROP : {
1245 Object rhs = stack[stackTop];
1246 if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1247 --stackTop;
1248 Object lhs = stack[stackTop];
1249 if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1250 stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs,
1251 cx, frame.scope);
1252 continue Loop;
1253 }
1254 case Icode_PROP_INC_DEC : {
1255 Object lhs = stack[stackTop];
1256 if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1257 stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg,
1258 cx, frame.scope,
1259 iCode[frame.pc]);
1260 ++frame.pc;
1261 continue Loop;
1262 }
1263 case Token.GETELEM : {
1264 stackTop = doGetElem(cx, frame, stack, sDbl, stackTop);
1265 continue Loop;
1266 }
1267 case Token.SETELEM : {
1268 stackTop = doSetElem(cx, frame, stack, sDbl, stackTop);
1269 continue Loop;
1270 }
1271 case Icode_ELEM_INC_DEC: {
1272 stackTop = doElemIncDec(cx, frame, iCode, stack, sDbl, stackTop);
1273 continue Loop;
1274 }
1275 case Token.GET_REF : {
1276 Ref ref = (Ref)stack[stackTop];
1277 stack[stackTop] = ScriptRuntime.refGet(ref, cx);
1278 continue Loop;
1279 }
1280 case Token.SET_REF : {
1281 Object value = stack[stackTop];
1282 if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1283 --stackTop;
1284 Ref ref = (Ref)stack[stackTop];
1285 stack[stackTop] = ScriptRuntime.refSet(ref, value, cx, frame.scope);
1286 continue Loop;
1287 }
1288 case Token.DEL_REF : {
1289 Ref ref = (Ref)stack[stackTop];
1290 stack[stackTop] = ScriptRuntime.refDel(ref, cx);
1291 continue Loop;
1292 }
1293 case Icode_REF_INC_DEC : {
1294 Ref ref = (Ref)stack[stackTop];
1295 stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, frame.scope,
1296 iCode[frame.pc]);
1297 ++frame.pc;
1298 continue Loop;
1299 }
1300 case Token.LOCAL_LOAD :
1301 ++stackTop;
1302 indexReg += frame.localShift;
1303 stack[stackTop] = stack[indexReg];
1304 sDbl[stackTop] = sDbl[indexReg];
1305 continue Loop;
1306 case Icode_LOCAL_CLEAR :
1307 indexReg += frame.localShift;
1308 stack[indexReg] = null;
1309 continue Loop;
1310 case Icode_NAME_AND_THIS :
1311 // stringReg: name
1312 ++stackTop;
1313 stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg,
1314 cx, frame.scope);
1315 ++stackTop;
1316 stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
1317 continue Loop;
1318 case Icode_PROP_AND_THIS: {
1319 Object obj = stack[stackTop];
1320 if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1321 // stringReg: property
1322 stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg,
1323 cx, frame.scope);
1324 ++stackTop;
1325 stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
1326 continue Loop;
1327 }
1328 case Icode_ELEM_AND_THIS: {
1329 Object obj = stack[stackTop - 1];
1330 if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]);
1331 Object id = stack[stackTop];
1332 if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1333 stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx,
1334 frame.scope);
1335 stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
1336 continue Loop;
1337 }
1338 case Icode_VALUE_AND_THIS : {
1339 Object value = stack[stackTop];
1340 if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1341 stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx);
1342 ++stackTop;
1343 stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
1344 continue Loop;
1345 }
1346 case Icode_CALLSPECIAL : {
1347 if (instructionCounting) {
1348 cx.instructionCount += INVOCATION_COST;
1349 }
1350 stackTop = doCallSpecial(cx, frame, stack, sDbl, stackTop, iCode, indexReg);
1351 continue Loop;
1352 }
1353 case Token.CALL :
1354 case Icode_TAIL_CALL :
1355 case Token.REF_CALL : {
1356 if (instructionCounting) {
1357 cx.instructionCount += INVOCATION_COST;
1358 }
1359 // stack change: function thisObj arg0 .. argN -> result
1360 // indexReg: number of arguments
1361 stackTop -= 1 + indexReg;
1362
1363 // CALL generation ensures that fun and funThisObj
1364 // are already Scriptable and Callable objects respectively
1365 Callable fun = (Callable)stack[stackTop];
1366 Scriptable funThisObj = (Scriptable)stack[stackTop + 1];
1367 if (op == Token.REF_CALL) {
1368 Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2,
1369 indexReg);
1370 stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj,
1371 outArgs, cx);
1372 continue Loop;
1373 }
1374 Scriptable calleeScope = frame.scope;
1375 if (frame.useActivation) {
1376 calleeScope = ScriptableObject.getTopLevelScope(frame.scope);
1377 }
1378 if (fun instanceof InterpretedFunction) {
1379 InterpretedFunction ifun = (InterpretedFunction)fun;
1380 if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
1381 CallFrame callParentFrame = frame;
1382 CallFrame calleeFrame = new CallFrame();
1383 if (op == Icode_TAIL_CALL) {
1384 // In principle tail call can re-use the current
1385 // frame and its stack arrays but it is hard to
1386 // do properly. Any exceptions that can legally
1387 // happen during frame re-initialization including
1388 // StackOverflowException during innocent looking
1389 // System.arraycopy may leave the current frame
1390 // data corrupted leading to undefined behaviour
1391 // in the catch code bellow that unwinds JS stack
1392 // on exceptions. Then there is issue about frame release
1393 // end exceptions there.
1394 // To avoid frame allocation a released frame
1395 // can be cached for re-use which would also benefit
1396 // non-tail calls but it is not clear that this caching
1397 // would gain in performance due to potentially
1398 // bad interaction with GC.
1399 callParentFrame = frame.parentFrame;
1400 // Release the current frame. See Bug #344501 to see why
1401 // it is being done here.
1402 exitFrame(cx, frame, null);
1403 }
1404 initFrame(cx, calleeScope, funThisObj, stack, sDbl,
1405 stackTop + 2, indexReg, ifun, callParentFrame,
1406 calleeFrame);
1407 if (op != Icode_TAIL_CALL) {
1408 frame.savedStackTop = stackTop;
1409 frame.savedCallOp = op;
1410 }
1411 frame = calleeFrame;
1412 continue StateLoop;
1413 }
1414 }
1415
1416 if (fun instanceof NativeContinuation) {
1417 // Jump to the captured continuation
1418 ContinuationJump cjump;
1419 cjump = new ContinuationJump((NativeContinuation)fun, frame);
1420
1421 // continuation result is the first argument if any
1422 // of continuation call
1423 if (indexReg == 0) {
1424 cjump.result = undefined;
1425 } else {
1426 cjump.result = stack[stackTop + 2];
1427 cjump.resultDbl = sDbl[stackTop + 2];
1428 }
1429
1430 // Start the real unwind job
1431 throwable = cjump;
1432 break withoutExceptions;
1433 }
1434
1435 if (fun instanceof IdFunctionObject) {
1436 IdFunctionObject ifun = (IdFunctionObject)fun;
1437 if (NativeContinuation.isContinuationConstructor(ifun)) {
1438 frame.stack[stackTop] = captureContinuation(cx,
1439 frame.parentFrame, false);
1440 continue Loop;
1441 }
1442 // Bug 405654 -- make best effort to keep Function.apply and
1443 // Function.call within this interpreter loop invocation
1444 if (BaseFunction.isApplyOrCall(ifun)) {
1445 Callable applyCallable = ScriptRuntime.getCallable(funThisObj);
1446 if (applyCallable instanceof InterpretedFunction) {
1447 InterpretedFunction iApplyCallable = (InterpretedFunction)applyCallable;
1448 if (frame.fnOrScript.securityDomain == iApplyCallable.securityDomain) {
1449 frame = initFrameForApplyOrCall(cx, frame, indexReg,
1450 stack, sDbl, stackTop, op, calleeScope, ifun,
1451 iApplyCallable);
1452 continue StateLoop;
1453 }
1454 }
1455 }
1456 }
1457
1458 // Bug 447697 -- make best effort to keep __noSuchMethod__ within this
1459 // interpreter loop invocation
1460 if (fun instanceof NoSuchMethodShim) {
1461 // get the shim and the actual method
1462 NoSuchMethodShim noSuchMethodShim = (NoSuchMethodShim) fun;
1463 Callable noSuchMethodMethod = noSuchMethodShim.noSuchMethodMethod;
1464 // if the method is in fact an InterpretedFunction
1465 if (noSuchMethodMethod instanceof InterpretedFunction) {
1466 InterpretedFunction ifun = (InterpretedFunction) noSuchMethodMethod;
1467 if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
1468 frame = initFrameForNoSuchMethod(cx, frame, indexReg, stack, sDbl,
1469 stackTop, op, funThisObj, calleeScope,
1470 noSuchMethodShim, ifun);
1471 continue StateLoop;
1472 }
1473 }
1474 }
1475
1476 cx.lastInterpreterFrame = frame;
1477 frame.savedCallOp = op;
1478 frame.savedStackTop = stackTop;
1479 stack[stackTop] = fun.call(cx, calleeScope, funThisObj,
1480 getArgsArray(stack, sDbl, stackTop + 2, indexReg));
1481
1482 continue Loop;
1483 }
1484 case Token.NEW : {
1485 if (instructionCounting) {
1486 cx.instructionCount += INVOCATION_COST;
1487 }
1488 // stack change: function arg0 .. argN -> newResult
1489 // indexReg: number of arguments
1490 stackTop -= indexReg;
1491
1492 Object lhs = stack[stackTop];
1493 if (lhs instanceof InterpretedFunction) {
1494 InterpretedFunction f = (InterpretedFunction)lhs;
1495 if (frame.fnOrScript.securityDomain == f.securityDomain) {
1496 Scriptable newInstance = f.createObject(cx, frame.scope);
1497 CallFrame calleeFrame = new CallFrame();
1498 initFrame(cx, frame.scope, newInstance, stack, sDbl,
1499 stackTop + 1, indexReg, f, frame,
1500 calleeFrame);
1501
1502 stack[stackTop] = newInstance;
1503 frame.savedStackTop = stackTop;
1504 frame.savedCallOp = op;
1505 frame = calleeFrame;
1506 continue StateLoop;
1507 }
1508 }
1509 if (!(lhs instanceof Function)) {
1510 if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1511 throw ScriptRuntime.notFunctionError(lhs);
1512 }
1513 Function fun = (Function)lhs;
1514
1515 if (fun instanceof IdFunctionObject) {
1516 IdFunctionObject ifun = (IdFunctionObject)fun;
1517 if (NativeContinuation.isContinuationConstructor(ifun)) {
1518 frame.stack[stackTop] =
1519 captureContinuation(cx, frame.parentFrame, false);
1520 continue Loop;
1521 }
1522 }
1523
1524 Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg);
1525 stack[stackTop] = fun.construct(cx, frame.scope, outArgs);
1526 continue Loop;
1527 }
1528 case Token.TYPEOF : {
1529 Object lhs = stack[stackTop];
1530 if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1531 stack[stackTop] = ScriptRuntime.typeof(lhs);
1532 continue Loop;
1533 }
1534 case Icode_TYPEOFNAME :
1535 stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg);
1536 continue Loop;
1537 case Token.STRING :
1538 stack[++stackTop] = stringReg;
1539 continue Loop;
1540 case Icode_SHORTNUMBER :
1541 ++stackTop;
1542 stack[stackTop] = DBL_MRK;
1543 sDbl[stackTop] = getShort(iCode, frame.pc);
1544 frame.pc += 2;
1545 continue Loop;
1546 case Icode_INTNUMBER :
1547 ++stackTop;
1548 stack[stackTop] = DBL_MRK;
1549 sDbl[stackTop] = getInt(iCode, frame.pc);
1550 frame.pc += 4;
1551 continue Loop;
1552 case Token.NUMBER :
1553 ++stackTop;
1554 stack[stackTop] = DBL_MRK;
1555 sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg];
1556 continue Loop;
1557 case Token.NAME :
1558 stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg);
1559 continue Loop;
1560 case Icode_NAME_INC_DEC :
1561 stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg,
1562 cx, iCode[frame.pc]);
1563 ++frame.pc;
1564 continue Loop;
1565 case Icode_SETCONSTVAR1:
1566 indexReg = iCode[frame.pc++];
1567 // fallthrough
1568 case Token.SETCONSTVAR :
1569 stackTop = doSetConstVar(frame, stack, sDbl, stackTop, vars, varDbls,
1570 varAttributes, indexReg);
1571 continue Loop;
1572 case Icode_SETVAR1:
1573 indexReg = iCode[frame.pc++];
1574 // fallthrough
1575 case Token.SETVAR :
1576 stackTop = doSetVar(frame, stack, sDbl, stackTop, vars, varDbls,
1577 varAttributes, indexReg);
1578 continue Loop;
1579 case Icode_GETVAR1:
1580 indexReg = iCode[frame.pc++];
1581 // fallthrough
1582 case Token.GETVAR :
1583 stackTop = doGetVar(frame, stack, sDbl, stackTop, vars, varDbls, indexReg);
1584 continue Loop;
1585 case Icode_VAR_INC_DEC : {
1586 stackTop = doVarIncDec(cx, frame, stack, sDbl, stackTop,
1587 vars, varDbls, varAttributes, indexReg);
1588 continue Loop;
1589 }
1590 case Icode_ZERO :
1591 ++stackTop;
1592 stack[stackTop] = DBL_MRK;
1593 sDbl[stackTop] = 0;
1594 continue Loop;
1595 case Icode_ONE :
1596 ++stackTop;
1597 stack[stackTop] = DBL_MRK;
1598 sDbl[stackTop] = 1;
1599 continue Loop;
1600 case Token.NULL :
1601 stack[++stackTop] = null;
1602 continue Loop;
1603 case Token.THIS :
1604 stack[++stackTop] = frame.thisObj;
1605 continue Loop;
1606 case Token.THISFN :
1607 stack[++stackTop] = frame.fnOrScript;
1608 continue Loop;
1609 case Token.FALSE :
1610 stack[++stackTop] = Boolean.FALSE;
1611 continue Loop;
1612 case Token.TRUE :
1613 stack[++stackTop] = Boolean.TRUE;
1614 continue Loop;
1615 case Icode_UNDEF :
1616 stack[++stackTop] = undefined;
1617 continue Loop;
1618 case Token.ENTERWITH : {
1619 Object lhs = stack[stackTop];
1620 if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1621 --stackTop;
1622 frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope);
1623 continue Loop;
1624 }
1625 case Token.LEAVEWITH :
1626 frame.scope = ScriptRuntime.leaveWith(frame.scope);
1627 continue Loop;
1628 case Token.CATCH_SCOPE : {
1629 // stack top: exception object
1630 // stringReg: name of exception variable
1631 // indexReg: local for exception scope
1632 --stackTop;
1633 indexReg += frame.localShift;
1634
1635 boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0);
1636 Throwable caughtException = (Throwable)stack[stackTop + 1];
1637 Scriptable lastCatchScope;
1638 if (!afterFirstScope) {
1639 lastCatchScope = null;
1640 } else {
1641 lastCatchScope = (Scriptable)stack[indexReg];
1642 }
1643 stack[indexReg] = ScriptRuntime.newCatchScope(caughtException,
1644 lastCatchScope, stringReg,
1645 cx, frame.scope);
1646 ++frame.pc;
1647 continue Loop;
1648 }
1649 case Token.ENUM_INIT_KEYS :
1650 case Token.ENUM_INIT_VALUES :
1651 case Token.ENUM_INIT_ARRAY :
1652 case Token.ENUM_INIT_VALUES_IN_ORDER : {
1653 Object lhs = stack[stackTop];
1654 if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1655 --stackTop;
1656 indexReg += frame.localShift;
1657 int enumType = op == Token.ENUM_INIT_KEYS
1658 ? ScriptRuntime.ENUMERATE_KEYS :
1659 op == Token.ENUM_INIT_VALUES
1660 ? ScriptRuntime.ENUMERATE_VALUES :
1661 op == Token.ENUM_INIT_VALUES_IN_ORDER
1662 ? ScriptRuntime.ENUMERATE_VALUES_IN_ORDER :
1663 ScriptRuntime.ENUMERATE_ARRAY;
1664 stack[indexReg] = ScriptRuntime.enumInit(lhs, cx, frame.scope, enumType);
1665 continue Loop;
1666 }
1667 case Token.ENUM_NEXT :
1668 case Token.ENUM_ID : {
1669 indexReg += frame.localShift;
1670 Object val = stack[indexReg];
1671 ++stackTop;
1672 stack[stackTop] = (op == Token.ENUM_NEXT)
1673 ? (Object)ScriptRuntime.enumNext(val)
1674 : (Object)ScriptRuntime.enumId(val, cx);
1675 continue Loop;
1676 }
1677 case Token.REF_SPECIAL : {
1678 //stringReg: name of special property
1679 Object obj = stack[stackTop];
1680 if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1681 stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg,
1682 cx, frame.scope);
1683 continue Loop;
1684 }
1685 case Token.REF_MEMBER: {
1686 //indexReg: flags
1687 stackTop = doRefMember(cx, stack, sDbl, stackTop, indexReg);
1688 continue Loop;
1689 }
1690 case Token.REF_NS_MEMBER: {
1691 //indexReg: flags
1692 stackTop = doRefNsMember(cx, stack, sDbl, stackTop, indexReg);
1693 continue Loop;
1694 }
1695 case Token.REF_NAME: {
1696 //indexReg: flags
1697 Object name = stack[stackTop];
1698 if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1699 stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope,
1700 indexReg);
1701 continue Loop;
1702 }
1703 case Token.REF_NS_NAME: {
1704 //indexReg: flags
1705 stackTop = doRefNsName(cx, frame, stack, sDbl, stackTop, indexReg);
1706 continue Loop;
1707 }
1708 case Icode_SCOPE_LOAD :
1709 indexReg += frame.localShift;
1710 frame.scope = (Scriptable)stack[indexReg];
1711 continue Loop;
1712 case Icode_SCOPE_SAVE :
1713 indexReg += frame.localShift;
1714 stack[indexReg] = frame.scope;
1715 continue Loop;
1716 case Icode_CLOSURE_EXPR :
1717 InterpretedFunction fn = InterpretedFunction.createFunction(cx, frame.scope,
1718 frame.fnOrScript,
1719 indexReg);
1720 if (fn.idata.itsFunctionType == FunctionNode.ARROW_FUNCTION) {
1721 stack[++stackTop] = new ArrowFunction(cx, frame.scope, fn, frame.thisObj);
1722 } else {
1723 stack[++stackTop] = fn;
1724 }
1725 continue Loop;
1726 case Icode_CLOSURE_STMT :
1727 initFunction(cx, frame.scope, frame.fnOrScript, indexReg);
1728 continue Loop;
1729 case Token.REGEXP :
1730 Object re = frame.idata.itsRegExpLiterals[indexReg];
1731 stack[++stackTop] = ScriptRuntime.wrapRegExp(cx, frame.scope, re);
1732 continue Loop;
1733 case Icode_LITERAL_NEW :
1734 // indexReg: number of values in the literal
1735 ++stackTop;
1736 stack[stackTop] = new int[indexReg];
1737 ++stackTop;
1738 stack[stackTop] = new Object[indexReg];
1739 sDbl[stackTop] = 0;
1740 continue Loop;
1741 case Icode_LITERAL_SET : {
1742 Object value = stack[stackTop];
1743 if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1744 --stackTop;
1745 int i = (int)sDbl[stackTop];
1746 ((Object[])stack[stackTop])[i] = value;
1747 sDbl[stackTop] = i + 1;
1748 continue Loop;
1749 }
1750 case Icode_LITERAL_GETTER : {
1751 Object value = stack[stackTop];
1752 --stackTop;
1753 int i = (int)sDbl[stackTop];
1754 ((Object[])stack[stackTop])[i] = value;
1755 ((int[])stack[stackTop - 1])[i] = -1;
1756 sDbl[stackTop] = i + 1;
1757 continue Loop;
1758 }
1759 case Icode_LITERAL_SETTER : {
1760 Object value = stack[stackTop];
1761 --stackTop;
1762 int i = (int)sDbl[stackTop];
1763 ((Object[])stack[stackTop])[i] = value;
1764 ((int[])stack[stackTop - 1])[i] = +1;
1765 sDbl[stackTop] = i + 1;
1766 continue Loop;
1767 }
1768 case Token.ARRAYLIT :
1769 case Icode_SPARE_ARRAYLIT :
1770 case Token.OBJECTLIT : {
1771 Object[] data = (Object[])stack[stackTop];
1772 --stackTop;
1773 int[] getterSetters = (int[])stack[stackTop];
1774 Object val;
1775 if (op == Token.OBJECTLIT) {
1776 Object[] ids = (Object[])frame.idata.literalIds[indexReg];
1777 val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx,
1778 frame.scope);
1779 } else {
1780 int[] skipIndexces = null;
1781 if (op == Icode_SPARE_ARRAYLIT) {
1782 skipIndexces = (int[])frame.idata.literalIds[indexReg];
1783 }
1784 val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx,
1785 frame.scope);
1786 }
1787 stack[stackTop] = val;
1788 continue Loop;
1789 }
1790 case Icode_ENTERDQ : {
1791 Object lhs = stack[stackTop];
1792 if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1793 --stackTop;
1794 frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope);
1795 continue Loop;
1796 }
1797 case Icode_LEAVEDQ : {
1798 boolean valBln = stack_boolean(frame, stackTop);
1799 Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope);
1800 if (x != null) {
1801 stack[stackTop] = x;
1802 frame.scope = ScriptRuntime.leaveDotQuery(frame.scope);
1803 frame.pc += 2;
1804 continue Loop;
1805 }
1806 // reset stack and PC to code after ENTERDQ
1807 --stackTop;
1808 break jumplessRun;
1809 }
1810 case Token.DEFAULTNAMESPACE : {
1811 Object value = stack[stackTop];
1812 if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
1813 stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx);
1814 continue Loop;
1815 }
1816 case Token.ESCXMLATTR : {
1817 Object value = stack[stackTop];
1818 if (value != DBL_MRK) {
1819 stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx);
1820 }
1821 continue Loop;
1822 }
1823 case Token.ESCXMLTEXT : {
1824 Object value = stack[stackTop];
1825 if (value != DBL_MRK) {
1826 stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx);
1827 }
1828 continue Loop;
1829 }
1830 case Icode_DEBUGGER:
1831 if (frame.debuggerFrame != null) {
1832 frame.debuggerFrame.onDebuggerStatement(cx);
1833 }
1834 continue Loop;
1835 case Icode_LINE :
1836 frame.pcSourceLineStart = frame.pc;
1837 if (frame.debuggerFrame != null) {
1838 int line = getIndex(iCode, frame.pc);
1839 frame.debuggerFrame.onLineChange(cx, line);
1840 }
1841 frame.pc += 2;
1842 continue Loop;
1843 case Icode_REG_IND_C0:
1844 indexReg = 0;
1845 continue Loop;
1846 case Icode_REG_IND_C1:
1847 indexReg = 1;
1848 continue Loop;
1849 case Icode_REG_IND_C2:
1850 indexReg = 2;
1851 continue Loop;
1852 case Icode_REG_IND_C3:
1853 indexReg = 3;
1854 continue Loop;
1855 case Icode_REG_IND_C4:
1856 indexReg = 4;
1857 continue Loop;
1858 case Icode_REG_IND_C5:
1859 indexReg = 5;
1860 continue Loop;
1861 case Icode_REG_IND1:
1862 indexReg = 0xFF & iCode[frame.pc];
1863 ++frame.pc;
1864 continue Loop;
1865 case Icode_REG_IND2:
1866 indexReg = getIndex(iCode, frame.pc);
1867 frame.pc += 2;
1868 continue Loop;
1869 case Icode_REG_IND4:
1870 indexReg = getInt(iCode, frame.pc);
1871 frame.pc += 4;
1872 continue Loop;
1873 case Icode_REG_STR_C0:
1874 stringReg = strings[0];
1875 continue Loop;
1876 case Icode_REG_STR_C1:
1877 stringReg = strings[1];
1878 continue Loop;
1879 case Icode_REG_STR_C2:
1880 stringReg = strings[2];
1881 continue Loop;
1882 case Icode_REG_STR_C3:
1883 stringReg = strings[3];
1884 continue Loop;
1885 case Icode_REG_STR1:
1886 stringReg = strings[0xFF & iCode[frame.pc]];
1887 ++frame.pc;
1888 continue Loop;
1889 case Icode_REG_STR2:
1890 stringReg = strings[getIndex(iCode, frame.pc)];
1891 frame.pc += 2;
1892 continue Loop;
1893 case Icode_REG_STR4:
1894 stringReg = strings[getInt(iCode, frame.pc)];
1895 frame.pc += 4;
1896 continue Loop;
1897 default :
1898 dumpICode(frame.idata);
1899 throw new RuntimeException("Unknown icode : " + op
1900 + " @ pc : " + (frame.pc-1));
1901 } // end of interpreter switch
1902
1903 } // end of jumplessRun label block
1904
1905 // This should be reachable only for jump implementation
1906 // when pc points to encoded target offset
1907 if (instructionCounting) {
1908 addInstructionCount(cx, frame, 2);
1909 }
1910 int offset = getShort(iCode, frame.pc);
1911 if (offset != 0) {
1912 // -1 accounts for pc pointing to jump opcode + 1
1913 frame.pc += offset - 1;
1914 } else {
1915 frame.pc = frame.idata.longJumps.
1916 getExistingInt(frame.pc);
1917 }
1918 if (instructionCounting) {
1919 frame.pcPrevBranch = frame.pc;
1920 }
1921 continue Loop;
1922
1923 } // end of Loop: for
1924
1925 exitFrame(cx, frame, null);
1926 interpreterResult = frame.result;
1927 interpreterResultDbl = frame.resultDbl;
1928 if (frame.parentFrame != null) {
1929 frame = frame.parentFrame;
1930 if (frame.frozen) {
1931 frame = frame.cloneFrozen();
1932 }
1933 setCallResult(
1934 frame, interpreterResult, interpreterResultDbl);
1935 interpreterResult = null; // Help GC
1936 continue StateLoop;
1937 }
1938 break StateLoop;
1939
1940 } // end of interpreter withoutExceptions: try
1941 catch (Throwable ex) {
1942 if (throwable != null) {
1943 // This is serious bug and it is better to track it ASAP
1944 ex.printStackTrace(System.err);
1945 throw new IllegalStateException();
1946 }
1947 throwable = ex;
1948 }
1949
1950 // This should be reachable only after above catch or from
1951 // finally when it needs to propagate exception or from
1952 // explicit throw
1953 if (throwable == null) Kit.codeBug();
1954
1955 // Exception type
1956 final int EX_CATCH_STATE = 2; // Can execute JS catch
1957 final int EX_FINALLY_STATE = 1; // Can execute JS finally
1958 final int EX_NO_JS_STATE = 0; // Terminate JS execution
1959
1960 int exState;
1961 ContinuationJump cjump = null;
1962
1963 if (generatorState != null &&
1964 generatorState.operation == NativeGenerator.GENERATOR_CLOSE &&
1965 throwable == generatorState.value)
1966 {
1967 exState = EX_FINALLY_STATE;
1968 } else if (throwable instanceof JavaScriptException) {
1969 exState = EX_CATCH_STATE;
1970 } else if (throwable instanceof EcmaError) {
1971 // an offical ECMA error object,
1972 exState = EX_CATCH_STATE;
1973 } else if (throwable instanceof EvaluatorException) {
1974 exState = EX_CATCH_STATE;
1975 } else if (throwable instanceof ContinuationPending) {
1976 exState = EX_NO_JS_STATE;
1977 } else if (throwable instanceof RuntimeException) {
1978 exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
1979 ? EX_CATCH_STATE
1980 : EX_FINALLY_STATE;
1981 } else if (throwable instanceof Error) {
1982 exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
1983 ? EX_CATCH_STATE
1984 : EX_NO_JS_STATE;
1985 } else if (throwable instanceof ContinuationJump) {
1986 // It must be ContinuationJump
1987 exState = EX_FINALLY_STATE;
1988 cjump = (ContinuationJump)throwable;
1989 } else {
1990 exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
1991 ? EX_CATCH_STATE
1992 : EX_FINALLY_STATE;
1993 }
1994
1995 if (instructionCounting) {
1996 try {
1997 addInstructionCount(cx, frame, EXCEPTION_COST);
1998 } catch (RuntimeException ex) {
1999 throwable = ex;
2000 exState = EX_FINALLY_STATE;
2001 } catch (Error ex) {
2002 // Error from instruction counting
2003 // => unconditionally terminate JS
2004 throwable = ex;
2005 cjump = null;
2006 exState = EX_NO_JS_STATE;
2007 }
2008 }
2009 if (frame.debuggerFrame != null
2010 && throwable instanceof RuntimeException)
2011 {
2012 // Call debugger only for RuntimeException
2013 RuntimeException rex = (RuntimeException)throwable;
2014 try {
2015 frame.debuggerFrame.onExceptionThrown(cx, rex);
2016 } catch (Throwable ex) {
2017 // Any exception from debugger
2018 // => unconditionally terminate JS
2019 throwable = ex;
2020 cjump = null;
2021 exState = EX_NO_JS_STATE;
2022 }
2023 }
2024
2025 for (;;) {
2026 if (exState != EX_NO_JS_STATE) {
2027 boolean onlyFinally = (exState != EX_CATCH_STATE);
2028 indexReg = getExceptionHandler(frame, onlyFinally);
2029 if (indexReg >= 0) {
2030 // We caught an exception, restart the loop
2031 // with exception pending the processing at the loop
2032 // start
2033 continue StateLoop;
2034 }
2035 }
2036 // No allowed exception handlers in this frame, unwind
2037 // to parent and try to look there
2038
2039 exitFrame(cx, frame, throwable);
2040
2041 frame = frame.parentFrame;
2042 if (frame == null) { break; }
2043 if (cjump != null && cjump.branchFrame == frame) {
2044 // Continuation branch point was hit,
2045 // restart the state loop to reenter continuation
2046 indexReg = -1;
2047 continue StateLoop;
2048 }
2049 }
2050
2051 // No more frames, rethrow the exception or deal with continuation
2052 if (cjump != null) {
2053 if (cjump.branchFrame != null) {
2054 // The above loop should locate the top frame
2055 Kit.codeBug();
2056 }
2057 if (cjump.capturedFrame != null) {
2058 // Restarting detached continuation
2059 indexReg = -1;
2060 continue StateLoop;
2061 }
2062 // Return continuation result to the caller
2063 interpreterResult = cjump.result;
2064 interpreterResultDbl = cjump.resultDbl;
2065 throwable = null;
2066 }
2067 break StateLoop;
2068
2069 } // end of StateLoop: for(;;)
2070
2071 // Do cleanups/restorations before the final return or throw
2072
2073 if (cx.previousInterpreterInvocations != null
2074 && cx.previousInterpreterInvocations.size() != 0)
2075 {
2076 cx.lastInterpreterFrame
2077 = cx.previousInterpreterInvocations.pop();
2078 } else {
2079 // It was the last interpreter frame on the stack
2080 cx.lastInterpreterFrame = null;
2081 // Force GC of the value cx.previousInterpreterInvocations
2082 cx.previousInterpreterInvocations = null;
2083 }
2084
2085 if (throwable != null) {
2086 if (throwable instanceof RuntimeException) {
2087 throw (RuntimeException)throwable;
2088 } else {
2089 // Must be instance of Error or code bug
2090 throw (Error)throwable;
2091 }
2092 }
2093
2094 return (interpreterResult != DBL_MRK)
2095 ? interpreterResult
2096 : ScriptRuntime.wrapNumber(interpreterResultDbl);
2097 }
2098
2099 private static int doInOrInstanceof(Context cx, int op, Object[] stack,
2100 double[] sDbl, int stackTop) {
2101 Object rhs = stack[stackTop];
2102 if (rhs == DOUBLE_MARK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2103 --stackTop;
2104 Object lhs = stack[stackTop];
2105 if (lhs == DOUBLE_MARK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2106 boolean valBln;
2107 if (op == Token.IN) {
2108 valBln = ScriptRuntime.in(lhs, rhs, cx);
2109 } else {
2110 valBln = ScriptRuntime.instanceOf(lhs, rhs, cx);
2111 }
2112 stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
2113 return stackTop;
2114 }
2115
2116 private static int doCompare(CallFrame frame, int op, Object[] stack,
2117 double[] sDbl, int stackTop) {
2118 --stackTop;
2119 Object rhs = stack[stackTop + 1];
2120 Object lhs = stack[stackTop];
2121 boolean valBln;
2122 object_compare:
2123 {
2124 number_compare:
2125 {
2126 double rDbl, lDbl;
2127 if (rhs == DOUBLE_MARK) {
2128 rDbl = sDbl[stackTop + 1];
2129 lDbl = stack_double(frame, stackTop);
2130 } else if (lhs == DOUBLE_MARK) {
2131 rDbl = ScriptRuntime.toNumber(rhs);
2132 lDbl = sDbl[stackTop];
2133 } else {
2134 break number_compare;
2135 }
2136 switch (op) {
2137 case Token.GE:
2138 valBln = (lDbl >= rDbl);
2139 break object_compare;
2140 case Token.LE:
2141 valBln = (lDbl <= rDbl);
2142 break object_compare;
2143 case Token.GT:
2144 valBln = (lDbl > rDbl);
2145 break object_compare;
2146 case Token.LT:
2147 valBln = (lDbl < rDbl);
2148 break object_compare;
2149 default:
2150 throw Kit.codeBug();
2151 }
2152 }
2153 switch (op) {
2154 case Token.GE:
2155 valBln = ScriptRuntime.cmp_LE(rhs, lhs);
2156 break;
2157 case Token.LE:
2158 valBln = ScriptRuntime.cmp_LE(lhs, rhs);
2159 break;
2160 case Token.GT:
2161 valBln = ScriptRuntime.cmp_LT(rhs, lhs);
2162 break;
2163 case Token.LT:
2164 valBln = ScriptRuntime.cmp_LT(lhs, rhs);
2165 break;
2166 default:
2167 throw Kit.codeBug();
2168 }
2169 }
2170 stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
2171 return stackTop;
2172 }
2173
2174 private static int doBitOp(CallFrame frame, int op, Object[] stack,
2175 double[] sDbl, int stackTop) {
2176 int lIntValue = stack_int32(frame, stackTop - 1);
2177 int rIntValue = stack_int32(frame, stackTop);
2178 stack[--stackTop] = DOUBLE_MARK;
2179 switch (op) {
2180 case Token.BITAND:
2181 lIntValue &= rIntValue;
2182 break;
2183 case Token.BITOR:
2184 lIntValue |= rIntValue;
2185 break;
2186 case Token.BITXOR:
2187 lIntValue ^= rIntValue;
2188 break;
2189 case Token.LSH:
2190 lIntValue <<= rIntValue;
2191 break;
2192 case Token.RSH:
2193 lIntValue >>= rIntValue;
2194 break;
2195 }
2196 sDbl[stackTop] = lIntValue;
2197 return stackTop;
2198 }
2199
2200 private static int doDelName(Context cx, CallFrame frame, int op,
2201 Object[] stack, double[] sDbl, int stackTop) {
2202 Object rhs = stack[stackTop];
2203 if (rhs == DOUBLE_MARK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2204 --stackTop;
2205 Object lhs = stack[stackTop];
2206 if (lhs == DOUBLE_MARK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2207 stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx, frame.scope,
2208 op == Icode_DELNAME);
2209 return stackTop;
2210 }
2211
2212 private static int doGetElem(Context cx, CallFrame frame, Object[] stack,
2213 double[] sDbl, int stackTop) {
2214 --stackTop;
2215 Object lhs = stack[stackTop];
2216 if (lhs == DOUBLE_MARK) {
2217 lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2218 }
2219 Object value;
2220 Object id = stack[stackTop + 1];
2221 if (id != DOUBLE_MARK) {
2222 value = ScriptRuntime.getObjectElem(lhs, id, cx, frame.scope);
2223 } else {
2224 double d = sDbl[stackTop + 1];
2225 value = ScriptRuntime.getObjectIndex(lhs, d, cx, frame.scope);
2226 }
2227 stack[stackTop] = value;
2228 return stackTop;
2229 }
2230
2231 private static int doSetElem(Context cx, CallFrame frame, Object[] stack,
2232 double[] sDbl, int stackTop) {
2233 stackTop -= 2;
2234 Object rhs = stack[stackTop + 2];
2235 if (rhs == DOUBLE_MARK) {
2236 rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]);
2237 }
2238 Object lhs = stack[stackTop];
2239 if (lhs == DOUBLE_MARK) {
2240 lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2241 }
2242 Object value;
2243 Object id = stack[stackTop + 1];
2244 if (id != DOUBLE_MARK) {
2245 value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx, frame.scope);
2246 } else {
2247 double d = sDbl[stackTop + 1];
2248 value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx, frame.scope);
2249 }
2250 stack[stackTop] = value;
2251 return stackTop;
2252 }
2253
2254 private static int doElemIncDec(Context cx, CallFrame frame, byte[] iCode,
2255 Object[] stack, double[] sDbl, int stackTop) {
2256 Object rhs = stack[stackTop];
2257 if (rhs == DOUBLE_MARK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2258 --stackTop;
2259 Object lhs = stack[stackTop];
2260 if (lhs == DOUBLE_MARK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2261 stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx, frame.scope,
2262 iCode[frame.pc]);
2263 ++frame.pc;
2264 return stackTop;
2265 }
2266
2267 private static int doCallSpecial(Context cx, CallFrame frame,
2268 Object[] stack, double[] sDbl,
2269 int stackTop, byte[] iCode,
2270 int indexReg) {
2271 int callType = iCode[frame.pc] & 0xFF;
2272 boolean isNew = (iCode[frame.pc + 1] != 0);
2273 int sourceLine = getIndex(iCode, frame.pc + 2);
2274
2275 // indexReg: number of arguments
2276 if (isNew) {
2277 // stack change: function arg0 .. argN -> newResult
2278 stackTop -= indexReg;
2279
2280 Object function = stack[stackTop];
2281 if (function == DOUBLE_MARK)
2282 function = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2283 Object[] outArgs = getArgsArray(
2284 stack, sDbl, stackTop + 1, indexReg);
2285 stack[stackTop] = ScriptRuntime.newSpecial(
2286 cx, function, outArgs, frame.scope, callType);
2287 } else {
2288 // stack change: function thisObj arg0 .. argN -> result
2289 stackTop -= 1 + indexReg;
2290
2291 // Call code generation ensure that stack here
2292 // is ... Callable Scriptable
2293 Scriptable functionThis = (Scriptable)stack[stackTop + 1];
2294 Callable function = (Callable)stack[stackTop];
2295 Object[] outArgs = getArgsArray(
2296 stack, sDbl, stackTop + 2, indexReg);
2297 stack[stackTop] = ScriptRuntime.callSpecial(
2298 cx, function, functionThis, outArgs,
2299 frame.scope, frame.thisObj, callType,
2300 frame.idata.itsSourceFile, sourceLine);
2301 }
2302 frame.pc += 4;
2303 return stackTop;
2304 }
2305
2306 private static int doSetConstVar(CallFrame frame, Object[] stack,
2307 double[] sDbl, int stackTop,
2308 Object[] vars, double[] varDbls,
2309 int[] varAttributes, int indexReg) {
2310 if (!frame.useActivation) {
2311 if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
2312 throw Context.reportRuntimeError1("msg.var.redecl",
2313 frame.idata.argNames[indexReg]);
2314 }
2315 if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST)
2316 != 0)
2317 {
2318 vars[indexReg] = stack[stackTop];
2319 varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST;
2320 varDbls[indexReg] = sDbl[stackTop];
2321 }
2322 } else {
2323 Object val = stack[stackTop];
2324 if (val == DOUBLE_MARK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2325 String stringReg = frame.idata.argNames[indexReg];
2326 if (frame.scope instanceof ConstProperties) {
2327 ConstProperties cp = (ConstProperties)frame.scope;
2328 cp.putConst(stringReg, frame.scope, val);
2329 } else
2330 throw Kit.codeBug();
2331 }
2332 return stackTop;
2333 }
2334
2335 private static int doSetVar(CallFrame frame, Object[] stack,
2336 double[] sDbl, int stackTop,
2337 Object[] vars, double[] varDbls,
2338 int[] varAttributes, int indexReg) {
2339 if (!frame.useActivation) {
2340 if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
2341 vars[indexReg] = stack[stackTop];
2342 varDbls[indexReg] = sDbl[stackTop];
2343 }
2344 } else {
2345 Object val = stack[stackTop];
2346 if (val == DOUBLE_MARK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2347 String stringReg = frame.idata.argNames[indexReg];
2348 frame.scope.put(stringReg, frame.scope, val);
2349 }
2350 return stackTop;
2351 }
2352
2353 private static int doGetVar(CallFrame frame, Object[] stack,
2354 double[] sDbl, int stackTop,
2355 Object[] vars, double[] varDbls,
2356 int indexReg) {
2357 ++stackTop;
2358 if (!frame.useActivation) {
2359 stack[stackTop] = vars[indexReg];
2360 sDbl[stackTop] = varDbls[indexReg];
2361 } else {
2362 String stringReg = frame.idata.argNames[indexReg];
2363 stack[stackTop] = frame.scope.get(stringReg, frame.scope);
2364 }
2365 return stackTop;
2366 }
2367
2368 private static int doVarIncDec(Context cx, CallFrame frame,
2369 Object[] stack, double[] sDbl,
2370 int stackTop, Object[] vars,
2371 double[] varDbls, int[] varAttributes,
2372 int indexReg) {
2373 // indexReg : varindex
2374 ++stackTop;
2375 int incrDecrMask = frame.idata.itsICode[frame.pc];
2376 if (!frame.useActivation) {
2377 Object varValue = vars[indexReg];
2378 double d;
2379 if (varValue == DOUBLE_MARK) {
2380 d = varDbls[indexReg];
2381 } else {
2382 d = ScriptRuntime.toNumber(varValue);
2383 }
2384 double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0)
2385 ? d + 1.0 : d - 1.0;
2386 boolean post = ((incrDecrMask & Node.POST_FLAG) != 0);
2387 if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
2388 if (varValue != DOUBLE_MARK) {
2389 vars[indexReg] = DOUBLE_MARK;
2390 }
2391 varDbls[indexReg] = d2;
2392 stack[stackTop] = DOUBLE_MARK;
2393 sDbl[stackTop] = post ? d : d2;
2394 } else {
2395 if (post && varValue != DOUBLE_MARK) {
2396 stack[stackTop] = varValue;
2397 } else {
2398 stack[stackTop] = DOUBLE_MARK;
2399 sDbl[stackTop] = post ? d : d2;
2400 }
2401 }
2402 } else {
2403 String varName = frame.idata.argNames[indexReg];
2404 stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName,
2405 cx, incrDecrMask);
2406 }
2407 ++frame.pc;
2408 return stackTop;
2409 }
2410
2411 private static int doRefMember(Context cx, Object[] stack, double[] sDbl,
2412 int stackTop, int flags) {
2413 Object elem = stack[stackTop];
2414 if (elem == DOUBLE_MARK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2415 --stackTop;
2416 Object obj = stack[stackTop];
2417 if (obj == DOUBLE_MARK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2418 stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, flags);
2419 return stackTop;
2420 }
2421
2422 private static int doRefNsMember(Context cx, Object[] stack, double[] sDbl,
2423 int stackTop, int flags) {
2424 Object elem = stack[stackTop];
2425 if (elem == DOUBLE_MARK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2426 --stackTop;
2427 Object ns = stack[stackTop];
2428 if (ns == DOUBLE_MARK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2429 --stackTop;
2430 Object obj = stack[stackTop];
2431 if (obj == DOUBLE_MARK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2432 stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, flags);
2433 return stackTop;
2434 }
2435
2436 private static int doRefNsName(Context cx, CallFrame frame,
2437 Object[] stack, double[] sDbl,
2438 int stackTop, int flags) {
2439 Object name = stack[stackTop];
2440 if (name == DOUBLE_MARK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2441 --stackTop;
2442 Object ns = stack[stackTop];
2443 if (ns == DOUBLE_MARK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
2444 stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope, flags);
2445 return stackTop;
2446 }
2447
2448 /**
2449 * Call __noSuchMethod__.
2450 */
2451 private static CallFrame initFrameForNoSuchMethod(Context cx,
2452 CallFrame frame, int indexReg, Object[] stack, double[] sDbl,
2453 int stackTop, int op, Scriptable funThisObj, Scriptable calleeScope,
2454 NoSuchMethodShim noSuchMethodShim, InterpretedFunction ifun)
2455 {
2456 // create an args array from the stack
2457 Object[] argsArray = null;
2458 // exactly like getArgsArray except that the first argument
2459 // is the method name from the shim
2460 int shift = stackTop + 2;
2461 Object[] elements = new Object[indexReg];
2462 for (int i=0; i < indexReg; ++i, ++shift) {
2463 Object val = stack[shift];
2464 if (val == DOUBLE_MARK) {
2465 val = ScriptRuntime.wrapNumber(sDbl[shift]);
2466 }
2467 elements[i] = val;
2468 }
2469 argsArray = new Object[2];
2470 argsArray[0] = noSuchMethodShim.methodName;
2471 argsArray[1] = cx.newArray(calleeScope, elements);
2472
2473 // exactly the same as if it's a regular InterpretedFunction
2474 CallFrame callParentFrame = frame;
2475 CallFrame calleeFrame = new CallFrame();
2476 if (op == Icode_TAIL_CALL) {
2477 callParentFrame = frame.parentFrame;
2478 exitFrame(cx, frame, null);
2479 }
2480 // init the frame with the underlying method with the
2481 // adjusted args array and shim's function
2482 initFrame(cx, calleeScope, funThisObj, argsArray, null,
2483 0, 2, ifun, callParentFrame, calleeFrame);
2484 if (op != Icode_TAIL_CALL) {
2485 frame.savedStackTop = stackTop;
2486 frame.savedCallOp = op;
2487 }
2488 return calleeFrame;
2489 }
2490
2491 private static boolean doEquals(Object[] stack, double[] sDbl,
2492 int stackTop) {
2493 Object rhs = stack[stackTop + 1];
2494 Object lhs = stack[stackTop];
2495 if (rhs == DOUBLE_MARK) {
2496 if (lhs == DOUBLE_MARK) {
2497 return (sDbl[stackTop] == sDbl[stackTop + 1]);
2498 } else {
2499 return ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs);
2500 }
2501 } else {
2502 if (lhs == DOUBLE_MARK) {
2503 return ScriptRuntime.eqNumber(sDbl[stackTop], rhs);
2504 } else {
2505 return ScriptRuntime.eq(lhs, rhs);
2506 }
2507 }
2508 }
2509
2510 private static boolean doShallowEquals(Object[] stack, double[] sDbl,
2511 int stackTop)
2512 {
2513 Object rhs = stack[stackTop + 1];
2514 Object lhs = stack[stackTop];
2515 final Object DBL_MRK = DOUBLE_MARK;
2516 double rdbl, ldbl;
2517 if (rhs == DBL_MRK) {
2518 rdbl = sDbl[stackTop + 1];
2519 if (lhs == DBL_MRK) {
2520 ldbl = sDbl[stackTop];
2521 } else if (lhs instanceof Number) {
2522 ldbl = ((Number)lhs).doubleValue();
2523 } else {
2524 return false;
2525 }
2526 } else if (lhs == DBL_MRK) {
2527 ldbl = sDbl[stackTop];
2528 if (rhs instanceof Number) {
2529 rdbl = ((Number)rhs).doubleValue();
2530 } else {
2531 return false;
2532 }
2533 } else {
2534 return ScriptRuntime.shallowEq(lhs, rhs);
2535 }
2536 return (ldbl == rdbl);
2537 }
2538
2539 private static CallFrame processThrowable(Context cx, Object throwable,
2540 CallFrame frame, int indexReg,
2541 boolean instructionCounting)
2542 {
2543 // Recovering from exception, indexReg contains
2544 // the index of handler
2545
2546 if (indexReg >= 0) {
2547 // Normal exception handler, transfer
2548 // control appropriately
2549
2550 if (frame.frozen) {
2551 // XXX Deal with exceptios!!!
2552 frame = frame.cloneFrozen();
2553 }
2554
2555 int[] table = frame.idata.itsExceptionTable;
2556
2557 frame.pc = table[indexReg + EXCEPTION_HANDLER_SLOT];
2558 if (instructionCounting) {
2559 frame.pcPrevBranch = frame.pc;
2560 }
2561
2562 frame.savedStackTop = frame.emptyStackTop;
2563 int scopeLocal = frame.localShift
2564 + table[indexReg
2565 + EXCEPTION_SCOPE_SLOT];
2566 int exLocal = frame.localShift
2567 + table[indexReg
2568 + EXCEPTION_LOCAL_SLOT];
2569 frame.scope = (Scriptable)frame.stack[scopeLocal];
2570 frame.stack[exLocal] = throwable;
2571
2572 throwable = null;
2573 } else {
2574 // Continuation restoration
2575 ContinuationJump cjump = (ContinuationJump)throwable;
2576
2577 // Clear throwable to indicate that exceptions are OK
2578 throwable = null;
2579
2580 if (cjump.branchFrame != frame) Kit.codeBug();
2581
2582 // Check that we have at least one frozen frame
2583 // in the case of detached continuation restoration:
2584 // unwind code ensure that
2585 if (cjump.capturedFrame == null) Kit.codeBug();
2586
2587 // Need to rewind branchFrame, capturedFrame
2588 // and all frames in between
2589 int rewindCount = cjump.capturedFrame.frameIndex + 1;
2590 if (cjump.branchFrame != null) {
2591 rewindCount -= cjump.branchFrame.frameIndex;
2592 }
2593
2594 int enterCount = 0;
2595 CallFrame[] enterFrames = null;
2596
2597 CallFrame x = cjump.capturedFrame;
2598 for (int i = 0; i != rewindCount; ++i) {
2599 if (!x.frozen) Kit.codeBug();
2600 if (isFrameEnterExitRequired(x)) {
2601 if (enterFrames == null) {
2602 // Allocate enough space to store the rest
2603 // of rewind frames in case all of them
2604 // would require to enter
2605 enterFrames = new CallFrame[rewindCount
2606 - i];
2607 }
2608 enterFrames[enterCount] = x;
2609 ++enterCount;
2610 }
2611 x = x.parentFrame;
2612 }
2613
2614 while (enterCount != 0) {
2615 // execute enter: walk enterFrames in the reverse
2616 // order since they were stored starting from
2617 // the capturedFrame, not branchFrame
2618 --enterCount;
2619 x = enterFrames[enterCount];
2620 enterFrame(cx, x, ScriptRuntime.emptyArgs, true);
2621 }
2622
2623 // Continuation jump is almost done: capturedFrame
2624 // points to the call to the function that captured
2625 // continuation, so clone capturedFrame and
2626 // emulate return that function with the suplied result
2627 frame = cjump.capturedFrame.cloneFrozen();
2628 setCallResult(frame, cjump.result, cjump.resultDbl);
2629 // restart the execution
2630 }
2631 frame.throwable = throwable;
2632 return frame;
2633 }
2634
2635 private static Object freezeGenerator(Context cx, CallFrame frame,
2636 int stackTop,
2637 GeneratorState generatorState)
2638 {
2639 if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) {
2640 // Error: no yields when generator is closing
2641 throw ScriptRuntime.typeError0("msg.yield.closing");
2642 }
2643 // return to our caller (which should be a method of NativeGenerator)
2644 frame.frozen = true;
2645 frame.result = frame.stack[stackTop];
2646 frame.resultDbl = frame.sDbl[stackTop];
2647 frame.savedStackTop = stackTop;
2648 frame.pc--; // we want to come back here when we resume
2649 ScriptRuntime.exitActivationFunction(cx);
2650 return (frame.result != DOUBLE_MARK)
2651 ? frame.result
2652 : ScriptRuntime.wrapNumber(frame.resultDbl);
2653 }
2654
2655 private static Object thawGenerator(CallFrame frame, int stackTop,
2656 GeneratorState generatorState, int op)
2657 {
2658 // we are resuming execution
2659 frame.frozen = false;
2660 int sourceLine = getIndex(frame.idata.itsICode, frame.pc);
2661 frame.pc += 2; // skip line number data
2662 if (generatorState.operation == NativeGenerator.GENERATOR_THROW) {
2663 // processing a call to <generator>.throw(exception): must
2664 // act as if exception was thrown from resumption point
2665 return new JavaScriptException(generatorState.value,
2666 frame.idata.itsSourceFile,
2667 sourceLine);
2668 }
2669 if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) {
2670 return generatorState.value;
2671 }
2672 if (generatorState.operation != NativeGenerator.GENERATOR_SEND)
2673 throw Kit.codeBug();
2674 if (op == Token.YIELD)
2675 frame.stack[stackTop] = generatorState.value;
2676 return Scriptable.NOT_FOUND;
2677 }
2678
2679 private static CallFrame initFrameForApplyOrCall(Context cx, CallFrame frame,
2680 int indexReg, Object[] stack, double[] sDbl, int stackTop, int op,
2681 Scriptable calleeScope, IdFunctionObject ifun,
2682 InterpretedFunction iApplyCallable)
2683 {
2684 Scriptable applyThis;
2685 if (indexReg != 0) {
2686 Object obj = stack[stackTop + 2];
2687 if (obj == DOUBLE_MARK)
2688 obj = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]);
2689 applyThis = ScriptRuntime.toObjectOrNull(cx, obj, frame.scope);
2690 }
2691 else {
2692 applyThis = null;
2693 }
2694 if (applyThis == null) {
2695 // This covers the case of args[0] == (null|undefined) as well.
2696 applyThis = ScriptRuntime.getTopCallScope(cx);
2697 }
2698 if(op == Icode_TAIL_CALL) {
2699 exitFrame(cx, frame, null);
2700 frame = frame.parentFrame;
2701 }
2702 else {
2703 frame.savedStackTop = stackTop;
2704 frame.savedCallOp = op;
2705 }
2706 CallFrame calleeFrame = new CallFrame();
2707 if(BaseFunction.isApply(ifun)) {
2708 Object[] callArgs = indexReg < 2 ? ScriptRuntime.emptyArgs :
2709 ScriptRuntime.getApplyArguments(cx, stack[stackTop + 3]);
2710 initFrame(cx, calleeScope, applyThis, callArgs, null, 0,
2711 callArgs.length, iApplyCallable, frame, calleeFrame);
2712 }
2713 else {
2714 // Shift args left
2715 for(int i = 1; i < indexReg; ++i) {
2716 stack[stackTop + 1 + i] = stack[stackTop + 2 + i];
2717 sDbl[stackTop + 1 + i] = sDbl[stackTop + 2 + i];
2718 }
2719 int argCount = indexReg < 2 ? 0 : indexReg - 1;
2720 initFrame(cx, calleeScope, applyThis, stack, sDbl, stackTop + 2,
2721 argCount, iApplyCallable, frame, calleeFrame);
2722 }
2723
2724 frame = calleeFrame;
2725 return frame;
2726 }
2727
2728 private static void initFrame(Context cx, Scriptable callerScope,
2729 Scriptable thisObj,
2730 Object[] args, double[] argsDbl,
2731 int argShift, int argCount,
2732 InterpretedFunction fnOrScript,
2733 CallFrame parentFrame, CallFrame frame)
2734 {
2735 InterpreterData idata = fnOrScript.idata;
2736
2737 boolean useActivation = idata.itsNeedsActivation;
2738 DebugFrame debuggerFrame = null;
2739 if (cx.debugger != null) {
2740 debuggerFrame = cx.debugger.getFrame(cx, idata);
2741 if (debuggerFrame != null) {
2742 useActivation = true;
2743 }
2744 }
2745
2746 if (useActivation) {
2747 // Copy args to new array to pass to enterActivationFunction
2748 // or debuggerFrame.onEnter
2749 if (argsDbl != null) {
2750 args = getArgsArray(args, argsDbl, argShift, argCount);
2751 }
2752 argShift = 0;
2753 argsDbl = null;
2754 }
2755
2756 Scriptable scope;
2757 if (idata.itsFunctionType != 0) {
2758 scope = fnOrScript.getParentScope();
2759
2760 if (useActivation) {
2761 if (idata.itsFunctionType == FunctionNode.ARROW_FUNCTION) {
2762 scope = ScriptRuntime.createArrowFunctionActivation(fnOrScript, scope, args, idata.isStrict);
2763 } else {
2764 scope = ScriptRuntime.createFunctionActivation(fnOrScript, scope, args, idata.isStrict);
2765 }
2766 }
2767 } else {
2768 scope = callerScope;
2769 ScriptRuntime.initScript(fnOrScript, thisObj, cx, scope,
2770 fnOrScript.idata.evalScriptFlag);
2771 }
2772
2773 if (idata.itsNestedFunctions != null) {
2774 if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
2775 Kit.codeBug();
2776 for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
2777 InterpreterData fdata = idata.itsNestedFunctions[i];
2778 if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) {
2779 initFunction(cx, scope, fnOrScript, i);
2780 }
2781 }
2782 }
2783
2784 // Initialize args, vars, locals and stack
2785
2786 int emptyStackTop = idata.itsMaxVars + idata.itsMaxLocals - 1;
2787 int maxFrameArray = idata.itsMaxFrameArray;
2788 if (maxFrameArray != emptyStackTop + idata.itsMaxStack + 1)
2789 Kit.codeBug();
2790
2791 Object[] stack;
2792 int[] stackAttributes;
2793 double[] sDbl;
2794 boolean stackReuse;
2795 if (frame.stack != null && maxFrameArray <= frame.stack.length) {
2796 // Reuse stacks from old frame
2797 stackReuse = true;
2798 stack = frame.stack;
2799 stackAttributes = frame.stackAttributes;
2800 sDbl = frame.sDbl;
2801 } else {
2802 stackReuse = false;
2803 stack = new Object[maxFrameArray];
2804 stackAttributes = new int[maxFrameArray];
2805 sDbl = new double[maxFrameArray];
2806 }
2807
2808 int varCount = idata.getParamAndVarCount();
2809 for (int i = 0; i < varCount; i++) {
2810 if (idata.getParamOrVarConst(i))
2811 stackAttributes[i] = ScriptableObject.CONST;
2812 }
2813 int definedArgs = idata.argCount;
2814 if (definedArgs > argCount) { definedArgs = argCount; }
2815
2816 // Fill the frame structure
2817
2818 frame.parentFrame = parentFrame;
2819 frame.frameIndex = (parentFrame == null)
2820 ? 0 : parentFrame.frameIndex + 1;
2821 if(frame.frameIndex > cx.getMaximumInterpreterStackDepth())
2822 {
2823 throw Context.reportRuntimeError("Exceeded maximum stack depth");
2824 }
2825 frame.frozen = false;
2826
2827 frame.fnOrScript = fnOrScript;
2828 frame.idata = idata;
2829
2830 frame.stack = stack;
2831 frame.stackAttributes = stackAttributes;
2832 frame.sDbl = sDbl;
2833 frame.varSource = frame;
2834 frame.localShift = idata.itsMaxVars;
2835 frame.emptyStackTop = emptyStackTop;
2836
2837 frame.debuggerFrame = debuggerFrame;
2838 frame.useActivation = useActivation;
2839
2840 frame.thisObj = thisObj;
2841
2842 // Initialize initial values of variables that change during
2843 // interpretation.
2844 frame.result = Undefined.instance;
2845 frame.pc = 0;
2846 frame.pcPrevBranch = 0;
2847 frame.pcSourceLineStart = idata.firstLinePC;
2848 frame.scope = scope;
2849
2850 frame.savedStackTop = emptyStackTop;
2851 frame.savedCallOp = 0;
2852
2853 System.arraycopy(args, argShift, stack, 0, definedArgs);
2854 if (argsDbl != null) {
2855 System.arraycopy(argsDbl, argShift, sDbl, 0, definedArgs);
2856 }
2857 for (int i = definedArgs; i != idata.itsMaxVars; ++i) {
2858 stack[i] = Undefined.instance;
2859 }
2860 if (stackReuse) {
2861 // Clean the stack part and space beyond stack if any
2862 // of the old array to allow to GC objects there
2863 for (int i = emptyStackTop + 1; i != stack.length; ++i) {
2864 stack[i] = null;
2865 }
2866 }
2867
2868 enterFrame(cx, frame, args, false);
2869 }
2870
2871 private static boolean isFrameEnterExitRequired(CallFrame frame)
2872 {
2873 return frame.debuggerFrame != null || frame.idata.itsNeedsActivation;
2874 }
2875
2876 private static void enterFrame(Context cx, CallFrame frame, Object[] args,
2877 boolean continuationRestart)
2878 {
2879 boolean usesActivation = frame.idata.itsNeedsActivation;
2880 boolean isDebugged = frame.debuggerFrame != null;
2881 if(usesActivation || isDebugged) {
2882 Scriptable scope = frame.scope;
2883 if(scope == null) {
2884 Kit.codeBug();
2885 } else if (continuationRestart) {
2886 // Walk the parent chain of frame.scope until a NativeCall is
2887 // found. Normally, frame.scope is a NativeCall when called
2888 // from initFrame() for a debugged or activatable function.
2889 // However, when called from interpretLoop() as part of
2890 // restarting a continuation, it can also be a NativeWith if
2891 // the continuation was captured within a "with" or "catch"
2892 // block ("catch" implicitly uses NativeWith to create a scope
2893 // to expose the exception variable).
2894 for(;;) {
2895 if(scope instanceof NativeWith) {
2896 scope = scope.getParentScope();
2897 if (scope == null || (frame.parentFrame != null &&
2898 frame.parentFrame.scope == scope))
2899 {
2900 // If we get here, we didn't find a NativeCall in
2901 // the call chain before reaching parent frame's
2902 // scope. This should not be possible.
2903 Kit.codeBug();
2904 break; // Never reached, but keeps the static analyzer
2905 // happy about "scope" not being null 5 lines above.
2906 }
2907 }
2908 else {
2909 break;
2910 }
2911 }
2912 }
2913 if (isDebugged) {
2914 frame.debuggerFrame.onEnter(cx, scope, frame.thisObj, args);
2915 }
2916 // Enter activation only when itsNeedsActivation true,
2917 // since debugger should not interfere with activation
2918 // chaining
2919 if (usesActivation) {
2920 ScriptRuntime.enterActivationFunction(cx, scope);
2921 }
2922 }
2923 }
2924
2925 private static void exitFrame(Context cx, CallFrame frame,
2926 Object throwable)
2927 {
2928 if (frame.idata.itsNeedsActivation) {
2929 ScriptRuntime.exitActivationFunction(cx);
2930 }
2931
2932 if (frame.debuggerFrame != null) {
2933 try {
2934 if (throwable instanceof Throwable) {
2935 frame.debuggerFrame.onExit(cx, true, throwable);
2936 } else {
2937 Object result;
2938 ContinuationJump cjump = (ContinuationJump)throwable;
2939 if (cjump == null) {
2940 result = frame.result;
2941 } else {
2942 result = cjump.result;
2943 }
2944 if (result == DOUBLE_MARK) {
2945 double resultDbl;
2946 if (cjump == null) {
2947 resultDbl = frame.resultDbl;
2948 } else {
2949 resultDbl = cjump.resultDbl;
2950 }
2951 result = ScriptRuntime.wrapNumber(resultDbl);
2952 }
2953 frame.debuggerFrame.onExit(cx, false, result);
2954 }
2955 } catch (Throwable ex) {
2956 System.err.println(
2957 "RHINO USAGE WARNING: onExit terminated with exception");
2958 ex.printStackTrace(System.err);
2959 }
2960 }
2961 }
2962
2963 private static void setCallResult(CallFrame frame,
2964 Object callResult,
2965 double callResultDbl)
2966 {
2967 if (frame.savedCallOp == Token.CALL) {
2968 frame.stack[frame.savedStackTop] = callResult;
2969 frame.sDbl[frame.savedStackTop] = callResultDbl;
2970 } else if (frame.savedCallOp == Token.NEW) {
2971 // If construct returns scriptable,
2972 // then it replaces on stack top saved original instance
2973 // of the object.
2974 if (callResult instanceof Scriptable) {
2975 frame.stack[frame.savedStackTop] = callResult;
2976 }
2977 } else {
2978 Kit.codeBug();
2979 }
2980 frame.savedCallOp = 0;
2981 }
2982
2983 public static NativeContinuation captureContinuation(Context cx) {
2984 if (cx.lastInterpreterFrame == null ||
2985 !(cx.lastInterpreterFrame instanceof CallFrame))
2986 {
2987 throw new IllegalStateException("Interpreter frames not found");
2988 }
2989 return captureContinuation(cx, (CallFrame)cx.lastInterpreterFrame, true);
2990 }
2991
2992 private static NativeContinuation captureContinuation(Context cx, CallFrame frame,
2993 boolean requireContinuationsTopFrame)
2994 {
2995 NativeContinuation c = new NativeContinuation();
2996 ScriptRuntime.setObjectProtoAndParent(
2997 c, ScriptRuntime.getTopCallScope(cx));
2998
2999 // Make sure that all frames are frozen
3000 CallFrame x = frame;
3001 CallFrame outermost = frame;
3002 while (x != null && !x.frozen) {
3003 x.frozen = true;
3004 // Allow to GC unused stack space
3005 for (int i = x.savedStackTop + 1; i != x.stack.length; ++i) {
3006 // Allow to GC unused stack space
3007 x.stack[i] = null;
3008 x.stackAttributes[i] = ScriptableObject.EMPTY;
3009 }
3010 if (x.savedCallOp == Token.CALL) {
3011 // the call will always overwrite the stack top with the result
3012 x.stack[x.savedStackTop] = null;
3013 } else {
3014 if (x.savedCallOp != Token.NEW) Kit.codeBug();
3015 // the new operator uses stack top to store the constructed
3016 // object so it shall not be cleared: see comments in
3017 // setCallResult
3018 }
3019 outermost = x;
3020 x = x.parentFrame;
3021 }
3022
3023 if (requireContinuationsTopFrame) {
3024 while (outermost.parentFrame != null)
3025 outermost = outermost.parentFrame;
3026
3027 if (!outermost.isContinuationsTopFrame) {
3028 throw new IllegalStateException("Cannot capture continuation " +
3029 "from JavaScript code not called directly by " +
3030 "executeScriptWithContinuations or " +
3031 "callFunctionWithContinuations");
3032 }
3033 }
3034
3035 c.initImplementation(frame);
3036 return c;
3037 }
3038
3039 private static int stack_int32(CallFrame frame, int i)
3040 {
3041 Object x = frame.stack[i];
3042 if (x == UniqueTag.DOUBLE_MARK) {
3043 return ScriptRuntime.toInt32(frame.sDbl[i]);
3044 } else {
3045 return ScriptRuntime.toInt32(x);
3046 }
3047 }
3048
3049 private static double stack_double(CallFrame frame, int i)
3050 {
3051 Object x = frame.stack[i];
3052 if (x != UniqueTag.DOUBLE_MARK) {
3053 return ScriptRuntime.toNumber(x);
3054 } else {
3055 return frame.sDbl[i];
3056 }
3057 }
3058
3059 private static boolean stack_boolean(CallFrame frame, int i)
3060 {
3061 Object x = frame.stack[i];
3062 if (x == Boolean.TRUE) {
3063 return true;
3064 } else if (x == Boolean.FALSE) {
3065 return false;
3066 } else if (x == UniqueTag.DOUBLE_MARK) {
3067 double d = frame.sDbl[i];
3068 return d == d && d != 0.0;
3069 } else if (x == null || x == Undefined.instance) {
3070 return false;
3071 } else if (x instanceof Number) {
3072 double d = ((Number)x).doubleValue();
3073 return (d == d && d != 0.0);
3074 } else if (x instanceof Boolean) {
3075 return ((Boolean)x).booleanValue();
3076 } else {
3077 return ScriptRuntime.toBoolean(x);
3078 }
3079 }
3080
3081 private static void doAdd(Object[] stack, double[] sDbl, int stackTop,
3082 Context cx)
3083 {
3084 Object rhs = stack[stackTop + 1];
3085 Object lhs = stack[stackTop];
3086 double d;
3087 boolean leftRightOrder;
3088 if (rhs == DOUBLE_MARK) {
3089 d = sDbl[stackTop + 1];
3090 if (lhs == DOUBLE_MARK) {
3091 sDbl[stackTop] += d;
3092 return;
3093 }
3094 leftRightOrder = true;
3095 // fallthrough to object + number code
3096 } else if (lhs == DOUBLE_MARK) {
3097 d = sDbl[stackTop];
3098 lhs = rhs;
3099 leftRightOrder = false;
3100 // fallthrough to object + number code
3101 } else {
3102 if (lhs instanceof Scriptable || rhs instanceof Scriptable) {
3103 stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx);
3104 } else if (lhs instanceof CharSequence || rhs instanceof CharSequence) {
3105 CharSequence lstr = ScriptRuntime.toCharSequence(lhs);
3106 CharSequence rstr = ScriptRuntime.toCharSequence(rhs);
3107 stack[stackTop] = new ConsString(lstr, rstr);
3108 } else {
3109 double lDbl = (lhs instanceof Number)
3110 ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
3111 double rDbl = (rhs instanceof Number)
3112 ? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs);
3113 stack[stackTop] = DOUBLE_MARK;
3114 sDbl[stackTop] = lDbl + rDbl;
3115 }
3116 return;
3117 }
3118
3119 // handle object(lhs) + number(d) code
3120 if (lhs instanceof Scriptable) {
3121 rhs = ScriptRuntime.wrapNumber(d);
3122 if (!leftRightOrder) {
3123 Object tmp = lhs;
3124 lhs = rhs;
3125 rhs = tmp;
3126 }
3127 stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx);
3128 } else if (lhs instanceof CharSequence) {
3129 CharSequence lstr = (CharSequence)lhs;
3130 CharSequence rstr = ScriptRuntime.toCharSequence(d);
3131 if (leftRightOrder) {
3132 stack[stackTop] = new ConsString(lstr, rstr);
3133 } else {
3134 stack[stackTop] = new ConsString(rstr, lstr);
3135 }
3136 } else {
3137 double lDbl = (lhs instanceof Number)
3138 ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
3139 stack[stackTop] = DOUBLE_MARK;
3140 sDbl[stackTop] = lDbl + d;
3141 }
3142 }
3143
3144 private static int doArithmetic(CallFrame frame, int op, Object[] stack,
3145 double[] sDbl, int stackTop) {
3146 double rDbl = stack_double(frame, stackTop);
3147 --stackTop;
3148 double lDbl = stack_double(frame, stackTop);
3149 stack[stackTop] = DOUBLE_MARK;
3150 switch (op) {
3151 case Token.SUB:
3152 lDbl -= rDbl;
3153 break;
3154 case Token.MUL:
3155 lDbl *= rDbl;
3156 break;
3157 case Token.DIV:
3158 lDbl /= rDbl;
3159 break;
3160 case Token.MOD:
3161 lDbl %= rDbl;
3162 break;
3163 }
3164 sDbl[stackTop] = lDbl;
3165 return stackTop;
3166 }
3167
3168 private static Object[] getArgsArray(Object[] stack, double[] sDbl,
3169 int shift, int count)
3170 {
3171 if (count == 0) {
3172 return ScriptRuntime.emptyArgs;
3173 }
3174 Object[] args = new Object[count];
3175 for (int i = 0; i != count; ++i, ++shift) {
3176 Object val = stack[shift];
3177 if (val == UniqueTag.DOUBLE_MARK) {
3178 val = ScriptRuntime.wrapNumber(sDbl[shift]);
3179 }
3180 args[i] = val;
3181 }
3182 return args;
3183 }
3184
3185 private static void addInstructionCount(Context cx, CallFrame frame,
3186 int extra)
3187 {
3188 cx.instructionCount += frame.pc - frame.pcPrevBranch + extra;
3189 if (cx.instructionCount > cx.instructionThreshold) {
3190 cx.observeInstructionCount(cx.instructionCount);
3191 cx.instructionCount = 0;
3192 }
3193 }
3194 }