1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.bcel.verifier.statics;
20
21 import java.util.Arrays;
22 import java.util.HashSet;
23 import java.util.Set;
24
25 import org.apache.bcel.Const;
26 import org.apache.bcel.Repository;
27 import org.apache.bcel.classfile.Attribute;
28 import org.apache.bcel.classfile.ClassFormatException;
29 import org.apache.bcel.classfile.Code;
30 import org.apache.bcel.classfile.CodeException;
31 import org.apache.bcel.classfile.Constant;
32 import org.apache.bcel.classfile.ConstantCP;
33 import org.apache.bcel.classfile.ConstantClass;
34 import org.apache.bcel.classfile.ConstantDouble;
35 import org.apache.bcel.classfile.ConstantDynamic;
36 import org.apache.bcel.classfile.ConstantFieldref;
37 import org.apache.bcel.classfile.ConstantFloat;
38 import org.apache.bcel.classfile.ConstantInteger;
39 import org.apache.bcel.classfile.ConstantInterfaceMethodref;
40 import org.apache.bcel.classfile.ConstantInvokeDynamic;
41 import org.apache.bcel.classfile.ConstantLong;
42 import org.apache.bcel.classfile.ConstantMethodref;
43 import org.apache.bcel.classfile.ConstantNameAndType;
44 import org.apache.bcel.classfile.ConstantString;
45 import org.apache.bcel.classfile.ConstantUtf8;
46 import org.apache.bcel.classfile.Field;
47 import org.apache.bcel.classfile.JavaClass;
48 import org.apache.bcel.classfile.LineNumber;
49 import org.apache.bcel.classfile.LineNumberTable;
50 import org.apache.bcel.classfile.LocalVariableTable;
51 import org.apache.bcel.classfile.Method;
52 import org.apache.bcel.generic.ALOAD;
53 import org.apache.bcel.generic.ANEWARRAY;
54 import org.apache.bcel.generic.ASTORE;
55 import org.apache.bcel.generic.ATHROW;
56 import org.apache.bcel.generic.ArrayType;
57 import org.apache.bcel.generic.BREAKPOINT;
58 import org.apache.bcel.generic.CHECKCAST;
59 import org.apache.bcel.generic.ConstantPoolGen;
60 import org.apache.bcel.generic.DLOAD;
61 import org.apache.bcel.generic.DSTORE;
62 import org.apache.bcel.generic.FLOAD;
63 import org.apache.bcel.generic.FSTORE;
64 import org.apache.bcel.generic.FieldInstruction;
65 import org.apache.bcel.generic.GETSTATIC;
66 import org.apache.bcel.generic.GotoInstruction;
67 import org.apache.bcel.generic.IINC;
68 import org.apache.bcel.generic.ILOAD;
69 import org.apache.bcel.generic.IMPDEP1;
70 import org.apache.bcel.generic.IMPDEP2;
71 import org.apache.bcel.generic.INSTANCEOF;
72 import org.apache.bcel.generic.INVOKEDYNAMIC;
73 import org.apache.bcel.generic.INVOKEINTERFACE;
74 import org.apache.bcel.generic.INVOKESPECIAL;
75 import org.apache.bcel.generic.INVOKESTATIC;
76 import org.apache.bcel.generic.INVOKEVIRTUAL;
77 import org.apache.bcel.generic.ISTORE;
78 import org.apache.bcel.generic.Instruction;
79 import org.apache.bcel.generic.InstructionHandle;
80 import org.apache.bcel.generic.InstructionList;
81 import org.apache.bcel.generic.InvokeInstruction;
82 import org.apache.bcel.generic.JsrInstruction;
83 import org.apache.bcel.generic.LDC;
84 import org.apache.bcel.generic.LDC2_W;
85 import org.apache.bcel.generic.LLOAD;
86 import org.apache.bcel.generic.LOOKUPSWITCH;
87 import org.apache.bcel.generic.LSTORE;
88 import org.apache.bcel.generic.LoadClass;
89 import org.apache.bcel.generic.MULTIANEWARRAY;
90 import org.apache.bcel.generic.NEW;
91 import org.apache.bcel.generic.NEWARRAY;
92 import org.apache.bcel.generic.ObjectType;
93 import org.apache.bcel.generic.PUTSTATIC;
94 import org.apache.bcel.generic.RET;
95 import org.apache.bcel.generic.ReferenceType;
96 import org.apache.bcel.generic.ReturnInstruction;
97 import org.apache.bcel.generic.TABLESWITCH;
98 import org.apache.bcel.generic.Type;
99 import org.apache.bcel.verifier.PassVerifier;
100 import org.apache.bcel.verifier.VerificationResult;
101 import org.apache.bcel.verifier.Verifier;
102 import org.apache.bcel.verifier.VerifierFactory;
103 import org.apache.bcel.verifier.exc.AssertionViolatedException;
104 import org.apache.bcel.verifier.exc.ClassConstraintException;
105 import org.apache.bcel.verifier.exc.InvalidMethodException;
106 import org.apache.bcel.verifier.exc.StaticCodeConstraintException;
107 import org.apache.bcel.verifier.exc.StaticCodeInstructionConstraintException;
108 import org.apache.bcel.verifier.exc.StaticCodeInstructionOperandConstraintException;
109
110
111
112
113
114
115
116 public final class Pass3aVerifier extends PassVerifier {
117
118
119
120
121 private final class InstOperandConstraintVisitor extends org.apache.bcel.generic.EmptyVisitor {
122
123
124 private final ConstantPoolGen constantPoolGen;
125
126
127
128
129 InstOperandConstraintVisitor(final ConstantPoolGen constantPoolGen) {
130 this.constantPoolGen = constantPoolGen;
131 }
132
133
134
135
136
137
138 private void constraintViolated(final Instruction i, final String message) {
139 throw new StaticCodeInstructionOperandConstraintException("Instruction " + tostring(i) + " constraint violated: " + message);
140 }
141
142
143
144
145
146
147
148
149 private Method getMethod(final JavaClass jc, final InvokeInstruction invoke) {
150 final Method[] ms = jc.getMethods();
151
152 if (invoke instanceof INVOKEVIRTUAL
153 && ("java.lang.invoke.MethodHandle".equals(jc.getClassName()) || "java.lang.invoke.VarHandle".equals(jc.getClassName()))) {
154 Method candidate = null;
155 int matches = 0;
156 for (final Method method : ms) {
157 if (method.getName().equals(invoke.getMethodName(constantPoolGen))) {
158 candidate = method;
159 matches++;
160 }
161 }
162 if (matches == 1 && candidate.isNative() && candidate.isVarArgs()
163 && Arrays.equals(candidate.getArgumentTypes(), new Type[] { new ArrayType(Type.OBJECT, 1) })) {
164 return candidate;
165 }
166 }
167 for (final Method element : ms) {
168 if (element.getName().equals(invoke.getMethodName(constantPoolGen))
169 && Type.getReturnType(element.getSignature()).equals(invoke.getReturnType(constantPoolGen))
170 && Arrays.equals(Type.getArgumentTypes(element.getSignature()), invoke.getArgumentTypes(constantPoolGen))) {
171 return element;
172 }
173 }
174
175 return null;
176 }
177
178
179
180
181
182
183
184
185
186 private Method getMethodRecursive(final JavaClass jc, final InvokeInstruction invoke) throws ClassNotFoundException {
187 Method m;
188
189 m = getMethod(jc, invoke);
190 if (m != null) {
191
192 return m;
193 }
194
195 for (final JavaClass superclass : jc.getSuperClasses()) {
196 m = getMethod(superclass, invoke);
197 if (m != null) {
198
199 return m;
200 }
201 }
202
203 for (final JavaClass superclass : jc.getInterfaces()) {
204 m = getMethod(superclass, invoke);
205 if (m != null) {
206
207 return m;
208 }
209 }
210
211 return null;
212 }
213
214 private ObjectType getObjectType(final FieldInstruction o) {
215 final ReferenceType rt = o.getReferenceType(constantPoolGen);
216 if (rt instanceof ObjectType) {
217 return (ObjectType) rt;
218 }
219 constraintViolated(o, "expecting ObjectType but got " + rt);
220 return null;
221 }
222
223
224
225
226
227
228
229
230
231
232
233 private void indexValid(final Instruction i, final int idx) {
234 if (idx < 0 || idx >= constantPoolGen.getSize()) {
235 constraintViolated(i, "Illegal constant pool index '" + idx + "'.");
236 }
237 }
238
239
240
241
242 private int maxLocals() {
243 try {
244 return Repository.lookupClass(verifier.getClassName()).getMethods()[methodNo].getCode().getMaxLocals();
245 } catch (final ClassNotFoundException e) {
246
247 throw new AssertionViolatedException("Missing class: " + e, e);
248 }
249 }
250
251
252 @Override
253 public void visitALOAD(final ALOAD o) {
254 final int idx = o.getIndex();
255 if (idx < 0) {
256 constraintViolated(o, "Index '" + idx + "' must be non-negative.");
257 } else {
258 final int maxminus1 = maxLocals() - 1;
259 if (idx > maxminus1) {
260 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-1 '" + maxminus1 + "'.");
261 }
262 }
263 }
264
265
266 @Override
267 public void visitANEWARRAY(final ANEWARRAY o) {
268 indexValid(o, o.getIndex());
269 final Constant c = constantPoolGen.getConstant(o.getIndex());
270 if (!(c instanceof ConstantClass)) {
271 constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '" + tostring(c) + "'.");
272 }
273 final Type t = o.getType(constantPoolGen);
274 if (t instanceof ArrayType) {
275 final int dimensions = ((ArrayType) t).getDimensions();
276 if (dimensions > Const.MAX_ARRAY_DIMENSIONS) {
277 constraintViolated(o,
278 "Not allowed to create an array with more than " + Const.MAX_ARRAY_DIMENSIONS + " dimensions; actual: " + dimensions);
279 }
280 }
281 }
282
283
284 @Override
285 public void visitASTORE(final ASTORE o) {
286 final int idx = o.getIndex();
287 if (idx < 0) {
288 constraintViolated(o, "Index '" + idx + "' must be non-negative.");
289 } else {
290 final int maxminus1 = maxLocals() - 1;
291 if (idx > maxminus1) {
292 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-1 '" + maxminus1 + "'.");
293 }
294 }
295 }
296
297
298 @Override
299 public void visitCHECKCAST(final CHECKCAST o) {
300 indexValid(o, o.getIndex());
301 final Constant c = constantPoolGen.getConstant(o.getIndex());
302 if (!(c instanceof ConstantClass)) {
303 constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '" + tostring(c) + "'.");
304 }
305 }
306
307
308 @Override
309 public void visitDLOAD(final DLOAD o) {
310 final int idx = o.getIndex();
311 if (idx < 0) {
312 constraintViolated(o, "Index '" + idx + "' must be non-negative."
313 + " [Constraint imposed by JustIce by analogy with the single-slot xLOAD/xSTORE instructions; may not happen anyway.]");
314 } else {
315 final int maxminus2 = maxLocals() - 2;
316 if (idx > maxminus2) {
317 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-2 '" + maxminus2 + "'.");
318 }
319 }
320 }
321
322
323 @Override
324 public void visitDSTORE(final DSTORE o) {
325 final int idx = o.getIndex();
326 if (idx < 0) {
327 constraintViolated(o, "Index '" + idx + "' must be non-negative."
328 + " [Constraint imposed by JustIce by analogy with the single-slot xLOAD/xSTORE instructions; may not happen anyway.]");
329 } else {
330 final int maxminus2 = maxLocals() - 2;
331 if (idx > maxminus2) {
332 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-2 '" + maxminus2 + "'.");
333 }
334 }
335 }
336
337
338
339 @Override
340 public void visitFieldInstruction(final FieldInstruction o) {
341 try {
342 indexValid(o, o.getIndex());
343 final Constant c = constantPoolGen.getConstant(o.getIndex());
344 if (!(c instanceof ConstantFieldref)) {
345 constraintViolated(o, "Indexing a constant that's not a CONSTANT_Fieldref but a '" + tostring(c) + "'.");
346 }
347
348 final String fieldName = o.getFieldName(constantPoolGen);
349
350 final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
351 final Field f = jc.findField(fieldName, o.getType(constantPoolGen));
352 if (f == null) {
353 constraintViolated(o, "Referenced field '" + fieldName + "' does not exist in class '" + jc.getClassName() + "'.");
354 }
355 } catch (final ClassNotFoundException e) {
356
357 throw new AssertionViolatedException("Missing class: " + e, e);
358 }
359 }
360
361
362 @Override
363 public void visitFLOAD(final FLOAD o) {
364 final int idx = o.getIndex();
365 if (idx < 0) {
366 constraintViolated(o, "Index '" + idx + "' must be non-negative.");
367 } else {
368 final int maxminus1 = maxLocals() - 1;
369 if (idx > maxminus1) {
370 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-1 '" + maxminus1 + "'.");
371 }
372 }
373 }
374
375
376 @Override
377 public void visitFSTORE(final FSTORE o) {
378 final int idx = o.getIndex();
379 if (idx < 0) {
380 constraintViolated(o, "Index '" + idx + "' must be non-negative.");
381 } else {
382 final int maxminus1 = maxLocals() - 1;
383 if (idx > maxminus1) {
384 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-1 '" + maxminus1 + "'.");
385 }
386 }
387 }
388
389
390 @Override
391 public void visitGETSTATIC(final GETSTATIC o) {
392 try {
393 final String fieldName = o.getFieldName(constantPoolGen);
394 final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
395 final Field f = jc.findField(fieldName, o.getType(constantPoolGen));
396 if (f == null) {
397 throw new AssertionViolatedException("Field '" + fieldName + "' not found in " + jc.getClassName());
398 }
399
400 if (!f.isStatic()) {
401 constraintViolated(o, "Referenced field '" + f + "' is not static which it should be.");
402 }
403 } catch (final ClassNotFoundException e) {
404
405 throw new AssertionViolatedException("Missing class: " + e, e);
406 }
407 }
408
409
410 @Override
411 public void visitIINC(final IINC o) {
412 final int idx = o.getIndex();
413 if (idx < 0) {
414 constraintViolated(o, "Index '" + idx + "' must be non-negative.");
415 } else {
416 final int maxminus1 = maxLocals() - 1;
417 if (idx > maxminus1) {
418 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-1 '" + maxminus1 + "'.");
419 }
420 }
421 }
422
423
424 @Override
425 public void visitILOAD(final ILOAD o) {
426 final int idx = o.getIndex();
427 if (idx < 0) {
428 constraintViolated(o, "Index '" + idx + "' must be non-negative.");
429 } else {
430 final int maxminus1 = maxLocals() - 1;
431 if (idx > maxminus1) {
432 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-1 '" + maxminus1 + "'.");
433 }
434 }
435 }
436
437
438 @Override
439 public void visitINSTANCEOF(final INSTANCEOF o) {
440 indexValid(o, o.getIndex());
441 final Constant c = constantPoolGen.getConstant(o.getIndex());
442 if (!(c instanceof ConstantClass)) {
443 constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '" + tostring(c) + "'.");
444 }
445 }
446
447
448
449
450
451
452 @Override
453 public void visitINVOKEDYNAMIC(final INVOKEDYNAMIC o) {
454 throw new UnsupportedOperationException("INVOKEDYNAMIC instruction is not supported at this time");
455 }
456
457
458 @Override
459 public void visitInvokeInstruction(final InvokeInstruction o) {
460 indexValid(o, o.getIndex());
461 if (o instanceof INVOKEVIRTUAL || o instanceof INVOKESPECIAL || o instanceof INVOKESTATIC) {
462 final Constant c = constantPoolGen.getConstant(o.getIndex());
463 if (!(c instanceof ConstantMethodref)) {
464 constraintViolated(o, "Indexing a constant that's not a CONSTANT_Methodref but a '" + tostring(c) + "'.");
465 } else {
466
467 final ConstantNameAndType cnat = (ConstantNameAndType) constantPoolGen.getConstant(((ConstantMethodref) c).getNameAndTypeIndex());
468 final ConstantUtf8 cutf8 = (ConstantUtf8) constantPoolGen.getConstant(cnat.getNameIndex());
469 if (cutf8.getBytes().equals(Const.CONSTRUCTOR_NAME) && !(o instanceof INVOKESPECIAL)) {
470 constraintViolated(o, "Only INVOKESPECIAL is allowed to invoke instance initialization methods.");
471 }
472 if (!cutf8.getBytes().equals(Const.CONSTRUCTOR_NAME) && cutf8.getBytes().startsWith("<")) {
473 constraintViolated(o, "No method with a name beginning with '<' other than the instance initialization methods"
474 + " may be called by the method invocation instructions.");
475 }
476 }
477 } else {
478 final Constant c = constantPoolGen.getConstant(o.getIndex());
479 if (!(c instanceof ConstantInterfaceMethodref) && !(c instanceof ConstantInvokeDynamic)) {
480 constraintViolated(o, "Indexing a constant that's not a CONSTANT_InterfaceMethodref/InvokeDynamic but a '" + tostring(c) + "'.");
481 }
482
483
484
485
486
487
488 final ConstantNameAndType cnat = (ConstantNameAndType) constantPoolGen.getConstant(((ConstantCP) c).getNameAndTypeIndex());
489 final String name = ((ConstantUtf8) constantPoolGen.getConstant(cnat.getNameIndex())).getBytes();
490 if (name.equals(Const.CONSTRUCTOR_NAME)) {
491 constraintViolated(o, "Method to invoke must not be '" + Const.CONSTRUCTOR_NAME + "'.");
492 }
493 if (name.equals(Const.STATIC_INITIALIZER_NAME)) {
494 constraintViolated(o, "Method to invoke must not be '" + Const.STATIC_INITIALIZER_NAME + "'.");
495 }
496 }
497
498
499
500 Type t = o.getReturnType(constantPoolGen);
501 if (t instanceof ArrayType) {
502 t = ((ArrayType) t).getBasicType();
503 }
504 if (t instanceof ObjectType) {
505 final Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName());
506 final VerificationResult vr = v.doPass2();
507 if (vr.getStatus() != VerificationResult.VERIFIED_OK) {
508 constraintViolated(o, "Return type class/interface could not be verified successfully: '" + vr.getMessage() + "'.");
509 }
510 }
511
512 final Type[] ts = o.getArgumentTypes(constantPoolGen);
513 for (final Type element : ts) {
514 t = element;
515 if (t instanceof ArrayType) {
516 t = ((ArrayType) t).getBasicType();
517 }
518 if (t instanceof ObjectType) {
519 final Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName());
520 final VerificationResult vr = v.doPass2();
521 if (vr.getStatus() != VerificationResult.VERIFIED_OK) {
522 constraintViolated(o, "Argument type class/interface could not be verified successfully: '" + vr.getMessage() + "'.");
523 }
524 }
525 }
526
527 }
528
529
530 @Override
531 public void visitINVOKEINTERFACE(final INVOKEINTERFACE o) {
532 try {
533
534
535
536
537 final String className = o.getClassName(constantPoolGen);
538 final JavaClass jc = Repository.lookupClass(className);
539 final Method m = getMethodRecursive(jc, o);
540 if (m == null) {
541 constraintViolated(o, "Referenced method '" + o.getMethodName(constantPoolGen) + "' with expected signature '"
542 + o.getSignature(constantPoolGen) + "' not found in class '" + jc.getClassName() + "'.");
543 }
544 if (jc.isClass()) {
545 constraintViolated(o, "Referenced class '" + jc.getClassName() + "' is a class, but not an interface as expected.");
546 }
547 } catch (final ClassNotFoundException e) {
548
549 throw new AssertionViolatedException("Missing class: " + e, e);
550 }
551 }
552
553
554 @Override
555 public void visitINVOKESPECIAL(final INVOKESPECIAL o) {
556 try {
557
558
559
560
561 final String className = o.getClassName(constantPoolGen);
562 final JavaClass jc = Repository.lookupClass(className);
563 final Method m = getMethodRecursive(jc, o);
564 if (m == null) {
565 constraintViolated(o, "Referenced method '" + o.getMethodName(constantPoolGen) + "' with expected signature '"
566 + o.getSignature(constantPoolGen) + "' not found in class '" + jc.getClassName() + "'.");
567 }
568
569 JavaClass current = Repository.lookupClass(verifier.getClassName());
570 if (current.isSuper() && Repository.instanceOf(current, jc) && !current.equals(jc)
571 && !o.getMethodName(constantPoolGen).equals(Const.CONSTRUCTOR_NAME)) {
572
573
574 int supidx = -1;
575
576 Method meth = null;
577 while (supidx != 0) {
578 supidx = current.getSuperclassNameIndex();
579 current = Repository.lookupClass(current.getSuperclassName());
580
581 final Method[] meths = current.getMethods();
582 for (final Method meth2 : meths) {
583 if (meth2.getName().equals(o.getMethodName(constantPoolGen))
584 && Type.getReturnType(meth2.getSignature()).equals(o.getReturnType(constantPoolGen))
585 && Arrays.equals(Type.getArgumentTypes(meth2.getSignature()), o.getArgumentTypes(constantPoolGen))) {
586 meth = meth2;
587 break;
588 }
589 }
590 if (meth != null) {
591 break;
592 }
593 }
594 if (meth == null) {
595 constraintViolated(o, "ACC_SUPER special lookup procedure not successful: method '" + o.getMethodName(constantPoolGen)
596 + "' with proper signature not declared in superclass hierarchy.");
597 }
598 }
599
600 } catch (final ClassNotFoundException e) {
601
602 throw new AssertionViolatedException("Missing class: " + e, e);
603 }
604
605 }
606
607
608 @Override
609 public void visitINVOKESTATIC(final INVOKESTATIC o) {
610 try {
611
612
613
614
615 final String className = o.getClassName(constantPoolGen);
616 final JavaClass jc = Repository.lookupClass(className);
617 final Method m = getMethodRecursive(jc, o);
618 if (m == null) {
619 constraintViolated(o, "Referenced method '" + o.getMethodName(constantPoolGen) + "' with expected signature '"
620 + o.getSignature(constantPoolGen) + "' not found in class '" + jc.getClassName() + "'.");
621 } else if (!m.isStatic()) {
622 constraintViolated(o, "Referenced method '" + o.getMethodName(constantPoolGen) + "' has ACC_STATIC unset.");
623 }
624
625 } catch (final ClassNotFoundException e) {
626
627 throw new AssertionViolatedException("Missing class: " + e, e);
628 }
629 }
630
631
632 @Override
633 public void visitINVOKEVIRTUAL(final INVOKEVIRTUAL o) {
634 try {
635
636
637
638
639 final String className = o.getClassName(constantPoolGen);
640 final JavaClass jc;
641 if (className.charAt(0) == '[') {
642 jc = Repository.lookupClass("java.lang.Object");
643 } else {
644 jc = Repository.lookupClass(className);
645 }
646 final Method m = getMethodRecursive(jc, o);
647 if (m == null) {
648 constraintViolated(o, "Referenced method '" + o.getMethodName(constantPoolGen) + "' with expected signature '"
649 + o.getSignature(constantPoolGen) + "' not found in class '" + jc.getClassName() + "'.");
650 }
651 if (!jc.isClass()) {
652 constraintViolated(o, "Referenced class '" + jc.getClassName() + "' is an interface, but not a class as expected.");
653 }
654
655 } catch (final ClassNotFoundException e) {
656
657
658 addMessage("Unable to verify INVOKEVIRTUAL because the target class cannot be loaded: " + e.getCause());
659 }
660 }
661
662
663 @Override
664 public void visitISTORE(final ISTORE o) {
665 final int idx = o.getIndex();
666 if (idx < 0) {
667 constraintViolated(o, "Index '" + idx + "' must be non-negative.");
668 } else {
669 final int maxminus1 = maxLocals() - 1;
670 if (idx > maxminus1) {
671 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-1 '" + maxminus1 + "'.");
672 }
673 }
674 }
675
676
677
678 @Override
679 public void visitLDC(final LDC ldc) {
680 indexValid(ldc, ldc.getIndex());
681 final Constant c = constantPoolGen.getConstant(ldc.getIndex());
682 if (c instanceof ConstantClass) {
683 addMessage("Operand of LDC or LDC_W is CONSTANT_Class '" + tostring(c) + "' - this is only supported in JDK 1.5 and higher.");
684 } else if (!(c instanceof ConstantInteger || c instanceof ConstantFloat || c instanceof ConstantString || c instanceof ConstantDynamic)) {
685 constraintViolated(ldc,
686 "Operand of LDC or LDC_W must be one of CONSTANT_Integer, CONSTANT_Float, CONSTANT_String or CONSTANT_Dynamic but is '"
687 + tostring(c) + "'.");
688 }
689 }
690
691
692
693 @Override
694 public void visitLDC2_W(final LDC2_W o) {
695 indexValid(o, o.getIndex());
696 final Constant c = constantPoolGen.getConstant(o.getIndex());
697 if (!(c instanceof ConstantLong || c instanceof ConstantDouble)) {
698 constraintViolated(o, "Operand of LDC2_W must be CONSTANT_Long or CONSTANT_Double, but is '" + tostring(c) + "'.");
699 }
700 try {
701 indexValid(o, o.getIndex() + 1);
702 } catch (final StaticCodeInstructionOperandConstraintException e) {
703 throw new AssertionViolatedException("Does BCEL not handle that? LDC2_W operand has a problem.", e);
704 }
705 }
706
707
708 @Override
709 public void visitLLOAD(final LLOAD o) {
710 final int idx = o.getIndex();
711 if (idx < 0) {
712 constraintViolated(o, "Index '" + idx + "' must be non-negative."
713 + " [Constraint imposed by JustIce by analogy with the single-slot xLOAD/xSTORE instructions; may not happen anyway.]");
714 } else {
715 final int maxminus2 = maxLocals() - 2;
716 if (idx > maxminus2) {
717 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-2 '" + maxminus2 + "'.");
718 }
719 }
720 }
721
722
723
724
725
726
727
728
729 @Override
730 public void visitLoadClass(final LoadClass loadClass) {
731 final ObjectType t = loadClass.getLoadClassType(constantPoolGen);
732 if (t != null) {
733 final Verifier v = VerifierFactory.getVerifier(t.getClassName());
734 final VerificationResult vr = v.doPass1();
735 if (vr.getStatus() != VerificationResult.VERIFIED_OK) {
736 constraintViolated((Instruction) loadClass,
737 "Class '" + loadClass.getLoadClassType(constantPoolGen).getClassName() + "' is referenced, but cannot be loaded: '" + vr + "'.");
738 }
739 }
740 }
741
742
743
744
745
746
747
748
749
750
751
752
753 @Override
754 public void visitLOOKUPSWITCH(final LOOKUPSWITCH o) {
755 final int[] matchs = o.getMatchs();
756 int max = Integer.MIN_VALUE;
757 for (int i = 0; i < matchs.length; i++) {
758 if (matchs[i] == max && i != 0) {
759 constraintViolated(o, "Match '" + matchs[i] + "' occurs more than once.");
760 }
761 if (matchs[i] < max) {
762 constraintViolated(o, "Lookup table must be sorted but isn't.");
763 } else {
764 max = matchs[i];
765 }
766 }
767 }
768
769
770 @Override
771 public void visitLSTORE(final LSTORE o) {
772 final int idx = o.getIndex();
773 if (idx < 0) {
774 constraintViolated(o, "Index '" + idx + "' must be non-negative."
775 + " [Constraint imposed by JustIce by analogy with the single-slot xLOAD/xSTORE instructions; may not happen anyway.]");
776 } else {
777 final int maxminus2 = maxLocals() - 2;
778 if (idx > maxminus2) {
779 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-2 '" + maxminus2 + "'.");
780 }
781 }
782 }
783
784
785 @Override
786 public void visitMULTIANEWARRAY(final MULTIANEWARRAY o) {
787 indexValid(o, o.getIndex());
788 final Constant c = constantPoolGen.getConstant(o.getIndex());
789 if (!(c instanceof ConstantClass)) {
790 constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '" + tostring(c) + "'.");
791 }
792 final int dimensions2create = o.getDimensions();
793 if (dimensions2create < 1) {
794 constraintViolated(o, "Number of dimensions to create must be greater than zero.");
795 }
796 final Type t = o.getType(constantPoolGen);
797 if (t instanceof ArrayType) {
798 final int dimensions = ((ArrayType) t).getDimensions();
799 if (dimensions < dimensions2create) {
800 constraintViolated(o, "Not allowed to create an array with more dimensions ('" + dimensions2create
801 + "') than the one referenced by the CONSTANT_Class '" + t + "'.");
802 }
803 } else {
804 constraintViolated(o, "Expecting a CONSTANT_Class referencing an array type."
805 + " [Constraint not found in The Java Virtual Machine Specification, Second Edition, 4.8.1]");
806 }
807 }
808
809
810 @Override
811 public void visitNEW(final NEW o) {
812 indexValid(o, o.getIndex());
813 final Constant c = constantPoolGen.getConstant(o.getIndex());
814 if (!(c instanceof ConstantClass)) {
815 constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '" + tostring(c) + "'.");
816 } else {
817 final ConstantUtf8 cutf8 = (ConstantUtf8) constantPoolGen.getConstant(((ConstantClass) c).getNameIndex());
818 final Type t = Type.getType("L" + cutf8.getBytes() + ";");
819 if (t instanceof ArrayType) {
820 constraintViolated(o, "NEW must not be used to create an array.");
821 }
822 }
823
824 }
825
826
827 @Override
828 public void visitNEWARRAY(final NEWARRAY o) {
829 final byte t = o.getTypecode();
830 if (!(t == Const.T_BOOLEAN || t == Const.T_CHAR || t == Const.T_FLOAT || t == Const.T_DOUBLE || t == Const.T_BYTE || t == Const.T_SHORT
831 || t == Const.T_INT || t == Const.T_LONG)) {
832 constraintViolated(o, "Illegal type code '" + tostring(t) + "' for 'atype' operand.");
833 }
834 }
835
836
837 @Override
838 public void visitPUTSTATIC(final PUTSTATIC o) {
839 try {
840 final String fieldName = o.getFieldName(constantPoolGen);
841 final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
842 final Field f = jc.findField(fieldName, o.getType(constantPoolGen));
843 if (f == null) {
844 throw new AssertionViolatedException("Field '" + fieldName + "' not found in " + jc.getClassName());
845 }
846
847 if (f.isFinal() && !verifier.getClassName().equals(getObjectType(o).getClassName())) {
848 constraintViolated(o, "Referenced field '" + f + "' is final and must therefore be declared in the current class '"
849 + verifier.getClassName() + "' which is not the case: it is declared in '" + o.getReferenceType(constantPoolGen) + "'.");
850 }
851
852 if (!f.isStatic()) {
853 constraintViolated(o, "Referenced field '" + f + "' is not static which it should be.");
854 }
855
856 final String methName = Repository.lookupClass(verifier.getClassName()).getMethods()[methodNo].getName();
857
858
859 if (!jc.isClass() && !methName.equals(Const.STATIC_INITIALIZER_NAME)) {
860 constraintViolated(o, "Interface field '" + f + "' must be set in a '" + Const.STATIC_INITIALIZER_NAME + "' method.");
861 }
862 } catch (final ClassNotFoundException e) {
863
864 throw new AssertionViolatedException("Missing class: " + e, e);
865 }
866 }
867
868
869 @Override
870 public void visitRET(final RET o) {
871 final int idx = o.getIndex();
872 if (idx < 0) {
873 constraintViolated(o, "Index '" + idx + "' must be non-negative.");
874 } else {
875 final int maxminus1 = maxLocals() - 1;
876 if (idx > maxminus1) {
877 constraintViolated(o, "Index '" + idx + "' must not be greater than max_locals-1 '" + maxminus1 + "'.");
878 }
879 }
880 }
881
882
883
884
885 @Override
886 public void visitTABLESWITCH(final TABLESWITCH o) {
887
888
889 }
890 }
891
892
893 private final Verifier verifier;
894
895
896
897
898 private final int methodNo;
899
900
901
902
903
904 private InstructionList instructionList;
905
906
907
908
909
910 private Code code;
911
912
913
914
915
916
917
918 public Pass3aVerifier(final Verifier verifier, final int methodNo) {
919 this.verifier = verifier;
920 this.methodNo = methodNo;
921 }
922
923
924
925
926
927
928
929
930
931 private void delayedPass2Checks() {
932
933 final int[] instructionPositions = instructionList.getInstructionPositions();
934 final int codeLength = code.getCode().length;
935
936
937
938
939 final Set<Integer> instructionPositionSet = new HashSet<>();
940 for (final int instructionPosition : instructionPositions) {
941 instructionPositionSet.add(Integer.valueOf(instructionPosition));
942 }
943
944
945
946
947 final LineNumberTable lnt = code.getLineNumberTable();
948 if (lnt != null) {
949 final LineNumber[] lineNumbers = lnt.getLineNumberTable();
950 final IntList offsets = new IntList();
951 for (final LineNumber lineNumber : lineNumbers) {
952 final int offset = lineNumber.getStartPC();
953 if (!instructionPositionSet.contains(Integer.valueOf(offset))) {
954 throw new ClassConstraintException("Code attribute '" + tostring(code) + "' has a LineNumberTable attribute '" + code.getLineNumberTable()
955 + "' referring to a code offset ('" + offset + "') that does not exist.");
956 }
957 if (offsets.contains(offset)) {
958 addMessage("LineNumberTable attribute '" + code.getLineNumberTable() + "' refers to the same code offset ('" + offset
959 + "') more than once, which violates the semantics [but is sometimes produced by IBM's 'jikes' compiler].");
960 } else {
961 offsets.add(offset);
962 }
963 }
964 }
965
966
967
968
969
970
971
972 final Attribute[] atts = code.getAttributes();
973 for (final Attribute att : atts) {
974 if (att instanceof LocalVariableTable) {
975 ((LocalVariableTable) att).forEach(localVariable -> {
976 final int startpc = localVariable.getStartPC();
977 final int length = localVariable.getLength();
978
979 if (!instructionPositionSet.contains(Integer.valueOf(startpc))) {
980 throw new ClassConstraintException("Code attribute '" + tostring(code) + "' has a LocalVariableTable attribute '"
981 + code.getLocalVariableTable() + "' referring to a code offset ('" + startpc + "') that does not exist.");
982 }
983 if (!instructionPositionSet.contains(Integer.valueOf(startpc + length)) && startpc + length != codeLength) {
984 throw new ClassConstraintException(
985 "Code attribute '" + tostring(code) + "' has a LocalVariableTable attribute '" + code.getLocalVariableTable()
986 + "' referring to a code offset start_pc+length ('" + (startpc + length) + "') that does not exist.");
987 }
988 });
989 }
990 }
991
992
993
994
995
996
997
998 final CodeException[] exceptionTable = code.getExceptionTable();
999 for (final CodeException element : exceptionTable) {
1000 final int startpc = element.getStartPC();
1001 final int endpc = element.getEndPC();
1002 final int handlerpc = element.getHandlerPC();
1003 if (startpc >= endpc) {
1004 throw new ClassConstraintException("Code attribute '" + tostring(code) + "' has an exception_table entry '" + element
1005 + "' that has its start_pc ('" + startpc + "') not smaller than its end_pc ('" + endpc + "').");
1006 }
1007 if (!instructionPositionSet.contains(Integer.valueOf(startpc))) {
1008 throw new ClassConstraintException("Code attribute '" + tostring(code) + "' has an exception_table entry '" + element
1009 + "' that has a nonexistent bytecode offset as its start_pc ('" + startpc + "').");
1010 }
1011 if (!instructionPositionSet.contains(Integer.valueOf(endpc)) && endpc != codeLength) {
1012 throw new ClassConstraintException("Code attribute '" + tostring(code) + "' has an exception_table entry '" + element
1013 + "' that has a nonexistent bytecode offset as its end_pc ('" + startpc + "') [that is also not equal to code_length ('" + codeLength
1014 + "')].");
1015 }
1016 if (!instructionPositionSet.contains(Integer.valueOf(handlerpc))) {
1017 throw new ClassConstraintException("Code attribute '" + tostring(code) + "' has an exception_table entry '" + element
1018 + "' that has a nonexistent bytecode offset as its handler_pc ('" + handlerpc + "').");
1019 }
1020 }
1021 }
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033 @Override
1034 public VerificationResult do_verify() {
1035 try {
1036 if (verifier.doPass2().equals(VerificationResult.VR_OK)) {
1037
1038
1039 final JavaClass jc = Repository.lookupClass(verifier.getClassName());
1040 final Method[] methods = jc.getMethods();
1041 if (methodNo >= methods.length) {
1042 throw new InvalidMethodException("METHOD DOES NOT EXIST.");
1043 }
1044 final Method method = methods[methodNo];
1045 code = method.getCode();
1046
1047
1048 if (method.isAbstract() || method.isNative()) {
1049 return VerificationResult.VR_OK;
1050 }
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061 try {
1062 instructionList = new InstructionList(method.getCode().getCode());
1063 } catch (final RuntimeException re) {
1064 return new VerificationResult(VerificationResult.VERIFIED_REJECTED,
1065 "Bad bytecode in the code array of the Code attribute of method '" + tostring(method) + "'.");
1066 }
1067
1068 instructionList.setPositions(true);
1069
1070
1071 VerificationResult vr = VerificationResult.VR_OK;
1072 try {
1073 delayedPass2Checks();
1074 } catch (final ClassConstraintException | ClassFormatException cce) {
1075 return new VerificationResult(VerificationResult.VERIFIED_REJECTED, cce.getMessage());
1076 }
1077 try {
1078 pass3StaticInstructionChecks();
1079 pass3StaticInstructionOperandsChecks();
1080 } catch (final StaticCodeConstraintException | ClassFormatException scce) {
1081 vr = new VerificationResult(VerificationResult.VERIFIED_REJECTED, scce.getMessage());
1082 } catch (final ClassCastException cce) {
1083 vr = new VerificationResult(VerificationResult.VERIFIED_REJECTED, "Class Cast Exception: " + cce.getMessage());
1084 }
1085 return vr;
1086 }
1087
1088 return VerificationResult.VR_NOTYET;
1089 } catch (final ClassNotFoundException e) {
1090
1091 throw new AssertionViolatedException("Missing class: " + e, e);
1092 }
1093 }
1094
1095
1096
1097
1098
1099
1100 public int getMethodNo() {
1101 return methodNo;
1102 }
1103
1104
1105
1106
1107
1108
1109
1110 private void pass3StaticInstructionChecks() {
1111
1112
1113
1114
1115
1116
1117 if (code.getCode().length >= Const.MAX_CODE_SIZE) {
1118 throw new StaticCodeInstructionConstraintException(
1119 "Code array in code attribute '" + tostring(code) + "' too big: must be smaller than " + Const.MAX_CODE_SIZE + "65536 bytes.");
1120 }
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137 InstructionHandle ih = instructionList.getStart();
1138 while (ih != null) {
1139 final Instruction i = ih.getInstruction();
1140 if (i instanceof IMPDEP1) {
1141 throw new StaticCodeInstructionConstraintException("IMPDEP1 must not be in the code; it is an illegal instruction for _internal_ JVM use.");
1142 }
1143 if (i instanceof IMPDEP2) {
1144 throw new StaticCodeInstructionConstraintException("IMPDEP2 must not be in the code; it is an illegal instruction for _internal_ JVM use.");
1145 }
1146 if (i instanceof BREAKPOINT) {
1147 throw new StaticCodeInstructionConstraintException("BREAKPOINT must not be in the code; it is an illegal instruction for _internal_ JVM use.");
1148 }
1149 ih = ih.getNext();
1150 }
1151
1152
1153
1154
1155
1156 final Instruction last = instructionList.getEnd().getInstruction();
1157 if (!(last instanceof ReturnInstruction || last instanceof RET || last instanceof GotoInstruction || last instanceof ATHROW)) {
1158 throw new StaticCodeInstructionConstraintException(
1159 "Execution must not fall off the bottom of the code array. This constraint is enforced statically as some existing verifiers do"
1160 + " - so it may be a false alarm if the last instruction is not reachable.");
1161 }
1162 }
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172 private void pass3StaticInstructionOperandsChecks() {
1173 try {
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185 final ConstantPoolGen cpg = new ConstantPoolGen(Repository.lookupClass(verifier.getClassName()).getConstantPool());
1186 final InstOperandConstraintVisitor v = new InstOperandConstraintVisitor(cpg);
1187
1188
1189 InstructionHandle ih = instructionList.getStart();
1190 while (ih != null) {
1191 final Instruction i = ih.getInstruction();
1192
1193
1194 if (i instanceof JsrInstruction) {
1195 final InstructionHandle target = ((JsrInstruction) i).getTarget();
1196 if (target == instructionList.getStart()) {
1197 throw new StaticCodeInstructionOperandConstraintException(
1198 "Due to JustIce's clear definition of subroutines, no JSR or JSR_W may have a top-level instruction"
1199 + " (such as the very first instruction, which is targeted by instruction '" + tostring(ih) + "' as its target.");
1200 }
1201 if (!(target.getInstruction() instanceof ASTORE)) {
1202 throw new StaticCodeInstructionOperandConstraintException(
1203 "Due to JustIce's clear definition of subroutines, no JSR or JSR_W may target anything"
1204 + " other than an ASTORE instruction. Instruction '" + tostring(ih) + "' targets '" + tostring(target) + "'.");
1205 }
1206 }
1207
1208
1209 ih.accept(v);
1210
1211 ih = ih.getNext();
1212 }
1213
1214 } catch (final ClassNotFoundException e) {
1215
1216 throw new AssertionViolatedException("Missing class: " + e, e);
1217 }
1218 }
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230 protected String tostring(final Object obj) {
1231 String ret;
1232 try {
1233 ret = obj.toString();
1234 } catch (final RuntimeException e) {
1235
1236
1237 String s = obj.getClass().getName();
1238 s = s.substring(s.lastIndexOf(".") + 1);
1239 ret = "<<" + s + ">>";
1240 }
1241 return ret;
1242 }
1243 }