Debian Codegraph @

src/main/java/org/jboss/classfilewriter/code/CodeAttribute.java

raw
1 /*
2 * JBoss, Home of Professional Open Source.
3 *
4 * Copyright 2012 Red Hat, Inc.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.jboss.classfilewriter.code;
19
20 import java.io.ByteArrayOutputStream;
21 import java.io.DataOutputStream;
22 import java.io.IOException;
23 import java.lang.reflect.Constructor;
24 import java.lang.reflect.Method;
25 import java.lang.reflect.Modifier;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.LinkedHashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.Set;
36
37 import org.jboss.classfilewriter.ClassMethod;
38 import org.jboss.classfilewriter.InvalidBytecodeException;
39 import org.jboss.classfilewriter.attributes.Attribute;
40 import org.jboss.classfilewriter.attributes.StackMapTableAttribute;
41 import org.jboss.classfilewriter.constpool.ConstPool;
42 import org.jboss.classfilewriter.util.ByteArrayDataOutputStream;
43 import org.jboss.classfilewriter.util.DescriptorUtils;
44 import org.jboss.classfilewriter.util.LazySize;
45
46 @SuppressWarnings("unused")
47 public class CodeAttribute extends Attribute {
48
49 public static final String NAME = "Code";
50
51 private final ClassMethod method;
52
53 private final ConstPool constPool;
54
55 private final ByteArrayOutputStream finalDataBytes;
56
57 private final DataOutputStream data;
58
59 private int maxLocals = 0;
60
61 private int maxStackDepth = 0;
62
63 private final LinkedHashMap<Integer, StackFrame> stackFrames = new LinkedHashMap<Integer, StackFrame>();
64
65 /**
66 * maps bytecode offsets to jump locations. As these jump locations where not known when the instruction was written they
67 * need to be overwritten when the final bytecode is written out
68 */
69 private final Map<Integer, Integer> jumpLocations = new HashMap<Integer, Integer>();
70
71 /**
72 * maps bytecode offsets to jump locations. As these jump locations where not known when the instruction was written they
73 * need to be overwritten when the final bytecode is written out
74 * <p/>
75 * These jump locations are 32 bit offsets,
76 */
77 private final Map<Integer, Integer> jumpLocations32 = new HashMap<Integer, Integer>();
78
79 private StackFrame currentFrame;
80
81 private int currentOffset;
82
83 private final List<Attribute> attributes = new ArrayList<Attribute>();
84
85 private final StackMapTableAttribute stackMapTableAttribute;
86
87 private final List<ExceptionHandler> exceptionTable = new ArrayList<ExceptionHandler>();
88
89 private StackFrameTypeResolver stackFrameTypeResolver;
90
91 public CodeAttribute(ClassMethod method, ConstPool constPool) {
92 super(NAME, constPool);
93 this.method = method;
94 this.constPool = constPool;
95 this.finalDataBytes = new ByteArrayOutputStream();
96 this.data = new DataOutputStream(finalDataBytes);
97
98 if (!Modifier.isStatic(method.getAccessFlags())) {
99 maxLocals++;
100 }
101 for (String param : method.getParameters()) {
102 if (DescriptorUtils.isWide(param)) {
103 maxLocals += 2;
104 } else {
105 maxLocals++;
106 }
107 }
108 // creates a new initial stack frame
109 currentFrame = new StackFrame(method);
110 stackFrames.put(0, currentFrame);
111 currentOffset = 0;
112 stackMapTableAttribute = new StackMapTableAttribute(method, constPool);
113 }
114
115 public StackFrameTypeResolver getStackFrameTypeResolver() {
116 return stackFrameTypeResolver;
117 }
118
119 public void setStackFrameTypeResolver(StackFrameTypeResolver stackFrameTypeResolver) {
120 this.stackFrameTypeResolver = stackFrameTypeResolver;
121 }
122
123 @Override
124 public void writeData(ByteArrayDataOutputStream stream) throws IOException {
125
126 // add the stack map table
127 if (method.getClassFile().getClassLoader() != null) {
128 //we don't generate the stack map if the class loader is null
129 attributes.add(stackMapTableAttribute);
130 }
131
132 if (finalDataBytes.size() == 0) {
133 throw new RuntimeException("Code attribute is empty for method " + method.getName() + " " + method.getDescriptor());
134 }
135
136 byte[] bytecode = finalDataBytes.toByteArray();
137 for (Entry<Integer, Integer> e : jumpLocations.entrySet()) {
138 overwriteShort(bytecode, e.getKey(), e.getValue());
139 }
140 for (Entry<Integer, Integer> e : jumpLocations32.entrySet()) {
141 overwriteInt(bytecode, e.getKey(), e.getValue());
142 }
143
144 LazySize size = stream.writeSize();
145 stream.writeShort(maxStackDepth);
146 stream.writeShort(maxLocals);
147 stream.writeInt(bytecode.length);
148 stream.write(bytecode);
149 stream.writeShort(exceptionTable.size()); // exception table length
150 for (ExceptionHandler exception : exceptionTable) {
151 stream.writeShort(exception.getStart());
152 stream.writeShort(exception.getEnd());
153 stream.writeShort(exception.getHandler());
154 stream.writeShort(exception.getExceptionIndex());
155 }
156 stream.writeShort(attributes.size()); // attributes count
157 for (Attribute attribute : attributes) {
158 attribute.write(stream);
159 }
160 size.markEnd();
161 }
162
163 // -------------------------------------------
164 // Instruction methods, in alphabetical order
165
166 public void aaload() {
167 assertTypeOnStack(StackEntryType.INT, "aaload requires int on top of stack");
168 if (!getStack().top_1().getDescriptor().startsWith("[")) {
169 throw new InvalidBytecodeException("aaload needs an array in position 2 on the stack");
170 }
171 writeByte(Opcode.AALOAD);
172 currentOffset++;
173 advanceFrame(currentFrame.pop2push1("Ljava/lang/Object;"));
174 }
175
176 public void aastore() {
177 assertTypeOnStack(StackEntryType.OBJECT, "aastore requires reference type on top of stack");
178 assertTypeOnStack(1, StackEntryType.INT, "aastore requires an int on position 2 stack");
179 if (!getStack().top_2().getDescriptor().startsWith("[")) {
180 throw new InvalidBytecodeException("aaload needs an array in position 3 on the stack");
181 }
182 writeByte(Opcode.AASTORE);
183 currentOffset++;
184 advanceFrame(currentFrame.pop3());
185 }
186
187 public void aconstNull() {
188 writeByte(Opcode.ACONST_NULL);
189 currentOffset++;
190 advanceFrame(currentFrame.aconstNull());
191 }
192
193 public void aload(int no) {
194 LocalVariableState locals = getLocalVars();
195 if (locals.size() <= no) {
196 throw new InvalidBytecodeException("Cannot load variable at " + no + ". Local Variables: " + locals.toString());
197 }
198 StackEntry entry = locals.get(no);
199 if (entry.getType() != StackEntryType.OBJECT && entry.getType() != StackEntryType.NULL
200 && entry.getType() != StackEntryType.UNINITIALIZED_THIS
201 && entry.getType() != StackEntryType.UNITITIALIZED_OBJECT) {
202 throw new InvalidBytecodeException("Invalid local variable at location " + no + " Local Variables "
203 + locals.toString());
204 }
205
206 if (no > 0xFF) {
207 // wide version
208 writeByte(Opcode.WIDE);
209 writeByte(Opcode.ALOAD);
210 writeShort(no);
211 currentOffset += 4;
212 } else if (no >= 0 && no < 4) {
213 writeByte(Opcode.ALOAD_0 + no);
214 currentOffset++;
215 } else {
216 writeByte(Opcode.ALOAD);
217 writeByte(no);
218 currentOffset += 2;
219 }
220 advanceFrame(currentFrame.push(entry));
221 }
222
223 public void anewarray(String arrayType) {
224 assertTypeOnStack(StackEntryType.INT, "anewarray requires int on stack");
225 int index = constPool.addClassEntry(arrayType);
226 writeByte(Opcode.ANEWARRAY);
227 writeShort(index);
228 currentOffset += 3;
229 if (arrayType.startsWith("[")) {
230 advanceFrame(currentFrame.replace("[" + arrayType));
231 } else {
232 advanceFrame(currentFrame.replace("[L" + arrayType + ";"));
233 }
234 }
235
236 public void arraylength() {
237 assertTypeOnStack(StackEntryType.OBJECT, "arraylength requires array on stack");
238 writeByte(Opcode.ARRAYLENGTH);
239 currentOffset++;
240 advanceFrame(currentFrame.replace("I"));
241 }
242
243 public void astore(int no) {
244 assertTypeOnStack(StackEntryType.OBJECT, "aastore requires reference type on stack");
245 if (no > 0xFF) {
246 // wide version
247 writeByte(Opcode.WIDE);
248 writeByte(Opcode.ASTORE);
249 writeShort(no);
250 currentOffset += 4;
251 } else if (no >= 0 && no < 4) {
252 writeByte(Opcode.ASTORE_0 + no);
253 currentOffset++;
254 } else {
255 writeByte(Opcode.ASTORE);
256 writeByte(no);
257 currentOffset += 2;
258 }
259 advanceFrame(currentFrame.store(no));
260 }
261
262 public void athrow() {
263 assertTypeOnStack(StackEntryType.OBJECT, "athrow requires an object on the stack");
264 writeByte(Opcode.ATHROW);
265 currentOffset++;
266 currentFrame = null;
267 }
268
269 public void baload() {
270 assertTypeOnStack(StackEntryType.INT, "baload requires an int on top of the stack");
271 assertTypeOnStack(1, StackEntryType.OBJECT, "baload requires an array in position 2 on the stack");
272 writeByte(Opcode.BALOAD);
273 currentOffset++;
274 advanceFrame(currentFrame.pop2push1("I"));
275 }
276
277 public void bastore() {
278 assertTypeOnStack(StackEntryType.INT, "bastore requires an int on top of the stack");
279 assertTypeOnStack(1, StackEntryType.INT, "bastore requires an int in position 2 on the stack");
280 assertTypeOnStack(2, StackEntryType.OBJECT, "bastore requires an array reference in position 3 on the stack");
281 writeByte(Opcode.BASTORE);
282 currentOffset++;
283 advanceFrame(currentFrame.pop3());
284 }
285
286 public void caload() {
287 assertTypeOnStack(StackEntryType.INT, "caload requires an int on top of the stack");
288 assertTypeOnStack(1, StackEntryType.OBJECT, "caload requires an array in position 2 on the stack");
289 writeByte(Opcode.CALOAD);
290 currentOffset++;
291 advanceFrame(currentFrame.pop2push1("I"));
292 }
293
294 public void castore() {
295 assertTypeOnStack(StackEntryType.INT, "castore requires an int on top of the stack");
296 assertTypeOnStack(1, StackEntryType.INT, "castore requires an int in position 2 on the stack");
297 assertTypeOnStack(2, StackEntryType.OBJECT, "castore requires an array reference in position 3 on the stack");
298 writeByte(Opcode.CASTORE);
299 currentOffset++;
300 advanceFrame(currentFrame.pop3());
301 }
302
303 public void bipush(byte value) {
304 writeByte(Opcode.BIPUSH);
305 writeByte(value);
306 currentOffset += 2;
307 advanceFrame(currentFrame.push("B"));
308 }
309
310 /**
311 * marks the end of a branch. The current stack frame is checked for compatibility with the stack frame at the branch start
312 */
313 public void branchEnd(BranchEnd end) {
314 mergeStackFrames(end.getStackFrame());
315 final int jump = currentOffset - end.getOffsetLocation();
316 if (end.isJump32Bit()) {
317 jumpLocations32.put(end.getBranchLocation(), jump);
318 } else {
319 if (jump > Short.MAX_VALUE) {
320 throw new RuntimeException(jump + " is to big to be written as a 16 bit value");
321 }
322 jumpLocations.put(end.getBranchLocation(), jump);
323 }
324 }
325
326 /**
327 * Do not use Descriptor format (e.g. Ljava/lang/Object;), the correct form is just java/lang/Object or java.lang.Object
328 */
329 public void checkcast(String className) {
330 if (!className.startsWith("[") && className.endsWith(";")) {
331 throw new RuntimeException("Invalid cast format " + className);
332 }
333 className = className.replace('.', '/');
334 assertTypeOnStack(StackEntryType.OBJECT, "checkcast requires reference type on stack");
335 int classIndex = constPool.addClassEntry(className);
336 writeByte(Opcode.CHECKCAST);
337 writeShort(classIndex);
338 currentOffset += 3;
339 advanceFrame(currentFrame.replace(className));
340 }
341
342 public void checkcast(Class<?> clazz) {
343 checkcast(clazz.getName());
344 }
345
346 public void d2f() {
347 assertTypeOnStack(StackEntryType.DOUBLE, "d2f requires double on stack");
348 writeByte(Opcode.D2F);
349 currentOffset++;
350 advanceFrame(currentFrame.pop2push1("F"));
351 }
352
353 public void d2i() {
354 assertTypeOnStack(StackEntryType.DOUBLE, "d2i requires double on stack");
355 writeByte(Opcode.D2I);
356 currentOffset++;
357 advanceFrame(currentFrame.pop2push1("I"));
358 }
359
360 public void d2l() {
361 assertTypeOnStack(StackEntryType.DOUBLE, "d2l requires double on stack");
362 writeByte(Opcode.D2L);
363 currentOffset++;
364 advanceFrame(currentFrame.pop2push1("J"));
365 }
366
367 public void dadd() {
368 assertTypeOnStack(StackEntryType.DOUBLE, "dadd requires double on stack");
369 assertTypeOnStack(2, StackEntryType.DOUBLE, "dadd requires double on stack");
370 writeByte(Opcode.DADD);
371 currentOffset++;
372 advanceFrame(currentFrame.pop2());
373 }
374
375 public void daload() {
376 assertTypeOnStack(StackEntryType.INT, "daload requires an int on top of the stack");
377 assertTypeOnStack(1, StackEntryType.OBJECT, "daload requires an array in position 2 on the stack");
378 writeByte(Opcode.DALOAD);
379 currentOffset++;
380 advanceFrame(currentFrame.pop2push1("D"));
381 }
382
383 public void dastore() {
384 assertTypeOnStack(StackEntryType.DOUBLE, "dastore requires an int on top of the stack");
385 assertTypeOnStack(2, StackEntryType.INT, "dastore requires an int in position 2 on the stack");
386 assertTypeOnStack(3, StackEntryType.OBJECT, "dastore requires an array reference in position 3 on the stack");
387 writeByte(Opcode.DASTORE);
388 currentOffset++;
389 advanceFrame(currentFrame.pop4());
390 }
391
392 public void dcmpg() {
393 assertTypeOnStack(StackEntryType.DOUBLE, "dcmpg requires double on stack");
394 assertTypeOnStack(2, StackEntryType.DOUBLE, "dcmpg requires double on stack");
395 writeByte(Opcode.DCMPG);
396 currentOffset++;
397 advanceFrame(currentFrame.pop4push1("I"));
398 }
399
400 public void dcmpl() {
401 assertTypeOnStack(StackEntryType.DOUBLE, "dcmpl requires double on stack");
402 assertTypeOnStack(2, StackEntryType.DOUBLE, "dcmpl requires double in position 3 on stack");
403 writeByte(Opcode.DCMPL);
404 currentOffset++;
405 advanceFrame(currentFrame.pop4push1("I"));
406 }
407
408 /**
409 * Adds the appropriate dconst instruction.
410 * <p/>
411 * note, if the value is not 0 or 1 then ldc is used instead
412 */
413 public void dconst(double value) {
414 if (value == 0.0) {
415 writeByte(Opcode.DCONST_0);
416 } else if (value == 1.0) {
417 writeByte(Opcode.DCONST_1);
418 } else {
419 ldc2(value);
420 return;
421 }
422 currentOffset++;
423 advanceFrame(currentFrame.push("D"));
424 }
425
426 public void ddiv() {
427 assertTypeOnStack(StackEntryType.DOUBLE, "ddiv requires double on stack");
428 assertTypeOnStack(2, StackEntryType.DOUBLE, "ddiv requires double in position 3 on stack");
429 writeByte(Opcode.DDIV);
430 currentOffset++;
431 advanceFrame(currentFrame.pop2());
432 }
433
434 public void dload(int no) {
435 LocalVariableState locals = getLocalVars();
436 if (locals.size() <= no) {
437 throw new InvalidBytecodeException("Cannot load variable at " + no + ". Local Variables: " + locals.toString());
438 }
439 StackEntry entry = locals.get(no);
440 if (entry.getType() != StackEntryType.DOUBLE) {
441 throw new InvalidBytecodeException("Invalid local variable at location " + no + " Local Variables "
442 + locals.toString());
443 }
444
445 if (no > 0xFF) {
446 // wide version
447 writeByte(Opcode.WIDE);
448 writeByte(Opcode.DLOAD);
449 writeShort(no);
450 currentOffset += 4;
451 } else if (no >= 0 && no < 4) {
452 writeByte(Opcode.DLOAD_0 + no);
453 currentOffset++;
454 } else {
455 writeByte(Opcode.DLOAD);
456 writeByte(no);
457 currentOffset += 2;
458 }
459 advanceFrame(currentFrame.push(entry));
460 }
461
462 public void dmul() {
463 assertTypeOnStack(StackEntryType.DOUBLE, "dmul requires double on stack");
464 assertTypeOnStack(2, StackEntryType.DOUBLE, "dmul requires double in position 3 on stack");
465 writeByte(Opcode.DMUL);
466 currentOffset++;
467 advanceFrame(currentFrame.pop2());
468 }
469
470 public void dneg() {
471 assertTypeOnStack(StackEntryType.DOUBLE, "dneg requires double on stack");
472 writeByte(Opcode.DNEG);
473 currentOffset++;
474 duplicateFrame();
475 }
476
477 public void drem() {
478 assertTypeOnStack(StackEntryType.DOUBLE, "drem requires double on stack");
479 assertTypeOnStack(2, StackEntryType.DOUBLE, "drem requires double in position 3 on stack");
480 writeByte(Opcode.DREM);
481 currentOffset++;
482 advanceFrame(currentFrame.pop2());
483 }
484
485 public void dstore(int no) {
486 assertTypeOnStack(StackEntryType.DOUBLE, "dastore requires double on stack");
487 if (no > 0xFF) {
488 // wide version
489 writeByte(Opcode.WIDE);
490 writeByte(Opcode.DSTORE);
491 writeShort(no);
492 currentOffset += 4;
493 } else if (no >= 0 && no < 4) {
494 writeByte(Opcode.DSTORE_0 + no);
495 currentOffset++;
496 } else {
497 writeByte(Opcode.DSTORE);
498 writeByte(no);
499 currentOffset += 2;
500 }
501 advanceFrame(currentFrame.store(no));
502 }
503
504 public void dsub() {
505 assertTypeOnStack(StackEntryType.DOUBLE, "dsub requires double on stack");
506 assertTypeOnStack(2, StackEntryType.DOUBLE, "dsub requires double in position 3 on stack");
507 writeByte(Opcode.DSUB);
508 currentOffset++;
509 advanceFrame(currentFrame.pop2());
510 }
511
512 public void dup() {
513 assertNotWideOnStack("dup acnnot be used if double or long is on top of the stack");
514 writeByte(Opcode.DUP);
515 currentOffset++;
516 advanceFrame(currentFrame.dup());
517 }
518
519 public void dupX1() {
520 assertNotWideOnStack("dup_x1 cannot be used if double or long is on top of the stack");
521 assertNotWideOnStack(1, "dup_x1 cannot be used if double or long is in position 2 on the stack");
522 writeByte(Opcode.DUP_X1);
523 currentOffset++;
524 advanceFrame(currentFrame.dupX1());
525 }
526
527 public void dupX2() {
528 assertNotWideOnStack("dup_x2 acnnot be used if double or long is on top of the stack");
529 writeByte(Opcode.DUP_X2);
530 currentOffset++;
531 advanceFrame(currentFrame.dupX2());
532 }
533
534 public void dup2() {
535 writeByte(Opcode.DUP2);
536 currentOffset++;
537 advanceFrame(currentFrame.dup2());
538 }
539
540 public void dup2X1() {
541 assertNotWideOnStack(2, "dup2_x1 cannot be used if double or long is in position 3 on the stack");
542 writeByte(Opcode.DUP2_X1);
543 currentOffset++;
544 advanceFrame(currentFrame.dup2X1());
545 }
546
547 public void dup2X2() {
548 assertNotWideOnStack(3, "dup2_x2 cannot be used if double or long is in position 4 on the stack");
549 writeByte(Opcode.DUP2_X2);
550 currentOffset++;
551 advanceFrame(currentFrame.dup2X2());
552 }
553
554 /**
555 * Begin writing an exception handler block. The handler is not actually persisted until exceptionHandler is called.
556 */
557 public ExceptionHandler exceptionBlockStart(String exceptionType) {
558 return new ExceptionHandler(currentOffset, constPool.addClassEntry(exceptionType), exceptionType,
559 currentFrame);
560 }
561
562 /**
563 * Mark the end of an exception handler block. The last instruction that was written will be the last instruction covered by
564 * the handler
565 */
566 public void exceptionBlockEnd(ExceptionHandler handler) {
567 handler.setEnd(currentOffset);
568 }
569
570 /**
571 * Marks the current code location as the exception handler and adds the handler to the exception handler table;
572 */
573 public void exceptionHandlerStart(ExceptionHandler handler) {
574 if (handler.getEnd() == 0) {
575 throw new InvalidBytecodeException(
576 "handler end location must be initialised via exceptionHandlerEnd before calling exceptionHandlerAdd");
577 }
578 handler.setHandler(currentOffset);
579 exceptionTable.add(handler);
580 mergeStackFrames(new StackFrame(new StackState(handler.getExceptionType(), constPool), handler.getFrame()
581 .getLocalVariableState(), StackFrameType.FULL_FRAME));
582 }
583
584 public void f2d() {
585 assertTypeOnStack(StackEntryType.FLOAT, "f2s requires float on stack");
586 writeByte(Opcode.F2D);
587 currentOffset++;
588 advanceFrame(currentFrame.replace("D"));
589 }
590
591 public void f2i() {
592 assertTypeOnStack(StackEntryType.FLOAT, "f2i requires float on stack");
593 writeByte(Opcode.F2I);
594 currentOffset++;
595 advanceFrame(currentFrame.replace("I"));
596 }
597
598 public void f2l() {
599 assertTypeOnStack(StackEntryType.FLOAT, "f2l requires float on stack");
600 writeByte(Opcode.F2L);
601 currentOffset++;
602 advanceFrame(currentFrame.replace("J"));
603 }
604
605 public void fadd() {
606 assertTypeOnStack(StackEntryType.FLOAT, "fadd requires float on stack");
607 assertTypeOnStack(1, StackEntryType.FLOAT, "fadd requires float on stack");
608 writeByte(Opcode.FADD);
609 currentOffset++;
610 advanceFrame(currentFrame.pop());
611 }
612
613 public void faload() {
614 assertTypeOnStack(StackEntryType.INT, "faload requires an int on top of the stack");
615 assertTypeOnStack(1, StackEntryType.OBJECT, "faload requires an array in position 2 on the stack");
616 writeByte(Opcode.FALOAD);
617 currentOffset++;
618 advanceFrame(currentFrame.pop2push1("F"));
619 }
620
621 public void fastore() {
622 assertTypeOnStack(StackEntryType.FLOAT, "fastore requires an int on top of the stack");
623 assertTypeOnStack(1, StackEntryType.INT, "fastore requires an int in position 2 on the stack");
624 assertTypeOnStack(2, StackEntryType.OBJECT, "fastore requires an array reference in position 3 on the stack");
625 writeByte(Opcode.FASTORE);
626 currentOffset++;
627 advanceFrame(currentFrame.pop3());
628 }
629
630 public void fcmpg() {
631 assertTypeOnStack(StackEntryType.FLOAT, "fcmpg requires float on stack");
632 assertTypeOnStack(1, StackEntryType.FLOAT, "fcmpg requires float on stack");
633 writeByte(Opcode.FCMPG);
634 currentOffset++;
635 advanceFrame(currentFrame.pop2push1("I"));
636 }
637
638 public void fcmpl() {
639 assertTypeOnStack(StackEntryType.FLOAT, "fcmpl requires float on stack");
640 assertTypeOnStack(1, StackEntryType.FLOAT, "fcmpl requires float in position 2 on stack");
641 writeByte(Opcode.FCMPL);
642 currentOffset++;
643 advanceFrame(currentFrame.pop2push1("I"));
644 }
645
646 /**
647 * Adds the appropriate fconst instruction.
648 * <p/>
649 * note, if the value is not 0, 1, 2 then ldc is used instead
650 */
651 public void fconst(float value) {
652 if (value == 0) {
653 writeByte(Opcode.FCONST_0);
654 } else if (value == 1) {
655 writeByte(Opcode.FCONST_1);
656 } else if (value == 2) {
657 writeByte(Opcode.FCONST_2);
658 } else {
659 ldc(value);
660 return;
661 }
662 currentOffset++;
663 advanceFrame(currentFrame.push("F"));
664 }
665
666 public void fdiv() {
667 assertTypeOnStack(StackEntryType.FLOAT, "fdiv requires float on stack");
668 assertTypeOnStack(1, StackEntryType.FLOAT, "fdiv requires float in position 2 on stack");
669 writeByte(Opcode.FDIV);
670 currentOffset++;
671 advanceFrame(currentFrame.pop());
672 }
673
674 public void fload(int no) {
675 LocalVariableState locals = getLocalVars();
676 if (locals.size() <= no) {
677 throw new InvalidBytecodeException("Cannot load variable at " + no + ". Local Variables: " + locals.toString());
678 }
679 StackEntry entry = locals.get(no);
680 if (entry.getType() != StackEntryType.FLOAT) {
681 throw new InvalidBytecodeException("Invalid local variable at location " + no + " Local Variables "
682 + locals.toString());
683 }
684
685 if (no > 0xFF) {
686 // wide version
687 writeByte(Opcode.WIDE);
688 writeByte(Opcode.FLOAD);
689 writeShort(no);
690 currentOffset += 4;
691 } else if (no >= 0 && no < 4) {
692 writeByte(Opcode.FLOAD_0 + no);
693 currentOffset++;
694 } else {
695 writeByte(Opcode.FLOAD);
696 writeByte(no);
697 currentOffset += 2;
698 }
699 advanceFrame(currentFrame.push(entry));
700 }
701
702 public void fmul() {
703 assertTypeOnStack(StackEntryType.FLOAT, "fmul requires float on stack");
704 assertTypeOnStack(1, StackEntryType.FLOAT, "fmul requires float in position 2 on stack");
705 writeByte(Opcode.FMUL);
706 currentOffset++;
707 advanceFrame(currentFrame.pop());
708 }
709
710 public void fneg() {
711 assertTypeOnStack(StackEntryType.FLOAT, "fneg requires float on stack");
712 writeByte(Opcode.FNEG);
713 currentOffset++;
714 duplicateFrame();
715 }
716
717 public void frem() {
718 assertTypeOnStack(StackEntryType.FLOAT, "frem requires float on stack");
719 assertTypeOnStack(1, StackEntryType.FLOAT, "frem requires float in position 2 on stack");
720 writeByte(Opcode.FREM);
721 currentOffset++;
722 advanceFrame(currentFrame.pop());
723 }
724
725 public void fstore(int no) {
726 assertTypeOnStack(StackEntryType.FLOAT, "fstore requires float on stack");
727 if (no > 0xFF) {
728 // wide version
729 writeByte(Opcode.WIDE);
730 writeByte(Opcode.FSTORE);
731 writeShort(no);
732 currentOffset += 4;
733 } else if (no >= 0 && no < 4) {
734 writeByte(Opcode.FSTORE_0 + no);
735 currentOffset++;
736 } else {
737 writeByte(Opcode.FSTORE);
738 writeByte(no);
739 currentOffset += 2;
740 }
741 advanceFrame(currentFrame.store(no));
742 }
743
744 public void fsub() {
745 assertTypeOnStack(StackEntryType.FLOAT, "fsub requires float on stack");
746 assertTypeOnStack(1, StackEntryType.FLOAT, "fsub requires float in position 2 on stack");
747 writeByte(Opcode.FSUB);
748 currentOffset++;
749 advanceFrame(currentFrame.pop());
750 }
751
752 public void getfield(String className, String field, Class<?> fieldType) {
753 getfield(className, field, DescriptorUtils.makeDescriptor(fieldType));
754 }
755
756 public void getfield(String className, String field, String descriptor) {
757 assertTypeOnStack(StackEntryType.OBJECT, "getfield requires object on stack");
758 int index = constPool.addFieldEntry(className, field, descriptor);
759 writeByte(Opcode.GETFIELD);
760 writeShort(index);
761 currentOffset += 3;
762 advanceFrame(currentFrame.replace(descriptor));
763 }
764
765 public void getstatic(String className, String field, Class<?> fieldType) {
766 getstatic(className, field, DescriptorUtils.makeDescriptor(fieldType));
767 }
768
769 public void getstatic(String className, String field, String descriptor) {
770 int index = constPool.addFieldEntry(className, field, descriptor);
771 writeByte(Opcode.GETSTATIC);
772 writeShort(index);
773 currentOffset += 3;
774 advanceFrame(currentFrame.push(descriptor));
775 }
776
777 /**
778 * writes a goto instruction.
779 * <p/>
780 * TODO: implemented goto_w
781 */
782 public void gotoInstruction(CodeLocation location) {
783 writeByte(Opcode.GOTO);
784 writeShort(location.getLocation() - currentOffset);
785 mergeStackFrames(location.getStackFrame());
786 currentOffset += 3;
787 currentFrame = null;
788 }
789
790 /**
791 * writes a goto instruction.
792 * <p/>
793 * TODO: implemented goto_w
794 */
795 public BranchEnd gotoInstruction() {
796 writeByte(Opcode.GOTO);
797 writeShort(0);
798 currentOffset += 3;
799 BranchEnd ret = new BranchEnd(currentOffset - 2, currentFrame, currentOffset - 3);
800 currentFrame = null;
801 return ret;
802 }
803
804 public void i2b() {
805 assertTypeOnStack(StackEntryType.INT, "i2b requires int on stack");
806 writeByte(Opcode.I2B);
807 currentOffset++;
808 advanceFrame(currentFrame.replace("B"));
809 }
810
811 public void i2c() {
812 assertTypeOnStack(StackEntryType.INT, "i2c requires int on stack");
813 writeByte(Opcode.I2C);
814 currentOffset++;
815 advanceFrame(currentFrame.replace("C"));
816 }
817
818 public void i2d() {
819 assertTypeOnStack(StackEntryType.INT, "i2d requires int on stack");
820 writeByte(Opcode.I2D);
821 currentOffset++;
822 advanceFrame(currentFrame.replace("D"));
823 }
824
825 public void i2f() {
826 assertTypeOnStack(StackEntryType.INT, "i2f requires int on stack");
827 writeByte(Opcode.I2F);
828 currentOffset++;
829 advanceFrame(currentFrame.replace("F"));
830 }
831
832 public void i2l() {
833 assertTypeOnStack(StackEntryType.INT, "i2l requires int on stack");
834 writeByte(Opcode.I2L);
835 currentOffset++;
836 advanceFrame(currentFrame.replace("J"));
837 }
838
839 public void i2s() {
840 assertTypeOnStack(StackEntryType.INT, "i2s requires int on stack");
841 writeByte(Opcode.I2S);
842 currentOffset++;
843 advanceFrame(currentFrame.replace("S"));
844 }
845
846 public void iadd() {
847 assertTypeOnStack(StackEntryType.INT, "iadd requires int on stack");
848 assertTypeOnStack(1, StackEntryType.INT, "iadd requires int on stack");
849 writeByte(Opcode.IADD);
850 currentOffset++;
851 advanceFrame(currentFrame.pop());
852 }
853
854 public void iaload() {
855 assertTypeOnStack(StackEntryType.INT, "iaload requires an int on top of the stack");
856 assertTypeOnStack(1, StackEntryType.OBJECT, "iaload requires an array in position 2 on the stack");
857 writeByte(Opcode.IALOAD);
858 currentOffset++;
859 advanceFrame(currentFrame.pop2push1("I"));
860 }
861
862 public void iand() {
863 assertTypeOnStack(StackEntryType.INT, "iand requires int on stack");
864 assertTypeOnStack(1, StackEntryType.INT, "iand requires int on stack");
865 writeByte(Opcode.IAND);
866 currentOffset++;
867 advanceFrame(currentFrame.pop());
868 }
869
870 public void iastore() {
871 assertTypeOnStack(StackEntryType.INT, "iastore requires an int on top of the stack");
872 assertTypeOnStack(1, StackEntryType.INT, "iastore requires an int in position 2 on the stack");
873 assertTypeOnStack(2, StackEntryType.OBJECT, "iastore requires an array reference in position 3 on the stack");
874 writeByte(Opcode.IASTORE);
875 currentOffset++;
876 advanceFrame(currentFrame.pop3());
877 }
878
879 /**
880 * Adds the appropriate iconst instruction.
881 * <p/>
882 * note, if the value is not in the range -1 to 5 ldc is written instead
883 *
884 * @param value
885 */
886 public void iconst(int value) {
887 if (value < -1 || value > 5) {
888 if (value < -128 || value > 127) {
889 ldc(value);
890 } else {
891 writeByte(Opcode.BIPUSH);
892 writeByte(value);
893 currentOffset += 2;
894 advanceFrame(currentFrame.push("I"));
895 }
896 return;
897 }
898 writeByte(Opcode.ICONST_0 + value);
899 currentOffset++;
900 advanceFrame(currentFrame.push("I"));
901 }
902
903 public void idiv() {
904 assertTypeOnStack(StackEntryType.INT, "idiv requires int on stack");
905 assertTypeOnStack(1, StackEntryType.INT, "idiv requires int in position 2 on stack");
906 writeByte(Opcode.IDIV);
907 currentOffset++;
908 advanceFrame(currentFrame.pop());
909 }
910
911 public void ifAcmpeq(CodeLocation location) {
912 assertTypeOnStack(StackEntryType.OBJECT, "ifAcmpeq requires reference type on stack");
913 assertTypeOnStack(1, StackEntryType.OBJECT, "ifAcmpeq requires reference type in position 2 on stack");
914 writeByte(Opcode.IF_ACMPEQ);
915 writeShort(location.getLocation() - currentOffset);
916 mergeStackFrames(location.getStackFrame());
917 currentOffset += 3;
918 advanceFrame(currentFrame.pop2());
919 }
920
921 public BranchEnd ifAcmpeq() {
922 assertTypeOnStack(StackEntryType.OBJECT, "ifAcmpeq requires reference type on stack");
923 assertTypeOnStack(1, StackEntryType.OBJECT, "ifAcmpeq requires reference type int position 2 on stack");
924 writeByte(Opcode.IF_ACMPEQ);
925 writeShort(0);
926 currentOffset += 3;
927 advanceFrame(currentFrame.pop2());
928 return new BranchEnd(currentOffset - 2, currentFrame, currentOffset - 3);
929 }
930
931 public void ifAcmpne(CodeLocation location) {
932 assertTypeOnStack(StackEntryType.OBJECT, "ifAcmpne requires reference type on stack");
933 assertTypeOnStack(1, StackEntryType.OBJECT, "ifAcmpne requires reference type in position 2 on stack");
934 writeByte(Opcode.IF_ACMPNE);
935 writeShort(location.getLocation() - currentOffset);
936 mergeStackFrames(location.getStackFrame());
937 currentOffset += 3;
938 advanceFrame(currentFrame.pop2());
939 }
940
941 public BranchEnd ifAcmpne() {
942 assertTypeOnStack(StackEntryType.OBJECT, "ifAcmpne requires reference type on stack");
943 assertTypeOnStack(1, StackEntryType.OBJECT, "ifAcmpne requires reference type int position 2 on stack");
944 writeByte(Opcode.IF_ACMPNE);
945 writeShort(0);
946 currentOffset += 3;
947 advanceFrame(currentFrame.pop2());
948 BranchEnd ret = new BranchEnd(currentOffset - 2, currentFrame, currentOffset - 3);
949 return ret;
950 }
951
952 public void ifIcmpeq(CodeLocation location) {
953 addIfIcmp(location, Opcode.IF_ICMPEQ, "ifIcmpeq");
954 }
955
956 public BranchEnd ifIcmpeq() {
957 return addIfIcmp(Opcode.IF_ICMPEQ, "ifIcmpeq");
958 }
959
960 public void ifIcmpne(CodeLocation location) {
961 addIfIcmp(location, Opcode.IF_ICMPNE, "ifIcmpne");
962 }
963
964 public BranchEnd ifIcmpne() {
965 return addIfIcmp(Opcode.IF_ICMPNE, "ifIcmpne");
966 }
967
968 public void ifIcmplt(CodeLocation location) {
969 addIfIcmp(location, Opcode.IF_ICMPLT, "ifIcmplt");
970 }
971
972 public BranchEnd ifIcmplt() {
973 return addIfIcmp(Opcode.IF_ICMPLT, "ifIcmplt");
974 }
975
976 public void ifIcmple(CodeLocation location) {
977 addIfIcmp(location, Opcode.IF_ICMPLE, "ifIcmple");
978 }
979
980 public BranchEnd ifIcmple() {
981 return addIfIcmp(Opcode.IF_ICMPLE, "ifIcmple");
982 }
983
984 public void ifIcmpgt(CodeLocation location) {
985 addIfIcmp(location, Opcode.IF_ICMPGT, "ifIcmpgt");
986 }
987
988 public BranchEnd ifIcmpgt() {
989 return addIfIcmp(Opcode.IF_ICMPGT, "ifIcmpgt");
990 }
991
992 public void ifIcmpge(CodeLocation location) {
993 addIfIcmp(location, Opcode.IF_ICMPGE, "ifIcmpge");
994 }
995
996 public BranchEnd ifIcmpge() {
997 return addIfIcmp(Opcode.IF_ICMPGE, "ifIcmpge");
998 }
999
1000 public void ifEq(CodeLocation location) {
1001 addIf(location, Opcode.IFEQ, "ifeq");
1002 }
1003
1004 public BranchEnd ifeq() {
1005 return addIf(Opcode.IFEQ, "ifeq");
1006 }
1007
1008 public void ifne(CodeLocation location) {
1009 addIf(location, Opcode.IFNE, "ifne");
1010 }
1011
1012 public BranchEnd ifne() {
1013 return addIf(Opcode.IFNE, "ifne");
1014 }
1015
1016 public void iflt(CodeLocation location) {
1017 addIf(location, Opcode.IFLT, "iflt");
1018 }
1019
1020 public BranchEnd iflt() {
1021 return addIf(Opcode.IFLT, "iflt");
1022 }
1023
1024 public void ifle(CodeLocation location) {
1025 addIf(location, Opcode.IFLE, "ifle");
1026 }
1027
1028 public BranchEnd ifle() {
1029 return addIf(Opcode.IFLE, "ifle");
1030 }
1031
1032 public void ifgt(CodeLocation location) {
1033 addIf(location, Opcode.IFGT, "ifgt");
1034 }
1035
1036 public BranchEnd ifgt() {
1037 return addIf(Opcode.IFGT, "ifgt");
1038 }
1039
1040 public void ifge(CodeLocation location) {
1041 addIf(location, Opcode.IFGE, "ifge");
1042 }
1043
1044 public BranchEnd ifge() {
1045 return addIf(Opcode.IFGE, "ifge");
1046 }
1047
1048 public void ifnotnull(CodeLocation location) {
1049 addNullComparison(location, Opcode.IFNONNULL, "ifnotnull");
1050 }
1051
1052 public BranchEnd ifnotnull() {
1053 return addNullComparison(Opcode.IFNONNULL, "ifnotnull");
1054 }
1055
1056 /**
1057 * Jump to the given location if the reference type on the top of the stack is null
1058 */
1059 public void ifnull(CodeLocation location) {
1060 addNullComparison(location, Opcode.IFNULL, "ifnull");
1061 }
1062
1063 /**
1064 * Jump to the given location if the reference type on the top of the stack is null.
1065 * <p/>
1066 * The {@link BranchEnd} returned from this method is used to set the end point to a future point in the bytecode stream
1067 */
1068 public BranchEnd ifnull() {
1069 return addNullComparison(Opcode.IFNULL, "ifnull");
1070 }
1071
1072 public void iinc(int local, int amount) {
1073 if (getLocalVars().get(local).getType() != StackEntryType.INT) {
1074 throw new InvalidBytecodeException("iinc requires int at local variable position " + local + " "
1075 + getLocalVars().toString());
1076 }
1077 if (local > 0xFF || amount > 0xFF) {
1078 writeByte(Opcode.WIDE);
1079 writeByte(Opcode.IINC);
1080 writeShort(local);
1081 writeShort(amount);
1082 currentOffset += 6;
1083 } else {
1084 writeByte(Opcode.IINC);
1085 writeByte(local);
1086 writeByte(amount);
1087 currentOffset += 3;
1088 }
1089 duplicateFrame();
1090 }
1091
1092 public void iload(int no) {
1093 LocalVariableState locals = getLocalVars();
1094 if (locals.size() <= no) {
1095 throw new InvalidBytecodeException("Cannot load variable at " + no + ". Local Variables: " + locals.toString());
1096 }
1097 StackEntry entry = locals.get(no);
1098 if (entry.getType() != StackEntryType.INT) {
1099 throw new InvalidBytecodeException("Invalid local variable at location " + no + " Local Variables "
1100 + locals.toString());
1101 }
1102
1103 if (no > 0xFF) {
1104 // wide version
1105 writeByte(Opcode.WIDE);
1106 writeByte(Opcode.ILOAD);
1107 writeShort(no);
1108 currentOffset += 4;
1109 } else if (no >= 0 && no < 4) {
1110 writeByte(Opcode.ILOAD_0 + no);
1111 currentOffset++;
1112 } else {
1113 writeByte(Opcode.ILOAD);
1114 writeByte(no);
1115 currentOffset += 2;
1116 }
1117 advanceFrame(currentFrame.push(entry));
1118 }
1119
1120 public void imul() {
1121 assertTypeOnStack(StackEntryType.INT, "imul requires int on stack");
1122 assertTypeOnStack(1, StackEntryType.INT, "imul requires int in position 2 on stack");
1123 writeByte(Opcode.IMUL);
1124 currentOffset++;
1125 advanceFrame(currentFrame.pop());
1126 }
1127
1128 public void ineg() {
1129 assertTypeOnStack(StackEntryType.INT, "ineg requires int on stack");
1130 writeByte(Opcode.INEG);
1131 currentOffset++;
1132 duplicateFrame();
1133 }
1134
1135 public void instanceofInstruction(String className) {
1136 assertTypeOnStack(StackEntryType.OBJECT, "instanceof requires an object reference on the stack");
1137 int classIndex = constPool.addClassEntry(className);
1138 writeByte(Opcode.INSTANCEOF);
1139 writeShort(classIndex);
1140 currentOffset += 3;
1141 advanceFrame(currentFrame.replace("I"));
1142 }
1143
1144 public void invokespecial(String className, String methodName, String descriptor) {
1145 String[] params = DescriptorUtils.parameterDescriptors(descriptor);
1146 String returnType = DescriptorUtils.returnType(descriptor);
1147 invokespecial(className, methodName, descriptor, returnType, params);
1148 }
1149
1150 public void invokespecial(String className, String methodName, String returnType, String[] parameterTypes) {
1151 String descriptor = DescriptorUtils.methodDescriptor(parameterTypes, returnType);
1152 invokespecial(className, methodName, descriptor, returnType, parameterTypes);
1153 }
1154
1155 public void invokespecial(Constructor<?> constructor) {
1156 invokespecial(constructor.getDeclaringClass().getName(), "<init>", DescriptorUtils
1157 .makeDescriptor(constructor), "V", DescriptorUtils.parameterDescriptors(constructor.getParameterTypes()));
1158 }
1159
1160 public void invokespecial(Method method) {
1161 if (Modifier.isStatic(method.getModifiers())) {
1162 throw new InvalidBytecodeException("Cannot use invokespacial to invoke a static method");
1163 }
1164 invokespecial(method.getDeclaringClass().getName(), method.getName(), DescriptorUtils.methodDescriptor(method),
1165 DescriptorUtils.makeDescriptor(method.getReturnType()), DescriptorUtils.parameterDescriptors(method
1166 .getParameterTypes()));
1167 }
1168
1169 private void invokespecial(String className, String methodName, String descriptor, String returnType,
1170 String[] parameterTypes) {
1171 // TODO: validate stack
1172 int method = constPool.addMethodEntry(className, methodName, descriptor);
1173 writeByte(Opcode.INVOKESPECIAL);
1174 writeShort(method);
1175 currentOffset += 3;
1176 int pop = 1 + parameterTypes.length;
1177 for (String argument : parameterTypes) {
1178 if (argument.equals("D") || argument.equals("J")) {
1179 pop++;
1180 }
1181 }
1182 if (methodName.equals("<init>")) {
1183 advanceFrame(currentFrame.constructorCall(pop - 1));
1184 } else if (returnType.equals("V")) {
1185 advanceFrame(currentFrame.pop(pop));
1186 } else {
1187 advanceFrame(currentFrame.pop(pop).push(returnType));
1188 }
1189 }
1190
1191 public void invokestatic(String className, String methodName, String descriptor) {
1192 String[] params = DescriptorUtils.parameterDescriptors(descriptor);
1193 String returnType = DescriptorUtils.returnType(descriptor);
1194 invokestatic(className, methodName, descriptor, returnType, params);
1195 }
1196
1197 public void invokestatic(String className, String methodName, String returnType, String[] parameterTypes) {
1198 String descriptor = DescriptorUtils.methodDescriptor(parameterTypes, returnType);
1199 invokestatic(className, methodName, descriptor, returnType, parameterTypes);
1200 }
1201
1202 public void invokestatic(Method method) {
1203 if (!Modifier.isStatic(method.getModifiers())) {
1204 throw new InvalidBytecodeException("Cannot use invokestatic to invoke a non static method");
1205 }
1206 invokestatic(method.getDeclaringClass().getName(), method.getName(), DescriptorUtils.methodDescriptor(method),
1207 DescriptorUtils.makeDescriptor(method.getReturnType()), DescriptorUtils.parameterDescriptors(method
1208 .getParameterTypes()));
1209 }
1210
1211 private void invokestatic(String className, String methodName, String descriptor, String returnType, String[] parameterTypes) {
1212 // TODO: validate stack
1213 int method = constPool.addMethodEntry(className, methodName, descriptor);
1214 writeByte(Opcode.INVOKESTATIC);
1215 writeShort(method);
1216 currentOffset += 3;
1217 int pop = parameterTypes.length;
1218 for (String argument : parameterTypes) {
1219 if (argument.equals("D") || argument.equals("J")) {
1220 pop++;
1221 }
1222 }
1223 if (returnType.equals("V")) {
1224 advanceFrame(currentFrame.pop(pop));
1225 } else {
1226 advanceFrame(currentFrame.pop(pop).push(returnType));
1227 }
1228 }
1229
1230 public void invokevirtual(String className, String methodName, String descriptor) {
1231 String[] params = DescriptorUtils.parameterDescriptors(descriptor);
1232 String returnType = DescriptorUtils.returnType(descriptor);
1233 invokevirtual(className, methodName, descriptor, returnType, params);
1234 }
1235
1236 public void invokevirtual(String className, String methodName, String returnType, String[] parameterTypes) {
1237 String descriptor = DescriptorUtils.methodDescriptor(parameterTypes, returnType);
1238 invokevirtual(className, methodName, descriptor, returnType, parameterTypes);
1239 }
1240
1241 public void invokevirtual(Method method) {
1242 if (Modifier.isStatic(method.getModifiers())) {
1243 throw new InvalidBytecodeException("Cannot use invokevirtual to invoke a static method");
1244 } else if (Modifier.isPrivate(method.getModifiers())) {
1245 throw new InvalidBytecodeException("Cannot use invokevirtual to invoke a private method");
1246 } else if (method.getDeclaringClass().isInterface()) {
1247 throw new InvalidBytecodeException("Cannot use invokevirtual to invoke an interface method");
1248 }
1249 invokevirtual(method.getDeclaringClass().getName(), method.getName(), DescriptorUtils.methodDescriptor(method),
1250 DescriptorUtils.makeDescriptor(method.getReturnType()), DescriptorUtils.parameterDescriptors(method
1251 .getParameterTypes()));
1252 }
1253
1254 private void invokevirtual(String className, String methodName, String descriptor, String returnType,
1255 String[] parameterTypes) {
1256 // TODO: validate stack
1257 int method = constPool.addMethodEntry(className, methodName, descriptor);
1258 writeByte(Opcode.INVOKEVIRTUAL);
1259 writeShort(method);
1260 currentOffset += 3;
1261 int pop = 1 + parameterTypes.length;
1262 for (String argument : parameterTypes) {
1263 if (argument.equals("D") || argument.equals("J")) {
1264 pop++;
1265 }
1266 }
1267 if (returnType.equals("V")) {
1268 advanceFrame(currentFrame.pop(pop));
1269 } else {
1270 advanceFrame(currentFrame.pop(pop).push(returnType));
1271 }
1272 }
1273
1274 public void invokeinterface(String className, String methodName, String descriptor) {
1275 String[] params = DescriptorUtils.parameterDescriptors(descriptor);
1276 String returnType = DescriptorUtils.returnType(descriptor);
1277 invokeinterface(className, methodName, descriptor, returnType, params);
1278 }
1279
1280 public void invokeinterface(String className, String methodName, String returnType, String[] parameterTypes) {
1281 String descriptor = DescriptorUtils.methodDescriptor(parameterTypes, returnType);
1282 invokeinterface(className, methodName, descriptor, returnType, parameterTypes);
1283 }
1284
1285 public void invokeinterface(Method method) {
1286 if (Modifier.isStatic(method.getModifiers())) {
1287 throw new InvalidBytecodeException("Cannot use invokeinterface to invoke a static method");
1288 } else if (Modifier.isPrivate(method.getModifiers())) {
1289 throw new InvalidBytecodeException("Cannot use invokeinterface to invoke a private method");
1290 } else if (!method.getDeclaringClass().isInterface()) {
1291 throw new InvalidBytecodeException("Cannot use invokeinterface to invoke a non interface method");
1292 }
1293 invokeinterface(method.getDeclaringClass().getName(), method.getName(), DescriptorUtils.methodDescriptor(method),
1294 DescriptorUtils.makeDescriptor(method.getReturnType()), DescriptorUtils.parameterDescriptors(method
1295 .getParameterTypes()));
1296 }
1297
1298 private void invokeinterface(String className, String methodName, String descriptor, String returnType,
1299 String[] parameterTypes) {
1300 // TODO: validate stack
1301
1302 int pop = 1 + parameterTypes.length;
1303 for (String argument : parameterTypes) {
1304 if (argument.equals("D") || argument.equals("J")) {
1305 pop++;
1306 }
1307 }
1308 int method = constPool.addInterfaceMethodEntry(className, methodName, descriptor);
1309 writeByte(Opcode.INVOKEINTERFACE);
1310 writeShort(method);
1311 writeByte(pop);
1312 writeByte(0);
1313 currentOffset += 5;
1314
1315 if (returnType.equals("V")) {
1316 advanceFrame(currentFrame.pop(pop));
1317 } else {
1318 advanceFrame(currentFrame.pop(pop).push(returnType));
1319 }
1320 }
1321
1322 public void ior() {
1323 assertTypeOnStack(StackEntryType.INT, "ior requires int on stack");
1324 assertTypeOnStack(1, StackEntryType.INT, "ior requires int on stack");
1325 writeByte(Opcode.IOR);
1326 currentOffset++;
1327 advanceFrame(currentFrame.pop());
1328 }
1329
1330 public void irem() {
1331 assertTypeOnStack(StackEntryType.INT, "irem requires int on stack");
1332 assertTypeOnStack(1, StackEntryType.INT, "irem requires int on stack");
1333 writeByte(Opcode.IREM);
1334 currentOffset++;
1335 advanceFrame(currentFrame.pop());
1336 }
1337
1338 public void ishl() {
1339 assertTypeOnStack(StackEntryType.INT, "ishl requires int on stack");
1340 assertTypeOnStack(1, StackEntryType.INT, "ishl requires int on stack");
1341 writeByte(Opcode.ISHL);
1342 currentOffset++;
1343 advanceFrame(currentFrame.pop());
1344 }
1345
1346 public void ishr() {
1347 assertTypeOnStack(StackEntryType.INT, "ishr requires int on stack");
1348 assertTypeOnStack(1, StackEntryType.INT, "ishr requires int on stack");
1349 writeByte(Opcode.ISHR);
1350 currentOffset++;
1351 advanceFrame(currentFrame.pop());
1352 }
1353
1354 public void istore(int no) {
1355 assertTypeOnStack(StackEntryType.INT, "istore requires int on stack");
1356 if (no > 0xFF) {
1357 // wide version
1358 writeByte(Opcode.WIDE);
1359 writeByte(Opcode.ISTORE);
1360 writeShort(no);
1361 currentOffset += 4;
1362 } else if (no >= 0 && no < 4) {
1363 writeByte(Opcode.ISTORE_0 + no);
1364 currentOffset++;
1365 } else {
1366 writeByte(Opcode.ISTORE);
1367 writeByte(no);
1368 currentOffset += 2;
1369 }
1370 advanceFrame(currentFrame.store(no));
1371 }
1372
1373 public void isub() {
1374 assertTypeOnStack(StackEntryType.INT, "isub requires int on stack");
1375 assertTypeOnStack(1, StackEntryType.INT, "isub requires int on stack");
1376 writeByte(Opcode.ISUB);
1377 currentOffset++;
1378 advanceFrame(currentFrame.pop());
1379 }
1380
1381 public void iushr() {
1382 assertTypeOnStack(StackEntryType.INT, "iushr requires int on stack");
1383 assertTypeOnStack(1, StackEntryType.INT, "iushr requires int on stack");
1384 writeByte(Opcode.IUSHR);
1385 currentOffset++;
1386 advanceFrame(currentFrame.pop());
1387 }
1388
1389 public void ixor() {
1390 assertTypeOnStack(StackEntryType.INT, "ixor requires int on stack");
1391 assertTypeOnStack(1, StackEntryType.INT, "ixor requires int on stack");
1392 writeByte(Opcode.IXOR);
1393 currentOffset++;
1394 advanceFrame(currentFrame.pop());
1395 }
1396
1397 public void l2d() {
1398 assertTypeOnStack(StackEntryType.LONG, "l2d requires long on stack");
1399 writeByte(Opcode.L2D);
1400 currentOffset++;
1401 advanceFrame(currentFrame.pop2push1("D"));
1402 }
1403
1404 public void l2f() {
1405 assertTypeOnStack(StackEntryType.LONG, "l2f requires long on stack");
1406 writeByte(Opcode.L2F);
1407 currentOffset++;
1408 advanceFrame(currentFrame.pop2push1("F"));
1409 }
1410
1411 public void l2i() {
1412 assertTypeOnStack(StackEntryType.LONG, "l2i requires long on stack");
1413 writeByte(Opcode.L2I);
1414 currentOffset++;
1415 advanceFrame(currentFrame.pop2push1("I"));
1416 }
1417
1418 public void ladd() {
1419 assertTypeOnStack(StackEntryType.LONG, "ladd requires long on stack");
1420 assertTypeOnStack(2, StackEntryType.LONG, "ladd requires long on stack");
1421 writeByte(Opcode.LADD);
1422 currentOffset++;
1423 advanceFrame(currentFrame.pop2());
1424 }
1425
1426 public void laload() {
1427 assertTypeOnStack(StackEntryType.INT, "laload requires an int on top of the stack");
1428 assertTypeOnStack(1, StackEntryType.OBJECT, "laload requires an array in position 2 on the stack");
1429 writeByte(Opcode.LALOAD);
1430 currentOffset++;
1431 advanceFrame(currentFrame.pop2push1("J"));
1432 }
1433
1434 public void land() {
1435 assertTypeOnStack(StackEntryType.LONG, "land requires long on stack");
1436 assertTypeOnStack(2, StackEntryType.LONG, "land requires long on stack");
1437 writeByte(Opcode.LAND);
1438 currentOffset++;
1439 advanceFrame(currentFrame.pop2());
1440 }
1441
1442 public void lastore() {
1443 assertTypeOnStack(StackEntryType.LONG, "lastore requires an long on top of the stack");
1444 assertTypeOnStack(2, StackEntryType.INT, "lastore requires an int in position 2 on the stack");
1445 assertTypeOnStack(3, StackEntryType.OBJECT, "lastore requires an array reference in position 3 on the stack");
1446 writeByte(Opcode.LASTORE);
1447 currentOffset++;
1448 advanceFrame(currentFrame.pop4());
1449 }
1450
1451 public void lcmp() {
1452 assertTypeOnStack(StackEntryType.LONG, "lcmp requires long on stack");
1453 assertTypeOnStack(2, StackEntryType.LONG, "lcmp requires long on stack");
1454 writeByte(Opcode.LCMP);
1455 currentOffset++;
1456 advanceFrame(currentFrame.pop4push1("I"));
1457 }
1458
1459 /**
1460 * Adds the appropriate lconst instruction.
1461 * <p/>
1462 * note, if the value is not 0 or 1 then ldc is used instead
1463 */
1464 public void lconst(long value) {
1465 if (value == 0) {
1466 writeByte(Opcode.LCONST_0);
1467 } else if (value == 1) {
1468 writeByte(Opcode.LCONST_1);
1469 } else {
1470 ldc2(value);
1471 return;
1472 }
1473 currentOffset++;
1474 advanceFrame(currentFrame.push("J"));
1475 }
1476
1477 /**
1478 * Adds an ldc instruction for an int.
1479 *
1480 * @param value The value to load
1481 */
1482 public void ldc(int value) {
1483 if (value > -2 && value < 6) {
1484 iconst(value);
1485 return;
1486 }
1487 int index = constPool.addIntegerEntry(value);
1488 ldcInternal(index);
1489 advanceFrame(currentFrame.push("I"));
1490 }
1491
1492 /**
1493 * Adds an ldc instruction for float
1494 */
1495 public void ldc(float value) {
1496 int index = constPool.addFloatEntry(value);
1497 ldcInternal(index);
1498 advanceFrame(currentFrame.push("F"));
1499 }
1500
1501 /**
1502 * Adds an ldc instruction for a String
1503 * <p/>
1504 * To load a class literal using ldc use the @{link #loadType(String)} method.
1505 */
1506 public void ldc(String value) {
1507 int index = constPool.addStringEntry(value);
1508 ldcInternal(index);
1509 advanceFrame(currentFrame.push("Ljava/lang/String;"));
1510 }
1511
1512 /**
1513 * Adds an ldc instruction for an int.
1514 */
1515 private void ldcInternal(int index) {
1516 if (index > 0xFF) {
1517 writeByte(Opcode.LDC_W);
1518 writeShort(index);
1519 currentOffset += 3;
1520 } else {
1521 writeByte(Opcode.LDC);
1522 writeByte(index);
1523 currentOffset += 2;
1524 }
1525 }
1526
1527 /**
1528 * Adds an ldc2_w instruction for double
1529 */
1530 public void ldc2(double value) {
1531 int index = constPool.addDoubleEntry(value);
1532 writeByte(Opcode.LDC2_W);
1533 writeShort(index);
1534 currentOffset += 3;
1535 advanceFrame(currentFrame.push("D"));
1536 }
1537
1538 /**
1539 * Adds an ldc2_w instruction for long
1540 */
1541 public void ldc2(long value) {
1542 int index = constPool.addLongEntry(value);
1543 writeByte(Opcode.LDC2_W);
1544 writeShort(index);
1545 currentOffset += 3;
1546 advanceFrame(currentFrame.push("J"));
1547 }
1548
1549 public void ldiv() {
1550 assertTypeOnStack(StackEntryType.LONG, "ldiv requires long on stack");
1551 assertTypeOnStack(2, StackEntryType.LONG, "ldiv requires long in position 3 on stack");
1552 writeByte(Opcode.LDIV);
1553 currentOffset++;
1554 advanceFrame(currentFrame.pop2());
1555 }
1556
1557 public void lload(int no) {
1558 LocalVariableState locals = getLocalVars();
1559 if (locals.size() <= no) {
1560 throw new InvalidBytecodeException("Cannot load variable at " + no + ". Local Variables: " + locals.toString());
1561 }
1562 StackEntry entry = locals.get(no);
1563 if (entry.getType() != StackEntryType.LONG) {
1564 throw new InvalidBytecodeException("Invalid local variable at location " + no + " Local Variables "
1565 + locals.toString());
1566 }
1567
1568 if (no > 0xFF) {
1569 // wide version
1570 writeByte(Opcode.WIDE);
1571 writeByte(Opcode.LLOAD);
1572 writeShort(no);
1573 currentOffset += 4;
1574 } else if (no >= 0 && no < 4) {
1575 writeByte(Opcode.LLOAD_0 + no);
1576 currentOffset++;
1577 } else {
1578 writeByte(Opcode.LLOAD);
1579 writeByte(no);
1580 currentOffset += 2;
1581 }
1582 advanceFrame(currentFrame.push(entry));
1583 }
1584
1585 public void lmul() {
1586 assertTypeOnStack(StackEntryType.LONG, "lmul requires long on stack");
1587 assertTypeOnStack(2, StackEntryType.LONG, "lmul requires long in position 3 on stack");
1588 writeByte(Opcode.LMUL);
1589 currentOffset++;
1590 advanceFrame(currentFrame.pop2());
1591 }
1592
1593 public void lneg() {
1594 assertTypeOnStack(StackEntryType.LONG, "lneg requires long on stack");
1595 writeByte(Opcode.LNEG);
1596 currentOffset++;
1597 duplicateFrame();
1598 }
1599
1600 /**
1601 * Generates the apprpriate load instruction for the given type
1602 *
1603 * @param type The type of variable
1604 * @param no local variable number
1605 */
1606 public void load(Class<?> type, int no) {
1607 load(DescriptorUtils.makeDescriptor(type), no);
1608 }
1609
1610 /**
1611 * Generates the apprpriate load instruction for the given type
1612 *
1613 * @param descriptor The descriptor of the variable
1614 * @param no local variable number
1615 */
1616 public void load(String descriptor, int no) {
1617 if (descriptor.length() != 1) {
1618 aload(no);
1619 } else {
1620 char type = descriptor.charAt(0);
1621 switch (type) {
1622 case 'F':
1623 fload(no);
1624 break;
1625 case 'J':
1626 lload(no);
1627 break;
1628 case 'D':
1629 dload(no);
1630 break;
1631 case 'I':
1632 case 'S':
1633 case 'B':
1634 case 'C':
1635 case 'Z':
1636 iload(no);
1637 break;
1638 default:
1639 throw new InvalidBytecodeException("Could not load primitive type: " + type);
1640 }
1641 }
1642 }
1643
1644 public void loadClass(String className) {
1645 int index = constPool.addClassEntry(className);
1646 ldcInternal(index);
1647 advanceFrame(currentFrame.push("Ljava/lang/Class;"));
1648 }
1649
1650 /**
1651 * Loads a java.lang.Class for the given descriptor into the stack.
1652 */
1653 public void loadType(String descriptor) {
1654 if (descriptor.length() != 1) {
1655 if (descriptor.startsWith("L") && descriptor.endsWith(";")) {
1656 descriptor = descriptor.substring(1, descriptor.length() - 1);
1657 }
1658 loadClass(descriptor);
1659 } else {
1660 char type = descriptor.charAt(0);
1661 switch (type) {
1662 case 'I':
1663 getstatic(Integer.class.getName(), "TYPE", "Ljava/lang/Class;");
1664 break;
1665 case 'J':
1666 getstatic(Long.class.getName(), "TYPE", "Ljava/lang/Class;");
1667 break;
1668 case 'S':
1669 getstatic(Short.class.getName(), "TYPE", "Ljava/lang/Class;");
1670 break;
1671 case 'F':
1672 getstatic(Float.class.getName(), "TYPE", "Ljava/lang/Class;");
1673 break;
1674 case 'D':
1675 getstatic(Double.class.getName(), "TYPE", "Ljava/lang/Class;");
1676 break;
1677 case 'B':
1678 getstatic(Byte.class.getName(), "TYPE", "Ljava/lang/Class;");
1679 break;
1680 case 'C':
1681 getstatic(Character.class.getName(), "TYPE", "Ljava/lang/Class;");
1682 break;
1683 case 'Z':
1684 getstatic(Boolean.class.getName(), "TYPE", "Ljava/lang/Class;");
1685 break;
1686 case 'V':
1687 getstatic(Void.class.getName(), "TYPE", "Ljava/lang/Class;");
1688 break;
1689 default:
1690 throw new InvalidBytecodeException("Unkown primitive type: " + type);
1691 }
1692 }
1693 }
1694
1695 /**
1696 * Adds a lookup switch statement
1697 *
1698 * @param lookupSwitchBuilder
1699 * @return
1700 */
1701 public void lookupswitch(final LookupSwitchBuilder lookupSwitchBuilder) {
1702 assertTypeOnStack(StackEntryType.INT, "lookupswitch requires an int on the stack");
1703 writeByte(Opcode.LOOKUPSWITCH);
1704 final int startOffset = currentOffset;
1705 currentOffset++;
1706 while (currentOffset % 4 != 0) {
1707 writeByte(0);
1708 currentOffset++;
1709 }
1710
1711 StackFrame frame = currentFrame.pop();
1712
1713 final List<LookupSwitchBuilder.ValuePair> values = new ArrayList<LookupSwitchBuilder.ValuePair>(lookupSwitchBuilder.getValues());
1714
1715 if (lookupSwitchBuilder.getDefaultLocation() != null) {
1716 writeInt(lookupSwitchBuilder.getDefaultLocation().getLocation() - currentOffset);
1717 } else {
1718 writeInt(0);
1719 final BranchEnd ret = new BranchEnd(currentOffset, frame, true, startOffset);
1720 lookupSwitchBuilder.getDefaultBranchEnd().set(ret);
1721 }
1722 writeInt(values.size());
1723 currentOffset += 8;
1724 Collections.sort(values);
1725 for (final LookupSwitchBuilder.ValuePair value : values) {
1726 writeInt(value.getValue());
1727 currentOffset += 4;
1728 if (value.getLocation() != null) {
1729 writeInt(value.getLocation().getLocation());
1730 currentOffset += 4;
1731 } else {
1732 writeInt(0);
1733 final BranchEnd ret = new BranchEnd(currentOffset, frame, true, startOffset);
1734 value.getBranchEnd().set(ret);
1735 currentOffset += 4;
1736 }
1737 }
1738 currentFrame = null;
1739 }
1740
1741 public void lor() {
1742 assertTypeOnStack(StackEntryType.LONG, "lor requires long on stack");
1743 assertTypeOnStack(2, StackEntryType.LONG, "lor requires long in position 3 on stack");
1744 writeByte(Opcode.LOR);
1745 currentOffset++;
1746 advanceFrame(currentFrame.pop2());
1747 }
1748
1749 public void lrem() {
1750 assertTypeOnStack(StackEntryType.LONG, "lrem requires long on stack");
1751 assertTypeOnStack(2, StackEntryType.LONG, "lrem requires long in position 3 on stack");
1752 writeByte(Opcode.LREM);
1753 currentOffset++;
1754 advanceFrame(currentFrame.pop2());
1755 }
1756
1757 public void lshl() {
1758 assertTypeOnStack(StackEntryType.INT, "lshl requires int on stack");
1759 assertTypeOnStack(1, StackEntryType.LONG, "lshl requires long in position 2 on stack");
1760 writeByte(Opcode.LSHL);
1761 currentOffset++;
1762 advanceFrame(currentFrame.pop());
1763 }
1764
1765 public void lshr() {
1766 assertTypeOnStack(StackEntryType.INT, "lshr requires int on stack");
1767 assertTypeOnStack(1, StackEntryType.LONG, "lshr requires long in position 2 on stack");
1768 writeByte(Opcode.LSHR);
1769 currentOffset++;
1770 advanceFrame(currentFrame.pop());
1771 }
1772
1773 public void lstore(int no) {
1774 assertTypeOnStack(StackEntryType.LONG, "lstore requires long on stack");
1775 if (no > 0xFF) {
1776 // wide version
1777 writeByte(Opcode.WIDE);
1778 writeByte(Opcode.LSTORE);
1779 writeShort(no);
1780 currentOffset += 4;
1781 } else if (no >= 0 && no < 4) {
1782 writeByte(Opcode.LSTORE_0 + no);
1783 currentOffset++;
1784 } else {
1785 writeByte(Opcode.LSTORE);
1786 writeByte(no);
1787 currentOffset += 2;
1788 }
1789 advanceFrame(currentFrame.store(no));
1790 }
1791
1792 public void lsub() {
1793 assertTypeOnStack(StackEntryType.LONG, "lsub requires long on stack");
1794 assertTypeOnStack(2, StackEntryType.LONG, "lsub requires long in position 3 on stack");
1795 writeByte(Opcode.LSUB);
1796 currentOffset++;
1797 advanceFrame(currentFrame.pop2());
1798 }
1799
1800 public void lushr() {
1801 assertTypeOnStack(StackEntryType.INT, "lushr requires int on stack");
1802 assertTypeOnStack(1, StackEntryType.LONG, "lushr requires long in position 2 on stack");
1803 writeByte(Opcode.LUSHR);
1804 currentOffset++;
1805 advanceFrame(currentFrame.pop());
1806 }
1807
1808 public void lxor() {
1809 assertTypeOnStack(StackEntryType.LONG, "lxor requires long on stack");
1810 assertTypeOnStack(2, StackEntryType.LONG, "lxor requires long in position 3 on stack");
1811 writeByte(Opcode.LXOR);
1812 currentOffset++;
1813 advanceFrame(currentFrame.pop2());
1814 }
1815
1816 /**
1817 * Gets the location object for the current location in the bytecode. Jumps to this location will begin executing the next
1818 * instruction that is written to the bytecode stream
1819 */
1820 public CodeLocation mark() {
1821 return new CodeLocation(currentOffset, currentFrame);
1822 }
1823
1824 public void monitorenter() {
1825 assertTypeOnStack(StackEntryType.OBJECT, "monitorenter requires object reference on stack");
1826 writeByte(Opcode.MONITORENTER);
1827 currentOffset++;
1828 advanceFrame(currentFrame.pop());
1829 }
1830
1831 public void monitorexit() {
1832 assertTypeOnStack(StackEntryType.OBJECT, "monitorexit requires object reference on stack");
1833 writeByte(Opcode.MONITOREXIT);
1834 currentOffset++;
1835 advanceFrame(currentFrame.pop());
1836 }
1837
1838 public void multianewarray(String arrayType, int dimensions) {
1839 StringBuilder newType = new StringBuilder();
1840 for (int i = 0; i < dimensions; ++i) {
1841 assertTypeOnStack(i, StackEntryType.INT, "multianewarray requires int on stack in position " + i);
1842 newType.append('[');
1843 }
1844 if (!arrayType.startsWith("[")) {
1845 newType.append('L');
1846 newType.append(arrayType.replace('.', '/'));
1847 newType.append(";");
1848 } else {
1849 newType.append(arrayType);
1850 }
1851 int classIndex = constPool.addClassEntry(newType.toString());
1852 writeByte(Opcode.MULTIANEWARRAY);
1853 writeShort(classIndex);
1854 writeByte(dimensions);
1855 currentOffset += 4;
1856
1857 advanceFrame(currentFrame.pop(dimensions).push(newType.toString()));
1858 }
1859
1860 public void newInstruction(String classname) {
1861 int classIndex = constPool.addClassEntry(classname);
1862 writeByte(Opcode.NEW);
1863 writeShort(classIndex);
1864 StackEntry entry = new StackEntry(StackEntryType.UNITITIALIZED_OBJECT, DescriptorUtils.makeDescriptor(classname), currentOffset);
1865 currentOffset += 3;
1866 advanceFrame(currentFrame.push(entry));
1867 }
1868
1869 public void newInstruction(Class<?> clazz) {
1870 newInstruction(clazz.getName());
1871 }
1872
1873 /**
1874 * arrayType must be a {@link Class} object that represents a primitive type
1875 */
1876 public void newarray(Class<?> arrayType) {
1877 assertTypeOnStack(StackEntryType.INT, "newarray requires int on stack");
1878 int type;
1879 String desc;
1880 if (arrayType == boolean.class) {
1881 type = Opcode.T_BOOLEAN;
1882 desc = "[Z";
1883 } else if (arrayType == char.class) {
1884 type = Opcode.T_CHAR;
1885 desc = "[C";
1886 } else if (arrayType == float.class) {
1887 type = Opcode.T_FLOAT;
1888 desc = "[F";
1889 } else if (arrayType == double.class) {
1890 type = Opcode.T_DOUBLE;
1891 desc = "[D";
1892 } else if (arrayType == byte.class) {
1893 type = Opcode.T_BYTE;
1894 desc = "[B";
1895 } else if (arrayType == short.class) {
1896 type = Opcode.T_SHORT;
1897 desc = "[S";
1898 } else if (arrayType == int.class) {
1899 type = Opcode.T_INT;
1900 desc = "[I";
1901 } else if (arrayType == long.class) {
1902 type = Opcode.T_LONG;
1903 desc = "[J";
1904 } else {
1905 throw new InvalidBytecodeException("Class " + arrayType + " is not a primitive type");
1906 }
1907 writeByte(Opcode.NEWARRAY);
1908 writeByte(type);
1909 currentOffset += 2;
1910 advanceFrame(currentFrame.replace(desc));
1911 }
1912
1913 public void nop() {
1914 writeByte(Opcode.NOP);
1915 currentOffset++;
1916 duplicateFrame();
1917 }
1918
1919 public void pop() {
1920 writeByte(Opcode.POP);
1921 currentOffset++;
1922 advanceFrame(currentFrame.pop());
1923 }
1924
1925 public void pop2() {
1926 writeByte(Opcode.POP2);
1927 currentOffset++;
1928 advanceFrame(currentFrame.pop2());
1929 }
1930
1931 public void putfield(String className, String field, Class<?> fieldType) {
1932 putfield(className, field, DescriptorUtils.makeDescriptor(fieldType));
1933 }
1934
1935 public void putfield(String className, String field, String descriptor) {
1936 if (!getStack().isOnTop(descriptor)) {
1937 throw new InvalidBytecodeException("Attempting to put wrong type into field. Field:" + className + "."
1938 + field + " (" + descriptor + "). Stack State: " + getStack().toString());
1939 }
1940 if (getStack().top_1().getType() != StackEntryType.UNINITIALIZED_THIS) {
1941 assertTypeOnStack(1, StackEntryType.OBJECT, "expected object in position 2 on stack");
1942 }
1943 int index = constPool.addFieldEntry(className, field, descriptor);
1944 writeByte(Opcode.PUTFIELD);
1945 writeShort(index);
1946 currentOffset += 3;
1947 advanceFrame(currentFrame.pop2());
1948 }
1949
1950 public void putstatic(String className, String field, Class<?> fieldType) {
1951 putstatic(className, field, DescriptorUtils.makeDescriptor(fieldType));
1952 }
1953
1954 public void putstatic(String className, String field, String descriptor) {
1955 if (!getStack().isOnTop(descriptor)) {
1956 throw new InvalidBytecodeException("Attempting to put wrong type into static field. Field:" + className + "."
1957 + field + " (" + descriptor + "). Stack State: " + getStack().toString());
1958 }
1959 int index = constPool.addFieldEntry(className, field, descriptor);
1960 writeByte(Opcode.PUTSTATIC);
1961 writeShort(index);
1962 currentOffset += 3;
1963 advanceFrame(currentFrame.pop());
1964 }
1965
1966 /**
1967 * Adds the appropriate return instruction for the methods return type.
1968 */
1969 public void returnInstruction() {
1970 String returnType = method.getReturnType();
1971 if (!returnType.equals("V")) {
1972 if (!getStack().isOnTop(returnType)) {
1973 throw new InvalidBytecodeException(returnType + " is not on top of stack. " + getStack().toString());
1974 }
1975 }
1976
1977 // all these instructions are one byte
1978 currentOffset++;
1979
1980 // return instructions do not create stack map entries
1981
1982 if (returnType.length() > 1) {
1983 writeByte(Opcode.ARETURN);
1984 } else {
1985 char ret = method.getReturnType().charAt(0);
1986 switch (ret) {
1987 case 'V':
1988 writeByte(Opcode.RETURN);
1989 break;
1990 case 'I':
1991 case 'Z':
1992 case 'S':
1993 case 'B':
1994 case 'C':
1995 writeByte(Opcode.IRETURN);
1996 break;
1997 case 'F':
1998 writeByte(Opcode.FRETURN);
1999 break;
2000 case 'D':
2001 writeByte(Opcode.DRETURN);
2002 break;
2003 case 'J':
2004 writeByte(Opcode.LRETURN);
2005 }
2006 }
2007 currentFrame = null;
2008 }
2009
2010 public void saload() {
2011 assertTypeOnStack(StackEntryType.INT, "saload requires an int on top of the stack");
2012 assertTypeOnStack(1, StackEntryType.OBJECT, "saload requires an array in position 2 on the stack");
2013 writeByte(Opcode.SALOAD);
2014 currentOffset++;
2015 advanceFrame(currentFrame.pop2push1("I"));
2016 }
2017
2018 public void sastore() {
2019 assertTypeOnStack(StackEntryType.INT, "sastore requires an int on top of the stack");
2020 assertTypeOnStack(1, StackEntryType.INT, "sastore requires an int in position 2 on the stack");
2021 assertTypeOnStack(2, StackEntryType.OBJECT, "sastore requires an array reference in position 3 on the stack");
2022 writeByte(Opcode.SASTORE);
2023 currentOffset++;
2024 advanceFrame(currentFrame.pop3());
2025 }
2026
2027 public void sipush(short value) {
2028 writeByte(Opcode.SIPUSH);
2029 writeShort(value);
2030 currentOffset += 3;
2031 advanceFrame(currentFrame.push("S"));
2032 }
2033
2034 public void swap() {
2035 assertNotWideOnStack("swap cannot be used when wide type is on top of stack");
2036 assertNotWideOnStack(1, "swap cannot be used when wide type is on position 1 of the stack");
2037 writeByte(Opcode.SWAP);
2038 currentOffset++;
2039 advanceFrame(currentFrame.swap());
2040 }
2041
2042 public void tableswitch(final TableSwitchBuilder builder) {
2043 assertTypeOnStack(StackEntryType.INT, "lookupswitch requires an int on the stack");
2044 writeByte(Opcode.TABLESWITCH);
2045 final int startOffset = currentOffset;
2046 currentOffset++;
2047 while (currentOffset % 4 != 0) {
2048 writeByte(0);
2049 currentOffset++;
2050 }
2051
2052 if (builder.getHigh() - builder.getLow() + 1 != builder.getValues().size()) {
2053 throw new RuntimeException("high - low + 1 != the number of values in the table");
2054 }
2055
2056 StackFrame frame = currentFrame.pop();
2057
2058 if (builder.getDefaultLocation() != null) {
2059 writeInt(builder.getDefaultLocation().getLocation() - currentOffset);
2060 } else {
2061 writeInt(0);
2062 final BranchEnd ret = new BranchEnd(currentOffset, frame, true, startOffset);
2063 builder.getDefaultBranchEnd().set(ret);
2064 }
2065 writeInt(builder.getLow());
2066 writeInt(builder.getHigh());
2067 currentOffset += 12;
2068 for (final TableSwitchBuilder.ValuePair value : builder.getValues()) {
2069 if (value.getLocation() != null) {
2070 writeInt(value.getLocation().getLocation());
2071 currentOffset += 4;
2072 } else {
2073 writeInt(0);
2074 final BranchEnd ret = new BranchEnd(currentOffset, frame, true, startOffset);
2075 value.getBranchEnd().set(ret);
2076 currentOffset += 4;
2077 }
2078 }
2079 currentFrame = null;
2080 }
2081
2082 /**
2083 * loads all parameters onto the stack.
2084 * <p/>
2085 * If this method is non-static then the parameter at location 0 (i.e. this object) is not pushed.
2086 */
2087 public void loadMethodParameters() {
2088 int index = method.isStatic() ? 0 : 1;
2089 for (String type : method.getParameters()) {
2090 if (type.length() > 1) {
2091 // object or array
2092 aload(index);
2093 } else if (type.equals("D")) {
2094 dload(index);
2095 index++;
2096 } else if (type.equals("J")) {
2097 lload(index);
2098 index++;
2099 } else if (type.equals("F")) {
2100 fload(index);
2101 } else {
2102 iload(index);
2103 }
2104 index++;
2105 }
2106 }
2107
2108 private void writeByte(int n) {
2109 try {
2110 data.writeByte(n);
2111 } catch (IOException e) {
2112 throw new RuntimeException(e);
2113 }
2114 }
2115
2116 private void writeShort(int n) {
2117 try {
2118 if (n > Short.MAX_VALUE * 2) {
2119 throw new RuntimeException(n + " is to big to be written as a 16 bit value");
2120 }
2121 data.writeShort(n);
2122 } catch (IOException e) {
2123 throw new RuntimeException(e);
2124 }
2125 }
2126
2127 private void writeInt(int n) {
2128 try {
2129 data.writeInt(n);
2130 } catch (IOException e) {
2131 throw new RuntimeException(e);
2132 }
2133 }
2134
2135 /**
2136 * overwrites a 16 bit value in the already written bytecode data
2137 */
2138 private void overwriteShort(byte[] bytecode, int offset, int value) {
2139 bytecode[offset] = (byte) (value >> 8);
2140 bytecode[offset + 1] = (byte) (value);
2141 }
2142
2143 /**
2144 * overwrites a 32 bit value in the already written bytecode data
2145 */
2146 private void overwriteInt(byte[] bytecode, int offset, int value) {
2147 bytecode[offset] = (byte) (value >> 24);
2148 bytecode[offset + 1] = (byte) (value >> 16);
2149 bytecode[offset + 2] = (byte) (value >> 8);
2150 bytecode[offset + 3] = (byte) (value);
2151 }
2152
2153 public LinkedHashMap<Integer, StackFrame> getStackFrames() {
2154 return new LinkedHashMap<Integer, StackFrame>(stackFrames);
2155 }
2156
2157 public void setupFrame(String... types) {
2158 final LocalVariableState localVariableState = new LocalVariableState(constPool, types);
2159 final StackFrame f = new StackFrame(new StackState(constPool), localVariableState, StackFrameType.FULL_FRAME);
2160 mergeStackFrames(f);
2161 }
2162
2163 public ConstPool getConstPool() {
2164 return constPool;
2165 }
2166
2167 /**
2168 * Adds a duplicate of the current frame to the current position.
2169 * <p/>
2170 * currently this just puts the same frame into a different position
2171 */
2172 private void duplicateFrame() {
2173 stackFrames.put(currentOffset, currentFrame);
2174 updateMaxValues();
2175 }
2176
2177 private void advanceFrame(StackFrame frame) {
2178 stackFrames.put(currentOffset, frame);
2179 currentFrame = frame;
2180 updateMaxValues();
2181 }
2182
2183 private void updateMaxValues() {
2184 if (getStack().getContents().size() > maxStackDepth) {
2185 maxStackDepth = getStack().getContents().size();
2186 }
2187 if (getLocalVars().getContents().size() > maxLocals) {
2188 maxLocals = getLocalVars().getContents().size();
2189 }
2190 }
2191
2192 private LocalVariableState getLocalVars() {
2193 if (currentFrame == null) {
2194 throw new RuntimeException("No local variable information available, call setupFrame first");
2195 }
2196 return currentFrame.getLocalVariableState();
2197 }
2198
2199 private StackState getStack() {
2200 return currentFrame.getStackState();
2201 }
2202
2203 public void assertTypeOnStack(int position, StackEntryType type, String message) {
2204 if (getStack().size() <= position) {
2205 throw new InvalidBytecodeException(message + " Stack State: " + getStack().toString());
2206 }
2207 int index = getStack().getContents().size() - 1 - position;
2208 if (type == StackEntryType.DOUBLE || type == StackEntryType.LONG) {
2209 index -= 1;
2210 }
2211 StackEntryType stype = getStack().getContents().get(index).getType();
2212 if (stype != type) {
2213 if (!(type == StackEntryType.OBJECT && stype == StackEntryType.NULL)) {
2214 throw new InvalidBytecodeException(message + " Stack State: " + getStack().toString());
2215 }
2216 }
2217 }
2218
2219 public void assertTypeOnStack(StackEntryType type, String message) {
2220 assertTypeOnStack(0, type, message);
2221 }
2222
2223 public void assertNotWideOnStack(int position, String message) {
2224 if (getStack().size() <= position) {
2225 throw new InvalidBytecodeException(message + " Stack State: " + getStack().toString());
2226 }
2227 int index = getStack().getContents().size() - 1 - position;
2228
2229 StackEntryType stype = getStack().getContents().get(index).getType();
2230 if (stype == StackEntryType.TOP) {
2231 throw new InvalidBytecodeException(message + " Stack State: " + getStack().toString());
2232 }
2233 }
2234
2235 public void assertNotWideOnStack(String message) {
2236 assertNotWideOnStack(0, message);
2237 }
2238
2239 /**
2240 * Merge the stack frames.
2241 * <p/>
2242 * If the frames are incompatible then an {@link InvalidBytecodeException} is thrown. If the frames cannot be properly
2243 * merged then the stack map is marked as invalid
2244 */
2245 private void mergeStackFrames(StackFrame stackFrame) {
2246 if (currentFrame == null) {
2247 currentFrame = stackFrame;
2248 stackFrames.put(currentOffset, currentFrame);
2249 return;
2250 }
2251 StackState currentStackState = getStack();
2252 StackState mergeStackState = stackFrame.getStackState();
2253 if (currentStackState.size() != mergeStackState.size()) {
2254 throw new InvalidBytecodeException("Cannot merge stack frames, different stack sizes " + currentFrame + " " + stackFrame);
2255 }
2256 for (int i = 0; i < mergeStackState.size(); ++i) {
2257 StackEntry currentEntry = currentStackState.getContents().get(i);
2258 StackEntry mergeEntry = mergeStackState.getContents().get(i);
2259 if (mergeEntry.getType() == currentEntry.getType()) {
2260 if (mergeEntry.getType() == StackEntryType.OBJECT) {
2261 if (!mergeEntry.getDescriptor().equals(currentEntry.getDescriptor())) {
2262 if (method.getClassFile().getClassLoader() != null) {
2263 String superType = findSuperType(mergeEntry.getDescriptor(), currentEntry.getDescriptor());
2264 if (superType == null) {
2265 throw new InvalidBytecodeException("Could not find common supertype for " + mergeEntry.getDescriptor() + " and " + currentEntry.getDescriptor() + " " + currentFrame + " " + stackFrame);
2266 } else if (!superType.equals(currentEntry.getDescriptor())) {
2267 stackFrames.put(currentOffset, currentFrame = currentFrame.mergeStack(i, new StackEntry(StackEntryType.OBJECT, DescriptorUtils.makeDescriptor(superType), constPool)));
2268 }
2269 }
2270 }
2271 }
2272 } else if (!((mergeEntry.getType() == StackEntryType.NULL && currentEntry.getType() == StackEntryType.OBJECT) || (mergeEntry
2273 .getType() == StackEntryType.OBJECT && currentEntry.getType() == StackEntryType.NULL))) {
2274 throw new InvalidBytecodeException("Cannot merge stack frame " + currentStackState + " with frame "
2275 + mergeStackState + " stack entry " + i + " is invalid " + currentFrame + " " + stackFrame);
2276 }
2277 }
2278
2279 LocalVariableState currentLocalVariableState = getLocalVars();
2280 LocalVariableState mergeLocalVariableState = stackFrame.getLocalVariableState();
2281 if (currentLocalVariableState.size() < mergeLocalVariableState.size()) {
2282 throw new InvalidBytecodeException(
2283 "Cannot merge stack frames, merge location has less locals than current location " + currentFrame + " " + stackFrame);
2284 }
2285 for (int i = 0; i < mergeLocalVariableState.size(); ++i) {
2286 StackEntry currentEntry = currentLocalVariableState.getContents().get(i);
2287 StackEntry mergeEntry = mergeLocalVariableState.getContents().get(i);
2288 if (mergeEntry.getType() == currentEntry.getType()) {
2289 if (mergeEntry.getType() == StackEntryType.OBJECT) {
2290 if (!mergeEntry.getDescriptor().equals(currentEntry.getDescriptor())) {
2291
2292 if (!mergeEntry.getDescriptor().equals(currentEntry.getDescriptor())) {
2293 if (method.getClassFile().getClassLoader() != null) {
2294 String superType = findSuperType(mergeEntry.getDescriptor(), currentEntry.getDescriptor());
2295 if (superType == null) {
2296 throw new InvalidBytecodeException("Could not find common supertype for " + mergeEntry.getDescriptor() + " and " + currentEntry.getDescriptor() + " " + currentFrame + " " + stackFrame);
2297 } else if (!superType.equals(currentEntry.getDescriptor())) {
2298 stackFrames.put(currentOffset, currentFrame = currentFrame.mergeLocals(i, new StackEntry(StackEntryType.OBJECT, DescriptorUtils.makeDescriptor(superType), constPool)));
2299 }
2300 }
2301 }
2302 }
2303 }
2304 } else if (!((mergeEntry.getType() == StackEntryType.NULL && currentEntry.getType() == StackEntryType.OBJECT) || (mergeEntry
2305 .getType() == StackEntryType.OBJECT && currentEntry.getType() == StackEntryType.NULL))) {
2306 throw new InvalidBytecodeException("Cannot merge stack frame " + currentLocalVariableState + " with frame "
2307 + currentLocalVariableState + " local variable entry " + i + " is invalid " + currentFrame + " " + stackFrame);
2308 }
2309 }
2310 }
2311
2312 private String findSuperType(String ds1, String ds2) {
2313 String d1 = ds1;
2314 if (ds1.endsWith(";")) {
2315 d1 = ds1.substring(1, ds1.length() - 1).replace("/", ".");
2316 }
2317 String d2 = ds2;
2318 if (ds2.endsWith(";")) {
2319 d2 = ds2.substring(1, ds2.length() - 1).replace("/", ".");
2320 }
2321 if (stackFrameTypeResolver != null) {
2322 return stackFrameTypeResolver.resolve(method.getClassFile().getClassLoader(), d1, d2);
2323 }
2324 //just load the classes for now
2325 ClassLoader cl = method.getClassFile().getClassLoader();
2326 try {
2327 Class<?> c1 = cl.loadClass(d1);
2328 Class<?> c2 = cl.loadClass(d2);
2329 if (c1.isAssignableFrom(c2)) {
2330 return c1.getName();
2331 } else if (c2.isAssignableFrom(c1)) {
2332 return c2.getName();
2333 } else {
2334 Class<?> p = c1;
2335 while (p != Object.class) {
2336 if (p.isAssignableFrom(c2)) {
2337 return p.getName();
2338 }
2339 p = p.getSuperclass();
2340 }
2341 p = c2;
2342 while (p != Object.class) {
2343 if (p.isAssignableFrom(c1)) {
2344 return p.getName();
2345 }
2346 p = p.getSuperclass();
2347 }
2348
2349 Set<Class<?>> s1 = getAllSuperclassesAndInterface(c1, new HashSet<Class<?>>());
2350 Set<Class<?>> s2 = getAllSuperclassesAndInterface(c2, new HashSet<Class<?>>());
2351 leavesOnly(s1);
2352 leavesOnly(s2);
2353 Set<Class<?>> interfaces = new HashSet<Class<?>>();
2354 interfaces.addAll(s1);
2355 interfaces.addAll(s2);
2356 interfaces.remove(c1);
2357 interfaces.remove(c2);
2358 if (interfaces.size() == 1) {
2359 return interfaces.iterator().next().getName();
2360 } else if (interfaces.size() > 1) {
2361 throw new RuntimeException("Could not resolve common superclass for " + d1 + " and " + d2);
2362 } else {
2363 return Object.class.getName();
2364 }
2365 }
2366 } catch (ClassNotFoundException e) {
2367 return null;
2368 }
2369 }
2370
2371 private void leavesOnly(Set<Class<?>> s2) {
2372 List<Class<?>> keys = new ArrayList<Class<?>>(s2);
2373 for (Class<?> key : keys) {
2374 for (Class<?> content : s2) {
2375 if (key == content) {
2376 continue;
2377 }
2378 if (key.isAssignableFrom(content)) {
2379 s2.remove(key);
2380 break;
2381 }
2382 }
2383 }
2384 }
2385
2386 private Set<Class<?>> getAllSuperclassesAndInterface(Class<?> c, Set<Class<?>> set) {
2387 set.addAll(Arrays.asList(c.getInterfaces()));
2388 set.add(c);
2389 if (c.getSuperclass() != null) {
2390 getAllSuperclassesAndInterface(c.getSuperclass(), set);
2391 }
2392 return set;
2393 }
2394
2395 private void addIfIcmp(CodeLocation location, int opcode, String name) {
2396 assertTypeOnStack(StackEntryType.INT, name + " requires int on stack");
2397 assertTypeOnStack(1, StackEntryType.INT, name + " requires int in position 2 on stack");
2398 writeByte(opcode);
2399 writeShort(location.getLocation() - currentOffset);
2400 currentOffset += 3;
2401 advanceFrame(currentFrame.pop2());
2402 mergeStackFrames(location.getStackFrame());
2403 }
2404
2405 private BranchEnd addIfIcmp(int opcode, String name) {
2406 assertTypeOnStack(StackEntryType.INT, name + " requires int on stack");
2407 assertTypeOnStack(1, StackEntryType.INT, name + " requires int int position 2 on stack");
2408 writeByte(opcode);
2409 writeShort(0);
2410 currentOffset += 3;
2411 advanceFrame(currentFrame.pop2());
2412 BranchEnd ret = new BranchEnd(currentOffset - 2, currentFrame, currentOffset - 3);
2413 return ret;
2414 }
2415
2416 private void addIf(CodeLocation location, int opcode, String name) {
2417 assertTypeOnStack(StackEntryType.INT, name + " requires int on stack");
2418 writeByte(opcode);
2419 writeShort(location.getLocation() - currentOffset);
2420 currentOffset += 3;
2421 advanceFrame(currentFrame.pop());
2422 mergeStackFrames(location.getStackFrame());
2423 }
2424
2425 private BranchEnd addIf(int opcode, String name) {
2426 assertTypeOnStack(StackEntryType.INT, name + " requires int on stack");
2427 writeByte(opcode);
2428 writeShort(0);
2429 currentOffset += 3;
2430 advanceFrame(currentFrame.pop());
2431 return new BranchEnd(currentOffset - 2, currentFrame, currentOffset - 3);
2432 }
2433
2434 private void addNullComparison(CodeLocation location, int opcode, String name) {
2435 assertTypeOnStack(StackEntryType.OBJECT, name + " requires reference type on stack");
2436 writeByte(opcode);
2437 writeShort(location.getLocation() - currentOffset);
2438 currentOffset += 3;
2439 advanceFrame(currentFrame.pop());
2440 mergeStackFrames(location.getStackFrame());
2441 }
2442
2443 private BranchEnd addNullComparison(int opcode, String name) {
2444 assertTypeOnStack(StackEntryType.OBJECT, name + " requires reference type on stack");
2445 writeByte(opcode);
2446 writeShort(0);
2447 currentOffset += 3;
2448 advanceFrame(currentFrame.pop());
2449 return new BranchEnd(currentOffset - 2, currentFrame, currentOffset - 3);
2450 }
2451
2452 /**
2453 * Interface that can be used to override the type merging process when merging stack frames
2454 */
2455 public interface StackFrameTypeResolver {
2456 String resolve(ClassLoader classLoader, String type1, String type2);
2457 }
2458 }