001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.bcel.verifier.statics;
020
021import java.util.HashMap;
022import java.util.HashSet;
023import java.util.Map;
024import java.util.Objects;
025import java.util.Set;
026
027import org.apache.bcel.Const;
028import org.apache.bcel.Constants;
029import org.apache.bcel.Repository;
030import org.apache.bcel.classfile.Attribute;
031import org.apache.bcel.classfile.ClassFormatException;
032import org.apache.bcel.classfile.Code;
033import org.apache.bcel.classfile.CodeException;
034import org.apache.bcel.classfile.Constant;
035import org.apache.bcel.classfile.ConstantClass;
036import org.apache.bcel.classfile.ConstantDouble;
037import org.apache.bcel.classfile.ConstantFieldref;
038import org.apache.bcel.classfile.ConstantFloat;
039import org.apache.bcel.classfile.ConstantInteger;
040import org.apache.bcel.classfile.ConstantInterfaceMethodref;
041import org.apache.bcel.classfile.ConstantLong;
042import org.apache.bcel.classfile.ConstantMethodref;
043import org.apache.bcel.classfile.ConstantNameAndType;
044import org.apache.bcel.classfile.ConstantPool;
045import org.apache.bcel.classfile.ConstantString;
046import org.apache.bcel.classfile.ConstantUtf8;
047import org.apache.bcel.classfile.ConstantValue;
048import org.apache.bcel.classfile.Deprecated;
049import org.apache.bcel.classfile.DescendingVisitor;
050import org.apache.bcel.classfile.EmptyVisitor;
051import org.apache.bcel.classfile.ExceptionTable;
052import org.apache.bcel.classfile.Field;
053import org.apache.bcel.classfile.InnerClass;
054import org.apache.bcel.classfile.InnerClasses;
055import org.apache.bcel.classfile.JavaClass;
056import org.apache.bcel.classfile.LineNumber;
057import org.apache.bcel.classfile.LineNumberTable;
058import org.apache.bcel.classfile.LocalVariable;
059import org.apache.bcel.classfile.LocalVariableTable;
060import org.apache.bcel.classfile.Method;
061import org.apache.bcel.classfile.Node;
062import org.apache.bcel.classfile.SourceFile;
063import org.apache.bcel.classfile.Synthetic;
064import org.apache.bcel.classfile.Unknown;
065import org.apache.bcel.classfile.Utility;
066import org.apache.bcel.generic.ArrayType;
067import org.apache.bcel.generic.ObjectType;
068import org.apache.bcel.generic.Type;
069import org.apache.bcel.verifier.PassVerifier;
070import org.apache.bcel.verifier.VerificationResult;
071import org.apache.bcel.verifier.Verifier;
072import org.apache.bcel.verifier.VerifierFactory;
073import org.apache.bcel.verifier.exc.AssertionViolatedException;
074import org.apache.bcel.verifier.exc.ClassConstraintException;
075import org.apache.bcel.verifier.exc.LocalVariableInfoInconsistentException;
076import org.apache.commons.lang3.StringUtils;
077
078/**
079 * This PassVerifier verifies a class file according to pass 2 as described in The Java Virtual Machine Specification,
080 * 2nd edition. More detailed information is to be found at the do_verify() method's documentation.
081 *
082 * @see #do_verify()
083 */
084public final class Pass2Verifier extends PassVerifier implements Constants {
085
086    /**
087     * A Visitor class that ensures the constant pool satisfies the static constraints. The visitXXX() methods throw
088     * ClassConstraintException instances otherwise.
089     *
090     * @see #constantPoolEntriesSatisfyStaticConstraints()
091     */
092    private final class CPESSC_Visitor extends EmptyVisitor {
093        private final Class<?> CONST_Class;
094
095        /*
096         * private Class<?> CONST_Fieldref; private Class<?> CONST_Methodref; private Class<?> CONST_InterfaceMethodref;
097         */
098        private final Class<?> CONST_String;
099        private final Class<?> CONST_Integer;
100        private final Class<?> CONST_Float;
101        private final Class<?> CONST_Long;
102        private final Class<?> CONST_Double;
103        private final Class<?> CONST_NameAndType;
104        private final Class<?> CONST_Utf8;
105
106        private final JavaClass jc;
107        private final ConstantPool cp; // ==jc.getConstantPool() -- only here to save typing work and computing power.
108        private final int cplen; // == cp.getLength() -- to save computing power.
109        private final DescendingVisitor carrier;
110
111        private final Set<String> fieldNames = new HashSet<>();
112        private final Set<String> fieldNamesAndDesc = new HashSet<>();
113        private final Set<String> methodNamesAndDesc = new HashSet<>();
114
115        private CPESSC_Visitor(final JavaClass jc) {
116            this.jc = jc;
117            this.cp = jc.getConstantPool();
118            this.cplen = cp.getLength();
119
120            this.CONST_Class = ConstantClass.class;
121            /*
122             * CONST_Fieldref = ConstantFieldref.class; CONST_Methodref = ConstantMethodref.class; CONST_InterfaceMethodref =
123             * ConstantInterfaceMethodref.class;
124             */
125            this.CONST_String = ConstantString.class;
126            this.CONST_Integer = ConstantInteger.class;
127            this.CONST_Float = ConstantFloat.class;
128            this.CONST_Long = ConstantLong.class;
129            this.CONST_Double = ConstantDouble.class;
130            this.CONST_NameAndType = ConstantNameAndType.class;
131            this.CONST_Utf8 = ConstantUtf8.class;
132
133            this.carrier = new DescendingVisitor(jc, this);
134            this.carrier.visit();
135        }
136
137        private void checkIndex(final Node referrer, final int index, final Class<?> shouldbe) {
138            if (index < 0 || index >= cplen) {
139                throw new ClassConstraintException("Invalid index '" + index + "' used by '" + tostring(referrer) + "'.");
140            }
141            final Constant c = cp.getConstant(index);
142            if (!shouldbe.isInstance(c)) {
143                /* String isnot = shouldbe.toString().substring(shouldbe.toString().lastIndexOf(".")+1); //Cut all before last "." */
144                throw new ClassConstraintException(
145                    "Illegal constant '" + tostring(c) + "' at index '" + index + "'. '" + tostring(referrer) + "' expects a '" + shouldbe + "'.");
146            }
147        }
148
149        // SYNTHETIC: see above
150        // DEPRECATED: see above
151        /////////////////////////////////////////////////////////
152        // method_info-structure-ATTRIBUTES (vmspec2 4.6, 4.7) //
153        /////////////////////////////////////////////////////////
154        @Override
155        public void visitCode(final Code obj) { // vmspec2 4.7.3
156            try {
157                // No code attribute allowed for native or abstract methods: see visitMethod(Method).
158                // Code array constraints are checked in Pass3 (3a and 3b).
159
160                checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
161
162                final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes();
163                if (!name.equals("Code")) {
164                    throw new ClassConstraintException("The Code attribute '" + tostring(obj) + "' is not correctly named 'Code' but '" + name + "'.");
165                }
166
167                if (!(carrier.predecessor() instanceof Method)) {
168                    addMessage("Code attribute '" + tostring(obj) + "' is not declared in a method_info structure but in '" + carrier.predecessor()
169                            + "'. Ignored.");
170                    return;
171                }
172                final Method m = (Method) carrier.predecessor(); // we can assume this method was visited before;
173                                                                 // for example the data consistency was verified.
174
175                if (obj.getCode().length == 0) {
176                    throw new ClassConstraintException("Code array of Code attribute '" + tostring(obj) + "' (method '" + m + "') must not be empty.");
177                }
178
179                // In JustIce, the check for correct offsets into the code array is delayed to Pass 3a.
180                final CodeException[] excTable = obj.getExceptionTable();
181                for (final CodeException element : excTable) {
182                    final int excIndex = element.getCatchType();
183                    if (excIndex != 0) { // if 0, it catches all Throwables
184                        checkIndex(obj, excIndex, CONST_Class);
185                        final ConstantClass cc = (ConstantClass) cp.getConstant(excIndex);
186                        // cannot be sure this ConstantClass has already been visited (checked)!
187                        checkIndex(cc, cc.getNameIndex(), CONST_Utf8);
188                        final String cname = Utility.pathToPackage(((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getBytes());
189
190                        Verifier v = VerifierFactory.getVerifier(cname);
191                        VerificationResult vr = v.doPass1();
192
193                        if (vr != VerificationResult.VR_OK) {
194                            throw new ClassConstraintException("Code attribute '" + tostring(obj) + "' (method '" + m + "') has an exception_table entry '"
195                                    + tostring(element) + "' that references '" + cname + "' as an Exception but it does not pass verification pass 1: " + vr);
196                        }
197                        // We cannot safely trust any other "instanceof" mechanism. We need to transitively verify
198                        // the ancestor hierarchy.
199                        JavaClass e = Repository.lookupClass(cname);
200                        final JavaClass t = Repository.lookupClass(Type.THROWABLE.getClassName());
201                        final JavaClass o = Repository.lookupClass(Type.OBJECT.getClassName());
202                        final Set<String> ancestors = new HashSet<>(); // save class names to detect circular inheritance
203                        while (e != o) {
204                            if (e == t) {
205                                break; // It's a subclass of Throwable, OKAY, leave.
206                            }
207                            if (!ancestors.add(e.getClassName())) {
208                                throw new ClassConstraintException("Code attribute '" + tostring(obj) + "' (method '" + m + "') has an exception_table entry '"
209                                        + tostring(element) + "' that references '" + cname
210                                        + "' as an Exception but its superclass hierarchy is circular at '" + e.getClassName() + "'.");
211                            }
212
213                            v = VerifierFactory.getVerifier(e.getSuperclassName());
214                            vr = v.doPass1();
215                            if (vr != VerificationResult.VR_OK) {
216                                throw new ClassConstraintException("Code attribute '" + tostring(obj) + "' (method '" + m + "') has an exception_table entry '"
217                                        + tostring(element) + "' that references '" + cname + "' as an Exception but '" + e.getSuperclassName()
218                                        + "' in the ancestor hierachy does not pass verification pass 1: " + vr);
219                            }
220                            e = Repository.lookupClass(e.getSuperclassName());
221                        }
222                        if (e != t) {
223                            throw new ClassConstraintException(
224                                    "Code attribute '" + tostring(obj) + "' (method '" + m + "') has an exception_table entry '" + tostring(element)
225                                            + "' that references '" + cname + "' as an Exception but it is not a subclass of '" + t.getClassName() + "'.");
226                        }
227                    }
228                }
229
230                // Create object for local variables information
231                // This is highly unelegant due to usage of the Visitor pattern.
232                // TODO: rework it.
233                int methodNumber = -1;
234                final Method[] ms = Repository.lookupClass(verifier.getClassName()).getMethods();
235                for (int mn = 0; mn < ms.length; mn++) {
236                    if (m == ms[mn]) {
237                        methodNumber = mn;
238                        break;
239                    }
240                }
241                // If the .class file is malformed the loop above may not find a method.
242                // Try matching names instead of pointers.
243                if (methodNumber < 0) {
244                    for (int mn = 0; mn < ms.length; mn++) {
245                        if (m.getName().equals(ms[mn].getName())) {
246                            methodNumber = mn;
247                            break;
248                        }
249                    }
250                }
251
252                if (methodNumber < 0) { // Mmmmh. Can we be sure BCEL does not sometimes instantiate new objects?
253                    throw new AssertionViolatedException("Could not find a known BCEL Method object in the corresponding BCEL JavaClass object.");
254                }
255                localVariablesInfos[methodNumber] = new LocalVariablesInfo(obj.getMaxLocals());
256
257                int numOfLvtAttribs = 0;
258                // Now iterate through the attributes the Code attribute has.
259                final Attribute[] atts = obj.getAttributes();
260                for (final Attribute att : atts) {
261                    if (!(att instanceof LineNumberTable) && !(att instanceof LocalVariableTable)) {
262                        addMessage("Attribute '" + tostring(att) + "' as an attribute of Code attribute '" + tostring(obj) + "' (method '" + m
263                                + "') is unknown and will therefore be ignored.");
264                    } else { // LineNumberTable or LocalVariableTable
265                        addMessage("Attribute '" + tostring(att) + "' as an attribute of Code attribute '" + tostring(obj) + "' (method '" + m
266                                + "') will effectively be ignored and is only useful for debuggers and such.");
267                    }
268
269                    // LocalVariableTable check (partially delayed to Pass3a).
270                    // Here because its easier to collect the information of the
271                    // (possibly more than one) LocalVariableTables belonging to
272                    // one certain Code attribute.
273                    if (att instanceof LocalVariableTable) { // checks conforming to vmspec2 4.7.9
274
275                        final LocalVariableTable lvt = (LocalVariableTable) att;
276
277                        checkIndex(lvt, lvt.getNameIndex(), CONST_Utf8);
278
279                        final String lvtname = ((ConstantUtf8) cp.getConstant(lvt.getNameIndex())).getBytes();
280                        if (!lvtname.equals("LocalVariableTable")) {
281                            throw new ClassConstraintException("The LocalVariableTable attribute '" + tostring(lvt)
282                                    + "' is not correctly named 'LocalVariableTable' but '" + lvtname + "'.");
283                        }
284
285                        // In JustIce, the check for correct offsets into the code array is delayed to Pass 3a.
286                        for (final LocalVariable localvariable : lvt.getLocalVariableTable()) {
287                            checkIndex(lvt, localvariable.getNameIndex(), CONST_Utf8);
288                            final String localname = ((ConstantUtf8) cp.getConstant(localvariable.getNameIndex())).getBytes();
289                            if (!validJavaIdentifier(localname)) {
290                                throw new ClassConstraintException("LocalVariableTable '" + tostring(lvt) + "' references a local variable by the name '"
291                                        + localname + "' which is not a legal Java simple name.");
292                            }
293
294                            checkIndex(lvt, localvariable.getSignatureIndex(), CONST_Utf8);
295                            final String localsig = ((ConstantUtf8) cp.getConstant(localvariable.getSignatureIndex())).getBytes(); // Local sig.(=descriptor)
296                            final Type t;
297                            try {
298                                t = Type.getType(localsig);
299                            } catch (final ClassFormatException cfe) {
300                                throw new ClassConstraintException("Illegal descriptor (==signature) '" + localsig + "' used by LocalVariable '"
301                                        + tostring(localvariable) + "' referenced by '" + tostring(lvt) + "'.", cfe);
302                            }
303                            final int localindex = localvariable.getIndex();
304                            if ((t == Type.LONG || t == Type.DOUBLE ? localindex + 1 : localindex) >= obj.getMaxLocals()) {
305                                throw new ClassConstraintException("LocalVariableTable attribute '" + tostring(lvt) + "' references a LocalVariable '"
306                                        + tostring(localvariable) + "' with an index that exceeds the surrounding Code attribute's max_locals value of '"
307                                        + obj.getMaxLocals() + "'.");
308                            }
309
310                            try {
311                                localVariablesInfos[methodNumber].add(localindex, localname, localvariable.getStartPC(), localvariable.getLength(), t);
312                            } catch (final LocalVariableInfoInconsistentException lviie) {
313                                throw new ClassConstraintException("Conflicting information in LocalVariableTable '" + tostring(lvt)
314                                        + "' found in Code attribute '" + tostring(obj) + "' (method '" + tostring(m) + "'). " + lviie.getMessage(), lviie);
315                            }
316                        } // for all local variables localvariables[i] in the LocalVariableTable attribute atts[a] END
317
318                        numOfLvtAttribs++;
319                        if (!m.isStatic() && numOfLvtAttribs > obj.getMaxLocals()) {
320                            throw new ClassConstraintException("Number of LocalVariableTable attributes of Code attribute '" + tostring(obj) + "' (method '"
321                                    + tostring(m) + "') exceeds number of local variable slots '" + obj.getMaxLocals()
322                                    + "' ('There may be at most one LocalVariableTable attribute per local variable in the Code attribute.').");
323                        }
324                    } // if atts[a] instanceof LocalVariableTable END
325                } // for all attributes atts[a] END
326
327            } catch (final ClassNotFoundException e) {
328                // FIXME: this might not be the best way to handle missing classes.
329                throw new AssertionViolatedException("Missing class: " + e, e);
330            }
331
332        } // visitCode(Code) END
333
334        @Override
335        public void visitCodeException(final CodeException obj) {
336            // Code constraints are checked in Pass3 (3a and 3b).
337            // This does not represent an Attribute but is only
338            // related to internal BCEL data representation.
339
340            // see visitCode(Code)
341        }
342
343        /////////////////////////////
344        // CONSTANTS (vmspec2 4.4) //
345        /////////////////////////////
346        @Override
347        public void visitConstantClass(final ConstantClass obj) {
348            if (obj.getTag() != Const.CONSTANT_Class) {
349                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
350            }
351            checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
352
353        }
354
355        @Override
356        public void visitConstantDouble(final ConstantDouble obj) {
357            if (obj.getTag() != Const.CONSTANT_Double) {
358                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
359            }
360            // no indices to check
361        }
362
363        @Override
364        public void visitConstantFieldref(final ConstantFieldref obj) {
365            if (obj.getTag() != Const.CONSTANT_Fieldref) {
366                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
367            }
368            checkIndex(obj, obj.getClassIndex(), CONST_Class);
369            checkIndex(obj, obj.getNameAndTypeIndex(), CONST_NameAndType);
370        }
371
372        @Override
373        public void visitConstantFloat(final ConstantFloat obj) {
374            if (obj.getTag() != Const.CONSTANT_Float) {
375                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
376            }
377            // no indices to check
378        }
379
380        @Override
381        public void visitConstantInteger(final ConstantInteger obj) {
382            if (obj.getTag() != Const.CONSTANT_Integer) {
383                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
384            }
385            // no indices to check
386        }
387
388        @Override
389        public void visitConstantInterfaceMethodref(final ConstantInterfaceMethodref obj) {
390            if (obj.getTag() != Const.CONSTANT_InterfaceMethodref) {
391                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
392            }
393            checkIndex(obj, obj.getClassIndex(), CONST_Class);
394            checkIndex(obj, obj.getNameAndTypeIndex(), CONST_NameAndType);
395        }
396
397        @Override
398        public void visitConstantLong(final ConstantLong obj) {
399            if (obj.getTag() != Const.CONSTANT_Long) {
400                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
401            }
402            // no indices to check
403        }
404
405        @Override
406        public void visitConstantMethodref(final ConstantMethodref obj) {
407            if (obj.getTag() != Const.CONSTANT_Methodref) {
408                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
409            }
410            checkIndex(obj, obj.getClassIndex(), CONST_Class);
411            checkIndex(obj, obj.getNameAndTypeIndex(), CONST_NameAndType);
412        }
413
414        @Override
415        public void visitConstantNameAndType(final ConstantNameAndType obj) {
416            if (obj.getTag() != Const.CONSTANT_NameAndType) {
417                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
418            }
419            checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
420            // checkIndex(obj, obj.getDescriptorIndex(), CONST_Utf8); //inconsistently named in BCEL, see below.
421            checkIndex(obj, obj.getSignatureIndex(), CONST_Utf8);
422        }
423
424        @Override
425        public void visitConstantPool(final ConstantPool obj) {
426            // No need to. We're piggybacked by the DescendingVisitor.
427            // This does not represent an Attribute but is only
428            // related to internal BCEL data representation.
429        }
430
431        @Override
432        public void visitConstantString(final ConstantString obj) {
433            if (obj.getTag() != Const.CONSTANT_String) {
434                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
435            }
436            checkIndex(obj, obj.getStringIndex(), CONST_Utf8);
437        }
438
439        @Override
440        public void visitConstantUtf8(final ConstantUtf8 obj) {
441            if (obj.getTag() != Const.CONSTANT_Utf8) {
442                throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
443            }
444            // no indices to check
445        }
446
447        ////////////////////////////////////////////////////////
448        // field_info-structure-ATTRIBUTES (vmspec2 4.5, 4.7) //
449        ////////////////////////////////////////////////////////
450        @Override
451        public void visitConstantValue(final ConstantValue obj) { // vmspec2 4.7.2
452            // Despite its name, this really is an Attribute,
453            // not a constant!
454            checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
455
456            final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes();
457            if (!name.equals("ConstantValue")) {
458                throw new ClassConstraintException(
459                    "The ConstantValue attribute '" + tostring(obj) + "' is not correctly named 'ConstantValue' but '" + name + "'.");
460            }
461
462            final Object pred = carrier.predecessor();
463            if (pred instanceof Field) { // ConstantValue attributes are quite senseless if the predecessor is not a field.
464                final Field f = (Field) pred;
465                // Field constraints have been checked before -- so we are safe using their type information.
466                final Type fieldType = Type.getType(((ConstantUtf8) cp.getConstant(f.getSignatureIndex())).getBytes());
467
468                final int index = obj.getConstantValueIndex();
469                if (index < 0 || index >= cplen) {
470                    throw new ClassConstraintException("Invalid index '" + index + "' used by '" + tostring(obj) + "'.");
471                }
472                final Constant c = cp.getConstant(index);
473
474                if (CONST_Long.isInstance(c) && fieldType.equals(Type.LONG) || CONST_Float.isInstance(c) && fieldType.equals(Type.FLOAT)) {
475                    return;
476                }
477                if (CONST_Double.isInstance(c) && fieldType.equals(Type.DOUBLE)) {
478                    return;
479                }
480                if (CONST_Integer.isInstance(c) && (fieldType.equals(Type.INT) || fieldType.equals(Type.SHORT) || fieldType.equals(Type.CHAR)
481                    || fieldType.equals(Type.BYTE) || fieldType.equals(Type.BOOLEAN))) {
482                    return;
483                }
484                if (CONST_String.isInstance(c) && fieldType.equals(Type.STRING)) {
485                    return;
486                }
487
488                throw new ClassConstraintException("Illegal type of ConstantValue '" + obj + "' embedding Constant '" + c + "'. It is referenced by field '"
489                    + tostring(f) + "' expecting a different type: '" + fieldType + "'.");
490            }
491        }
492
493        @Override
494        public void visitDeprecated(final Deprecated obj) { // vmspec2 4.7.10
495            checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
496
497            final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes();
498            if (!name.equals("Deprecated")) {
499                throw new ClassConstraintException("The Deprecated attribute '" + tostring(obj) + "' is not correctly named 'Deprecated' but '" + name + "'.");
500            }
501        }
502
503        @Override
504        public void visitExceptionTable(final ExceptionTable obj) { // vmspec2 4.7.4
505            try {
506                // incorrectly named, it's the Exceptions attribute (vmspec2 4.7.4)
507                checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
508
509                final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes();
510                if (!name.equals("Exceptions")) {
511                    throw new ClassConstraintException(
512                        "The Exceptions attribute '" + tostring(obj) + "' is not correctly named 'Exceptions' but '" + name + "'.");
513                }
514
515                final int[] excIndices = obj.getExceptionIndexTable();
516
517                for (final int excIndice : excIndices) {
518                    checkIndex(obj, excIndice, CONST_Class);
519
520                    final ConstantClass cc = (ConstantClass) cp.getConstant(excIndice);
521                    checkIndex(cc, cc.getNameIndex(), CONST_Utf8); // can't be sure this ConstantClass has already been visited (checked)!
522                    // convert internal notation on-the-fly to external notation:
523                    final String cname = Utility.pathToPackage(((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getBytes());
524
525                    Verifier v = VerifierFactory.getVerifier(cname);
526                    VerificationResult vr = v.doPass1();
527
528                    if (vr != VerificationResult.VR_OK) {
529                        throw new ClassConstraintException("Exceptions attribute '" + tostring(obj) + "' references '" + cname
530                            + "' as an Exception but it does not pass verification pass 1: " + vr);
531                    }
532                    // We cannot safely trust any other "instanceof" mechanism. We need to transitively verify
533                    // the ancestor hierarchy.
534                    JavaClass e = Repository.lookupClass(cname);
535                    final JavaClass t = Repository.lookupClass(Type.THROWABLE.getClassName());
536                    final JavaClass o = Repository.lookupClass(Type.OBJECT.getClassName());
537                    final Set<String> ancestors = new HashSet<>(); // save class names to detect circular inheritance
538                    while (e != o) {
539                        if (e == t) {
540                            break; // It's a subclass of Throwable, OKAY, leave.
541                        }
542                        if (!ancestors.add(e.getClassName())) {
543                            throw new ClassConstraintException("Exceptions attribute '" + tostring(obj) + "' references '" + cname
544                                + "' as an Exception but its superclass hierarchy is circular at '" + e.getClassName() + "'.");
545                        }
546
547                        v = VerifierFactory.getVerifier(e.getSuperclassName());
548                        vr = v.doPass1();
549                        if (vr != VerificationResult.VR_OK) {
550                            throw new ClassConstraintException("Exceptions attribute '" + tostring(obj) + "' references '" + cname + "' as an Exception but '"
551                                + e.getSuperclassName() + "' in the ancestor hierachy does not pass verification pass 1: " + vr);
552                        }
553                        e = Repository.lookupClass(e.getSuperclassName());
554                    }
555                    if (e != t) {
556                        throw new ClassConstraintException("Exceptions attribute '" + tostring(obj) + "' references '" + cname
557                            + "' as an Exception but it is not a subclass of '" + t.getClassName() + "'.");
558                    }
559                }
560
561            } catch (final ClassNotFoundException e) {
562                // FIXME: this might not be the best way to handle missing classes.
563                throw new AssertionViolatedException("Missing class: " + e, e);
564            }
565        }
566
567        //////////////////////////
568        // FIELDS (vmspec2 4.5) //
569        //////////////////////////
570        @Override
571        public void visitField(final Field obj) {
572
573            if (jc.isClass()) {
574                int maxone = 0;
575                if (obj.isPrivate()) {
576                    maxone++;
577                }
578                if (obj.isProtected()) {
579                    maxone++;
580                }
581                if (obj.isPublic()) {
582                    maxone++;
583                }
584                if (maxone > 1) {
585                    throw new ClassConstraintException(
586                        "Field '" + tostring(obj) + "' must only have at most one of its ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC modifiers set.");
587                }
588
589                if (obj.isFinal() && obj.isVolatile()) {
590                    throw new ClassConstraintException(
591                        "Field '" + tostring(obj) + "' must only have at most one of its ACC_FINAL, ACC_VOLATILE modifiers set.");
592                }
593            } else { // isInterface!
594                if (!obj.isPublic()) {
595                    throw new ClassConstraintException("Interface field '" + tostring(obj) + "' must have the ACC_PUBLIC modifier set but hasn't.");
596                }
597                if (!obj.isStatic()) {
598                    throw new ClassConstraintException("Interface field '" + tostring(obj) + "' must have the ACC_STATIC modifier set but hasn't.");
599                }
600                if (!obj.isFinal()) {
601                    throw new ClassConstraintException("Interface field '" + tostring(obj) + "' must have the ACC_FINAL modifier set but hasn't.");
602                }
603            }
604
605            if ((obj.getAccessFlags() & ~(Const.ACC_PUBLIC | Const.ACC_PRIVATE | Const.ACC_PROTECTED | Const.ACC_STATIC | Const.ACC_FINAL | Const.ACC_VOLATILE |
606                Const.ACC_TRANSIENT)) > 0) {
607                addMessage("Field '" + tostring(obj) + "' has access flag(s) other than ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED,"
608                    + " ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_TRANSIENT set (ignored).");
609            }
610
611            checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
612
613            final String name = obj.getName();
614            if (!validFieldName(name)) {
615                throw new ClassConstraintException("Field '" + tostring(obj) + "' has illegal name '" + obj.getName() + "'.");
616            }
617
618            // A descriptor is often named signature in BCEL
619            checkIndex(obj, obj.getSignatureIndex(), CONST_Utf8);
620
621            final String sig = ((ConstantUtf8) cp.getConstant(obj.getSignatureIndex())).getBytes(); // Field or Method sig.(=descriptor)
622
623            try {
624                Type.getType(sig); /* Don't need the return value */
625            } catch (final ClassFormatException cfe) {
626                throw new ClassConstraintException("Illegal descriptor (==signature) '" + sig + "' used by '" + tostring(obj) + "'.", cfe);
627            }
628
629            final String nameanddesc = name + sig;
630            if (fieldNamesAndDesc.contains(nameanddesc)) {
631                throw new ClassConstraintException("No two fields (like '" + tostring(obj) + "') are allowed have same names and descriptors.");
632            }
633            if (fieldNames.contains(name)) {
634                addMessage("More than one field of name '" + name + "' detected (but with different type descriptors). This is very unusual.");
635            }
636            fieldNamesAndDesc.add(nameanddesc);
637            fieldNames.add(name);
638
639            final Attribute[] atts = obj.getAttributes();
640            for (final Attribute att : atts) {
641                if (!(att instanceof ConstantValue) && !(att instanceof Synthetic) && !(att instanceof Deprecated)) {
642                    addMessage("Attribute '" + tostring(att) + "' as an attribute of Field '" + tostring(obj) + "' is unknown and will therefore be ignored.");
643                }
644                if (!(att instanceof ConstantValue)) {
645                    addMessage("Attribute '" + tostring(att) + "' as an attribute of Field '" + tostring(obj)
646                        + "' is not a ConstantValue and is therefore only of use for debuggers and such.");
647                }
648            }
649        }
650
651        @Override
652        public void visitInnerClass(final InnerClass obj) {
653            // This does not represent an Attribute but is only
654            // related to internal BCEL data representation.
655        }
656
657        @Override
658        public void visitInnerClasses(final InnerClasses innerClasses) { // vmspec2 4.7.5
659
660            // exactly one InnerClasses attr per ClassFile if some inner class is refernced: see visitJavaClass()
661
662            checkIndex(innerClasses, innerClasses.getNameIndex(), CONST_Utf8);
663
664            final String name = ((ConstantUtf8) cp.getConstant(innerClasses.getNameIndex())).getBytes();
665            if (!name.equals("InnerClasses")) {
666                throw new ClassConstraintException(
667                    "The InnerClasses attribute '" + tostring(innerClasses) + "' is not correctly named 'InnerClasses' but '" + name + "'.");
668            }
669
670            innerClasses.forEach(ic -> {
671                checkIndex(innerClasses, ic.getInnerClassIndex(), CONST_Class);
672                final int outerIdx = ic.getOuterClassIndex();
673                if (outerIdx != 0) {
674                    checkIndex(innerClasses, outerIdx, CONST_Class);
675                }
676                final int innernameIdx = ic.getInnerNameIndex();
677                if (innernameIdx != 0) {
678                    checkIndex(innerClasses, innernameIdx, CONST_Utf8);
679                }
680                int acc = ic.getInnerAccessFlags();
681                acc &= ~(Const.ACC_PUBLIC | Const.ACC_PRIVATE | Const.ACC_PROTECTED | Const.ACC_STATIC | Const.ACC_FINAL | Const.ACC_INTERFACE |
682                    Const.ACC_ABSTRACT);
683                if (acc != 0) {
684                    addMessage("Unknown access flag for inner class '" + tostring(ic) + "' set (InnerClasses attribute '" + tostring(innerClasses) + "').");
685                }
686            });
687            // Semantical consistency is not yet checked by Sun, see vmspec2 4.7.5.
688            // [marked TODO in JustIce]
689        }
690
691        ///////////////////////////////////////
692        // ClassFile structure (vmspec2 4.1) //
693        ///////////////////////////////////////
694        @Override
695        public void visitJavaClass(final JavaClass obj) {
696            final Attribute[] atts = obj.getAttributes();
697            boolean foundSourceFile = false;
698            boolean foundInnerClasses = false;
699
700            // Is there an InnerClass referenced?
701            // This is a costly check; existing verifiers don't do it!
702            final boolean hasInnerClass = new InnerClassDetector(jc).innerClassReferenced();
703
704            for (final Attribute att : atts) {
705                if (!(att instanceof SourceFile) && !(att instanceof Deprecated) && !(att instanceof InnerClasses) && !(att instanceof Synthetic)) {
706                    addMessage("Attribute '" + tostring(att) + "' as an attribute of the ClassFile structure '" + tostring(obj)
707                        + "' is unknown and will therefore be ignored.");
708                }
709
710                if (att instanceof SourceFile) {
711                    if (foundSourceFile) {
712                        throw new ClassConstraintException(
713                            "A ClassFile structure (like '" + tostring(obj) + "') may have no more than one SourceFile attribute."); // vmspec2 4.7.7
714                    }
715                    foundSourceFile = true;
716                }
717
718                if (att instanceof InnerClasses) {
719                    if (!foundInnerClasses) {
720                        foundInnerClasses = true;
721                    } else if (hasInnerClass) {
722                        throw new ClassConstraintException("A Classfile structure (like '" + tostring(obj) + "') must have exactly one InnerClasses attribute"
723                            + " if at least one Inner Class is referenced (which is the case). More than one InnerClasses attribute was found.");
724                    }
725                    if (!hasInnerClass) {
726                        addMessage("No referenced Inner Class found, but InnerClasses attribute '" + tostring(att)
727                            + "' found. Strongly suggest removal of that attribute.");
728                    }
729                }
730
731            }
732            if (hasInnerClass && !foundInnerClasses) {
733                // throw new ClassConstraintException("A Classfile structure (like '"+tostring(obj)+
734                // "') must have exactly one InnerClasses attribute if at least one Inner Class is referenced (which is the case)."+
735                // " No InnerClasses attribute was found.");
736                // vmspec2, page 125 says it would be a constraint: but existing verifiers
737                // don't check it and javac doesn't satisfy it when it comes to anonymous
738                // inner classes
739                addMessage("A Classfile structure (like '" + tostring(obj)
740                    + "') must have exactly one InnerClasses attribute if at least one Inner Class is referenced (which is the case)."
741                    + " No InnerClasses attribute was found.");
742            }
743        }
744
745        @Override
746        public void visitLineNumber(final LineNumber obj) {
747            // This does not represent an Attribute but is only
748            // related to internal BCEL data representation.
749
750            // see visitLineNumberTable(LineNumberTable)
751        }
752
753        // SYNTHETIC: see above
754        // DEPRECATED: see above
755        //////////////////////////////////////////////////////////////
756        // code_attribute-structure-ATTRIBUTES (vmspec2 4.7.3, 4.7) //
757        //////////////////////////////////////////////////////////////
758        @Override
759        public void visitLineNumberTable(final LineNumberTable obj) { // vmspec2 4.7.8
760            checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
761
762            final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes();
763            if (!name.equals("LineNumberTable")) {
764                throw new ClassConstraintException(
765                    "The LineNumberTable attribute '" + tostring(obj) + "' is not correctly named 'LineNumberTable' but '" + name + "'.");
766            }
767
768            // In JustIce, this check is delayed to Pass 3a.
769            // LineNumber[] linenumbers = obj.getLineNumberTable();
770            // ...validity check...
771
772        }
773
774        //////////
775        // BCEL //
776        //////////
777        @Override
778        public void visitLocalVariable(final LocalVariable obj) {
779            // This does not represent an Attribute but is only
780            // related to internal BCEL data representation.
781
782            // see visitLocalVariableTable(LocalVariableTable)
783        }
784
785        @Override
786        public void visitLocalVariableTable(final LocalVariableTable obj) { // vmspec2 4.7.9
787            // In JustIce, this check is partially delayed to Pass 3a.
788            // The other part can be found in the visitCode(Code) method.
789        }
790
791        ///////////////////////////
792        // METHODS (vmspec2 4.6) //
793        ///////////////////////////
794        @Override
795        public void visitMethod(final Method obj) {
796
797            checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
798
799            final String name = obj.getName();
800            if (!validMethodName(name, true)) {
801                throw new ClassConstraintException("Method '" + tostring(obj) + "' has illegal name '" + name + "'.");
802            }
803
804            // A descriptor is often named signature in BCEL
805            checkIndex(obj, obj.getSignatureIndex(), CONST_Utf8);
806
807            final String sig = ((ConstantUtf8) cp.getConstant(obj.getSignatureIndex())).getBytes(); // Method's signature(=descriptor)
808
809            final Type t;
810            final Type[] ts; // needed below the try block.
811            try {
812                t = Type.getReturnType(sig);
813                ts = Type.getArgumentTypes(sig);
814            } catch (final ClassFormatException cfe) {
815                throw new ClassConstraintException("Illegal descriptor (==signature) '" + sig + "' used by Method '" + tostring(obj) + "'.", cfe);
816            }
817
818            // Check if referenced objects exist.
819            Type act = t;
820            if (act instanceof ArrayType) {
821                act = ((ArrayType) act).getBasicType();
822            }
823            if (act instanceof ObjectType) {
824                final Verifier v = VerifierFactory.getVerifier(((ObjectType) act).getClassName());
825                final VerificationResult vr = v.doPass1();
826                if (vr != VerificationResult.VR_OK) {
827                    throw new ClassConstraintException(
828                        "Method '" + tostring(obj) + "' has a return type that does not pass verification pass 1: '" + vr + "'.");
829                }
830            }
831
832            for (final Type element : ts) {
833                act = element;
834                if (act instanceof ArrayType) {
835                    act = ((ArrayType) act).getBasicType();
836                }
837                if (act instanceof ObjectType) {
838                    final Verifier v = VerifierFactory.getVerifier(((ObjectType) act).getClassName());
839                    final VerificationResult vr = v.doPass1();
840                    if (vr != VerificationResult.VR_OK) {
841                        throw new ClassConstraintException(
842                            "Method '" + tostring(obj) + "' has an argument type that does not pass verification pass 1: '" + vr + "'.");
843                    }
844                }
845            }
846
847            // Nearly forgot this! Funny return values are allowed, but a non-empty arguments list makes a different method out of
848            // it!
849            if (name.equals(Const.STATIC_INITIALIZER_NAME) && ts.length != 0) {
850                throw new ClassConstraintException("Method '" + tostring(obj) + "' has illegal name '" + name + "'."
851                    + " Its name resembles the class or interface initialization method which it isn't because of its arguments (==descriptor).");
852            }
853
854            if (jc.isClass()) {
855                int maxone = 0;
856                if (obj.isPrivate()) {
857                    maxone++;
858                }
859                if (obj.isProtected()) {
860                    maxone++;
861                }
862                if (obj.isPublic()) {
863                    maxone++;
864                }
865                if (maxone > 1) {
866                    throw new ClassConstraintException(
867                        "Method '" + tostring(obj) + "' must only have at most one of its ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC modifiers set.");
868                }
869
870                if (obj.isAbstract()) {
871                    if (obj.isFinal()) {
872                        throw new ClassConstraintException("Abstract method '" + tostring(obj) + "' must not have the ACC_FINAL modifier set.");
873                    }
874                    if (obj.isNative()) {
875                        throw new ClassConstraintException("Abstract method '" + tostring(obj) + "' must not have the ACC_NATIVE modifier set.");
876                    }
877                    if (obj.isPrivate()) {
878                        throw new ClassConstraintException("Abstract method '" + tostring(obj) + "' must not have the ACC_PRIVATE modifier set.");
879                    }
880                    if (obj.isStatic()) {
881                        throw new ClassConstraintException("Abstract method '" + tostring(obj) + "' must not have the ACC_STATIC modifier set.");
882                    }
883                    if (obj.isStrictfp()) {
884                        throw new ClassConstraintException("Abstract method '" + tostring(obj) + "' must not have the ACC_STRICT modifier set.");
885                    }
886                    if (obj.isSynchronized()) {
887                        throw new ClassConstraintException("Abstract method '" + tostring(obj) + "' must not have the ACC_SYNCHRONIZED modifier set.");
888                    }
889                }
890
891                // A specific instance initialization method... (vmspec2,Page 116).
892                // ..may have at most one of ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC set: is checked above.
893                // ..may also have ACC_STRICT set, but none of the other flags in table 4.5 (vmspec2, page 115)
894                if (name.equals(Const.CONSTRUCTOR_NAME) && (obj.isStatic() || obj.isFinal() || obj.isSynchronized() || obj.isNative() || obj.isAbstract())) {
895                    throw new ClassConstraintException("Instance initialization method '" + tostring(obj) + "' must not have"
896                            + " any of the ACC_STATIC, ACC_FINAL, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT modifiers set.");
897                }
898            } else if (!name.equals(Const.STATIC_INITIALIZER_NAME)) { // vmspec2, p.116, 2nd paragraph
899                if (jc.getMajor() >= Const.MAJOR_1_8) {
900                    if (obj.isPublic() == obj.isPrivate()) {
901                        throw new ClassConstraintException(
902                            "Interface method '" + tostring(obj) + "' must have exactly one of its ACC_PUBLIC and ACC_PRIVATE modifiers set.");
903                    }
904                    if (obj.isProtected() || obj.isFinal() || obj.isSynchronized() || obj.isNative()) {
905                        throw new ClassConstraintException("Interface method '" + tostring(obj) + "' must not have"
906                            + " any of the ACC_PROTECTED, ACC_FINAL, ACC_SYNCHRONIZED, or ACC_NATIVE modifiers set.");
907                    }
908
909                } else {
910                    if (!obj.isPublic()) {
911                        throw new ClassConstraintException("Interface method '" + tostring(obj) + "' must have the ACC_PUBLIC modifier set but hasn't.");
912                    }
913                    if (!obj.isAbstract()) {
914                        throw new ClassConstraintException("Interface method '" + tostring(obj) + "' must have the ACC_ABSTRACT modifier set but hasn't.");
915                    }
916                    if (obj.isPrivate() || obj.isProtected() || obj.isStatic() || obj.isFinal() || obj.isSynchronized() || obj.isNative() || obj.isStrictfp()) {
917                        throw new ClassConstraintException("Interface method '" + tostring(obj) + "' must not have"
918                            + " any of the ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_SYNCHRONIZED,"
919                            + " ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT modifiers set.");
920                    }
921                }
922            }
923
924            if ((obj.getAccessFlags() & ~(Const.ACC_PUBLIC | Const.ACC_PRIVATE | Const.ACC_PROTECTED | Const.ACC_STATIC | Const.ACC_FINAL |
925                Const.ACC_SYNCHRONIZED | Const.ACC_NATIVE | Const.ACC_ABSTRACT | Const.ACC_STRICT)) > 0) {
926                addMessage("Method '" + tostring(obj) + "' has access flag(s) other than ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,"
927                    + " ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT set (ignored).");
928            }
929
930            final String nameanddesc = name + sig;
931            if (methodNamesAndDesc.contains(nameanddesc)) {
932                throw new ClassConstraintException("No two methods (like '" + tostring(obj) + "') are allowed have same names and desciptors.");
933            }
934            methodNamesAndDesc.add(nameanddesc);
935
936            final Attribute[] atts = obj.getAttributes();
937            int numCodeAtts = 0;
938            for (final Attribute att : atts) {
939                if (!(att instanceof Code) && !(att instanceof ExceptionTable) && !(att instanceof Synthetic) && !(att instanceof Deprecated)) {
940                    addMessage("Attribute '" + tostring(att) + "' as an attribute of Method '" + tostring(obj) + "' is unknown and will therefore be ignored.");
941                }
942                if (!(att instanceof Code) && !(att instanceof ExceptionTable)) {
943                    addMessage("Attribute '" + tostring(att) + "' as an attribute of Method '" + tostring(obj)
944                        + "' is neither Code nor Exceptions and is therefore only of use for debuggers and such.");
945                }
946                if (att instanceof Code && (obj.isNative() || obj.isAbstract())) {
947                    throw new ClassConstraintException(
948                        "Native or abstract methods like '" + tostring(obj) + "' must not have a Code attribute like '" + tostring(att) + "'."); // vmspec2
949                                                                                                                                                 // page120,
950                                                                                                                                                 // 4.7.3
951                }
952                if (att instanceof Code) {
953                    numCodeAtts++;
954                }
955            }
956            if (!obj.isNative() && !obj.isAbstract() && numCodeAtts != 1) {
957                throw new ClassConstraintException(
958                    "Non-native, non-abstract methods like '" + tostring(obj) + "' must have exactly one Code attribute (found: " + numCodeAtts + ").");
959            }
960        }
961
962        ///////////////////////////////////////////////////////
963        // ClassFile-structure-ATTRIBUTES (vmspec2 4.1, 4.7) //
964        ///////////////////////////////////////////////////////
965        @Override
966        public void visitSourceFile(final SourceFile obj) { // vmspec2 4.7.7
967
968            // zero or one SourceFile attr per ClassFile: see visitJavaClass()
969
970            checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
971
972            final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes();
973            if (!name.equals("SourceFile")) {
974                throw new ClassConstraintException("The SourceFile attribute '" + tostring(obj) + "' is not correctly named 'SourceFile' but '" + name + "'.");
975            }
976
977            checkIndex(obj, obj.getSourceFileIndex(), CONST_Utf8);
978
979            final String sourceFileName = ((ConstantUtf8) cp.getConstant(obj.getSourceFileIndex())).getBytes(); // ==obj.getSourceFileName() ?
980            final String sourceFileNameLc = StringUtils.toRootLowerCase(sourceFileName);
981
982            if (sourceFileName.indexOf('/') != -1 || sourceFileName.indexOf('\\') != -1 || sourceFileName.indexOf(':') != -1
983                || sourceFileNameLc.lastIndexOf(".java") == -1) {
984                addMessage("SourceFile attribute '" + tostring(obj)
985                    + "' has a funny name: remember not to confuse certain parsers working on javap's output. Also, this name ('" + sourceFileName
986                    + "') is considered an unqualified (simple) file name only.");
987            }
988        }
989
990        @Override
991        public void visitSynthetic(final Synthetic obj) { // vmspec2 4.7.6
992            checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
993            final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes();
994            if (!name.equals("Synthetic")) {
995                throw new ClassConstraintException("The Synthetic attribute '" + tostring(obj) + "' is not correctly named 'Synthetic' but '" + name + "'.");
996            }
997        }
998
999        ////////////////////////////////////////////////////
1000        // MISC-structure-ATTRIBUTES (vmspec2 4.7.1, 4.7) //
1001        ////////////////////////////////////////////////////
1002        @Override
1003        public void visitUnknown(final Unknown obj) { // vmspec2 4.7.1
1004            // Represents an unknown attribute.
1005            checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
1006
1007            // Maybe only misnamed? Give a (warning) message.
1008            addMessage("Unknown attribute '" + tostring(obj) + "'. This attribute is not known in any context!");
1009        }
1010    }
1011
1012    /**
1013     * A Visitor class that ensures the ConstantCP-subclassed entries of the constant pool are valid. <B>Precondition:
1014     * index-style cross referencing in the constant pool must be valid.</B>
1015     *
1016     * @see #constantPoolEntriesSatisfyStaticConstraints()
1017     * @see org.apache.bcel.classfile.ConstantCP
1018     */
1019    private final class FAMRAV_Visitor extends EmptyVisitor {
1020        private final ConstantPool cp; // ==jc.getConstantPool() -- only here to save typing work.
1021
1022        private FAMRAV_Visitor(final JavaClass jc) {
1023            this.cp = jc.getConstantPool();
1024        }
1025
1026        @Override
1027        public void visitConstantFieldref(final ConstantFieldref obj) {
1028            if (obj.getTag() != Const.CONSTANT_Fieldref) {
1029                throw new ClassConstraintException("ConstantFieldref '" + tostring(obj) + "' has wrong tag.");
1030            }
1031            final int nameAndTypeIndex = obj.getNameAndTypeIndex();
1032            final ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(nameAndTypeIndex);
1033            final String name = ((ConstantUtf8) cp.getConstant(cnat.getNameIndex())).getBytes(); // Field or Method name
1034            if (!validFieldName(name)) {
1035                throw new ClassConstraintException("Invalid field name '" + name + "' referenced by '" + tostring(obj) + "'.");
1036            }
1037
1038            final int classIndex = obj.getClassIndex();
1039            final ConstantClass cc = (ConstantClass) cp.getConstant(classIndex);
1040            final String className = ((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getBytes(); // Class Name in internal form
1041            if (!validClassName(className)) {
1042                throw new ClassConstraintException("Illegal class name '" + className + "' used by '" + tostring(obj) + "'.");
1043            }
1044
1045            final String sig = ((ConstantUtf8) cp.getConstant(cnat.getSignatureIndex())).getBytes(); // Field or Method sig.(=descriptor)
1046
1047            try {
1048                Type.getType(sig); /* Don't need the return value */
1049            } catch (final ClassFormatException cfe) {
1050                throw new ClassConstraintException("Illegal descriptor (==signature) '" + sig + "' used by '" + tostring(obj) + "'.", cfe);
1051            }
1052        }
1053
1054        @Override
1055        public void visitConstantInterfaceMethodref(final ConstantInterfaceMethodref obj) {
1056            if (obj.getTag() != Const.CONSTANT_InterfaceMethodref) {
1057                throw new ClassConstraintException("ConstantInterfaceMethodref '" + tostring(obj) + "' has wrong tag.");
1058            }
1059            final int nameAndTypeIndex = obj.getNameAndTypeIndex();
1060            final ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(nameAndTypeIndex);
1061            final String name = ((ConstantUtf8) cp.getConstant(cnat.getNameIndex())).getBytes(); // Field or Method name
1062            if (!validInterfaceMethodName(name)) {
1063                throw new ClassConstraintException("Invalid (interface) method name '" + name + "' referenced by '" + tostring(obj) + "'.");
1064            }
1065
1066            final int classIndex = obj.getClassIndex();
1067            final ConstantClass cc = (ConstantClass) cp.getConstant(classIndex);
1068            final String className = ((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getBytes(); // Class Name in internal form
1069            if (!validClassName(className)) {
1070                throw new ClassConstraintException("Illegal class name '" + className + "' used by '" + tostring(obj) + "'.");
1071            }
1072
1073            final String sig = ((ConstantUtf8) cp.getConstant(cnat.getSignatureIndex())).getBytes(); // Field or Method sig.(=descriptor)
1074
1075            try {
1076                final Type t = Type.getReturnType(sig);
1077                if (name.equals(Const.STATIC_INITIALIZER_NAME) && t != Type.VOID) {
1078                    addMessage("Class or interface initialization method '" + Const.STATIC_INITIALIZER_NAME + "' usually has VOID return type instead of '" + t
1079                        + "'. Note this is really not a requirement of The Java Virtual Machine Specification, Second Edition.");
1080                }
1081            } catch (final ClassFormatException cfe) {
1082                throw new ClassConstraintException("Illegal descriptor (==signature) '" + sig + "' used by '" + tostring(obj) + "'.", cfe);
1083            }
1084
1085        }
1086
1087        @Override
1088        public void visitConstantMethodref(final ConstantMethodref obj) {
1089            if (obj.getTag() != Const.CONSTANT_Methodref) {
1090                throw new ClassConstraintException("ConstantMethodref '" + tostring(obj) + "' has wrong tag.");
1091            }
1092            final int nameAndTypeIndex = obj.getNameAndTypeIndex();
1093            final ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(nameAndTypeIndex);
1094            final String name = ((ConstantUtf8) cp.getConstant(cnat.getNameIndex())).getBytes(); // Field or Method name
1095            if (!validClassMethodName(name)) {
1096                throw new ClassConstraintException("Invalid (non-interface) method name '" + name + "' referenced by '" + tostring(obj) + "'.");
1097            }
1098
1099            final int classIndex = obj.getClassIndex();
1100            final ConstantClass cc = (ConstantClass) cp.getConstant(classIndex);
1101            final String className = ((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getBytes(); // Class Name in internal form
1102            if (!validClassName(className)) {
1103                throw new ClassConstraintException("Illegal class name '" + className + "' used by '" + tostring(obj) + "'.");
1104            }
1105
1106            final String sig = ((ConstantUtf8) cp.getConstant(cnat.getSignatureIndex())).getBytes(); // Field or Method sig.(=descriptor)
1107
1108            try {
1109                final Type t = Type.getReturnType(sig);
1110                if (name.equals(Const.CONSTRUCTOR_NAME) && t != Type.VOID) {
1111                    throw new ClassConstraintException("Instance initialization method must have VOID return type.");
1112                }
1113            } catch (final ClassFormatException cfe) {
1114                throw new ClassConstraintException("Illegal descriptor (==signature) '" + sig + "' used by '" + tostring(obj) + "'.", cfe);
1115            }
1116        }
1117
1118    }
1119
1120    /**
1121     * This class serves for finding out if a given JavaClass' ConstantPool references an Inner Class. The Java Virtual
1122     * Machine Specification, Second Edition is not very precise about when an "InnerClasses" attribute has to appear.
1123     * However, it states that there has to be exactly one InnerClasses attribute in the ClassFile structure if the constant
1124     * pool of a class or interface refers to any class or interface "that is not a member of a package". Sun does not mean
1125     * "member of the default package". In "Inner Classes Specification" they point out how a "bytecode name" is derived so
1126     * one has to deduce what a class name of a class "that is not a member of a package" looks like: there is at least one
1127     * character in the byte- code name that cannot be part of a legal Java Language Class name (and not equal to '/'). This
1128     * assumption is wrong as the delimiter is '$' for which Character.isJavaIdentifierPart() == true. Hence, you really run
1129     * into trouble if you have a toplevel class called "A$XXX" and another toplevel class called "A" with in inner class
1130     * called "XXX". JustIce cannot repair this; please note that existing verifiers at this time even fail to detect
1131     * missing InnerClasses attributes in pass 2.
1132     */
1133    private static final class InnerClassDetector extends EmptyVisitor {
1134        private boolean hasInnerClass;
1135        private final JavaClass jc;
1136        private final ConstantPool cp;
1137
1138        /** Constructs an InnerClassDetector working on the JavaClass _jc. */
1139        InnerClassDetector(final JavaClass javaClass) {
1140            this.jc = javaClass;
1141            this.cp = jc.getConstantPool();
1142            new DescendingVisitor(jc, this).visit();
1143        }
1144
1145        /**
1146         * Returns if the JavaClass this InnerClassDetector is working on has an Inner Class reference in its constant pool.
1147         *
1148         * @return Whether this InnerClassDetector is working on has an Inner Class reference in its constant pool.
1149         */
1150        public boolean innerClassReferenced() {
1151            return hasInnerClass;
1152        }
1153
1154        /** This method casually visits ConstantClass references. */
1155        @Override
1156        public void visitConstantClass(final ConstantClass obj) {
1157            final Constant c = cp.getConstant(obj.getNameIndex());
1158            if (c instanceof ConstantUtf8) { // Ignore the case where it's not a ConstantUtf8 here, we'll find out later.
1159                final String className = ((ConstantUtf8) c).getBytes();
1160                if (className.startsWith(Utility.packageToPath(jc.getClassName()) + "$")) {
1161                    hasInnerClass = true;
1162                }
1163            }
1164        }
1165    }
1166
1167    /**
1168     * This method is here to save typing work and improve code readability.
1169     */
1170    private static String tostring(final Node n) {
1171        return new StringRepresentation(n).toString();
1172    }
1173
1174    /**
1175     * This method returns true if and only if the supplied String represents a valid method name that may be referenced by
1176     * ConstantMethodref objects.
1177     */
1178    private static boolean validClassMethodName(final String name) {
1179        return validMethodName(name, false);
1180    }
1181
1182    /**
1183     * This method returns true if and only if the supplied String represents a valid Java class name.
1184     */
1185    private static boolean validClassName(final String name) {
1186        /*
1187         * TODO: implement. Are there any restrictions?
1188         */
1189        Objects.requireNonNull(name, "name");
1190        return true;
1191    }
1192
1193    /**
1194     * This method returns true if and only if the supplied String represents a valid Java field name.
1195     */
1196    private static boolean validFieldName(final String name) {
1197        // vmspec2 2.7, vmspec2 2.2
1198        return validJavaIdentifier(name);
1199    }
1200
1201    /**
1202     * This method returns true if and only if the supplied String represents a valid Java interface method name that may be
1203     * referenced by ConstantInterfaceMethodref objects.
1204     */
1205    private static boolean validInterfaceMethodName(final String name) {
1206        // I guess we should assume special names forbidden here.
1207        if (name.startsWith("<")) {
1208            return false;
1209        }
1210        return validJavaLangMethodName(name);
1211    }
1212
1213    /**
1214     * This method returns true if and only if the supplied String represents a valid Java identifier (so-called simple or
1215     * unqualified name).
1216     */
1217    private static boolean validJavaIdentifier(final String name) {
1218        // vmspec2 2.7, vmspec2 2.2
1219        if (name.isEmpty() || !Character.isJavaIdentifierStart(name.charAt(0))) {
1220            return false;
1221        }
1222
1223        for (int i = 1; i < name.length(); i++) {
1224            if (!Character.isJavaIdentifierPart(name.charAt(i))) {
1225                return false;
1226            }
1227        }
1228        return true;
1229    }
1230
1231    /**
1232     * This method returns true if and only if the supplied String represents a valid Java programming language method name
1233     * stored as a simple (non-qualified) name. Conforming to: The Java Virtual Machine Specification, Second Edition,
1234     * �2.7, �2.7.1, �2.2.
1235     */
1236    private static boolean validJavaLangMethodName(final String name) {
1237        return validJavaIdentifier(name);
1238    }
1239
1240    /**
1241     * This method returns true if and only if the supplied String represents a valid method name. This is basically the
1242     * same as a valid identifier name in the Java programming language, but the special name for the instance
1243     * initialization method is allowed and the special name for the class/interface initialization method may be allowed.
1244     */
1245    private static boolean validMethodName(final String name, final boolean allowStaticInit) {
1246        if (validJavaLangMethodName(name)) {
1247            return true;
1248        }
1249
1250        if (allowStaticInit) {
1251            return name.equals(Const.CONSTRUCTOR_NAME) || name.equals(Const.STATIC_INITIALIZER_NAME);
1252        }
1253        return name.equals(Const.CONSTRUCTOR_NAME);
1254    }
1255
1256    /**
1257     * The LocalVariableInfo instances used by Pass3bVerifier. localVariablesInfos[i] denotes the information for the local
1258     * variables of method number i in the JavaClass this verifier operates on.
1259     */
1260    private LocalVariablesInfo[] localVariablesInfos;
1261
1262    /** The Verifier that created this. */
1263    private final Verifier verifier;
1264
1265    /**
1266     * Should only be instantiated by a Verifier.
1267     *
1268     * @param verifier The verifier.
1269     * @see Verifier
1270     */
1271    public Pass2Verifier(final Verifier verifier) {
1272        this.verifier = verifier;
1273    }
1274
1275    /**
1276     * Ensures that the constant pool entries satisfy the static constraints as described in The Java Virtual Machine
1277     * Specification, 2nd Edition.
1278     *
1279     * @throws AssertionViolatedException Thrown if the class is missing.
1280     */
1281    private void constantPoolEntriesSatisfyStaticConstraints() {
1282        try {
1283            // Most of the consistency is handled internally by BCEL; here
1284            // we only have to verify if the indices of the constants point
1285            // to constants of the appropriate type and such.
1286            final JavaClass jc = Repository.lookupClass(verifier.getClassName());
1287            new CPESSC_Visitor(jc); // constructor implicitly traverses jc
1288
1289        } catch (final ClassNotFoundException e) {
1290            // FIXME: this might not be the best way to handle missing classes.
1291            throw new AssertionViolatedException("Missing class: " + e, e);
1292        }
1293    }
1294
1295    /**
1296     * Pass 2 is the pass where static properties of the class file are checked without looking into "Code" arrays of
1297     * methods. This verification pass is usually invoked when a class is resolved; and it may be possible that this
1298     * verification pass has to load in other classes such as superclasses or implemented interfaces. Therefore, Pass 1 is
1299     * run on them.
1300     * <p>
1301     * Note that most referenced classes are <strong>not</strong> loaded in for verification or for an existence check by this pass;
1302     * only the syntactical correctness of their names and descriptors (a.k.a. signatures) is checked.
1303     * </p>
1304     * <p>
1305     * Very few checks that conceptually belong here are delayed until pass 3a in JustIce. JustIce does not only check for
1306     * syntactical correctness but also for semantical sanity - therefore it needs access to the "Code" array of methods in
1307     * a few cases. Please see the pass 3a documentation, too.
1308     * </p>
1309     *
1310     * @see Pass3aVerifier
1311     */
1312    @Override
1313    public VerificationResult do_verify() {
1314        try {
1315            final VerificationResult vr1 = verifier.doPass1();
1316            if (vr1.equals(VerificationResult.VR_OK)) {
1317
1318                // For every method, we could have information about the local variables out of LocalVariableTable attributes of
1319                // the Code attributes.
1320                localVariablesInfos = new LocalVariablesInfo[Repository.lookupClass(verifier.getClassName()).getMethods().length];
1321
1322                VerificationResult vr = VerificationResult.VR_OK; // default.
1323                try {
1324                    constantPoolEntriesSatisfyStaticConstraints();
1325                    fieldAndMethodRefsAreValid();
1326                    everyClassHasAnAccessibleSuperclass();
1327                    finalMethodsAreNotOverridden();
1328                } catch (final ClassConstraintException cce) {
1329                    vr = new VerificationResult(VerificationResult.VERIFIED_REJECTED, cce.getMessage());
1330                }
1331                return vr;
1332            }
1333            return VerificationResult.VR_NOTYET;
1334
1335        } catch (final ClassNotFoundException e) {
1336            // FIXME: this might not be the best way to handle missing classes.
1337            throw new AssertionViolatedException("Missing class: " + e, e);
1338        }
1339    }
1340
1341    /**
1342     * Ensures that every class has a super class and that {@code final} classes are not subclassed. This means, the class
1343     * this Pass2Verifier operates on has proper super classes (transitively) up to {@link Object}. The reason for really
1344     * loading (and Pass1-verifying) all of those classes here is that we need them in Pass2 anyway to verify no final
1345     * methods are overridden (that could be declared anywhere in the ancestor hierarchy).
1346     *
1347     * @throws ClassConstraintException otherwise.
1348     */
1349    private void everyClassHasAnAccessibleSuperclass() {
1350        try {
1351            final Set<String> hs = new HashSet<>(); // save class names to detect circular inheritance
1352            JavaClass jc = Repository.lookupClass(verifier.getClassName());
1353            int supidx = -1;
1354
1355            while (supidx != 0) {
1356                supidx = jc.getSuperclassNameIndex();
1357
1358                if (supidx == 0) {
1359                    if (jc != Repository.lookupClass(Type.OBJECT.getClassName())) {
1360                        throw new ClassConstraintException(
1361                            "Superclass of '" + jc.getClassName() + "' missing but not " + Type.OBJECT.getClassName() + " itself!");
1362                    }
1363                } else {
1364                    final String supername = jc.getSuperclassName();
1365                    if (!hs.add(supername)) { // If supername already is in the list
1366                        throw new ClassConstraintException("Circular superclass hierarchy detected.");
1367                    }
1368                    final Verifier v = VerifierFactory.getVerifier(supername);
1369                    final VerificationResult vr = v.doPass1();
1370
1371                    if (vr != VerificationResult.VR_OK) {
1372                        throw new ClassConstraintException("Could not load in ancestor class '" + supername + "'.");
1373                    }
1374                    jc = Repository.lookupClass(supername);
1375
1376                    if (jc.isFinal()) {
1377                        throw new ClassConstraintException(
1378                            "Ancestor class '" + supername + "' has the FINAL access modifier and must therefore not be subclassed.");
1379                    }
1380                }
1381            }
1382
1383        } catch (final ClassNotFoundException e) {
1384            // FIXME: this might not be the best way to handle missing classes.
1385            throw new AssertionViolatedException("Missing class: " + e, e);
1386        }
1387    }
1388
1389    /**
1390     * Ensures that the ConstantCP-subclassed entries of the constant pool are valid. According to "Yellin: Low Level
1391     * Security in Java", this method does not verify the existence of referenced entities (such as classes) but only the
1392     * formal correctness (such as well-formed signatures). The visitXXX() methods throw ClassConstraintException instances
1393     * otherwise. <B>Precondition: index-style cross referencing in the constant pool must be valid. Simply invoke
1394     * constant_pool_entries_satisfy_static_constraints() before.</B>
1395     *
1396     * @throws AssertionViolatedException Thrown if the class is missing.
1397     * @see #constantPoolEntriesSatisfyStaticConstraints()
1398     */
1399    private void fieldAndMethodRefsAreValid() {
1400        try {
1401            final JavaClass jc = Repository.lookupClass(verifier.getClassName());
1402            final DescendingVisitor v = new DescendingVisitor(jc, new FAMRAV_Visitor(jc));
1403            v.visit();
1404        } catch (final ClassNotFoundException e) {
1405            // FIXME: this might not be the best way to handle missing classes.
1406            throw new AssertionViolatedException("Missing class: " + e, e);
1407        }
1408    }
1409
1410    /**
1411     * Ensures that {@code final} methods are not overridden. <B>Precondition to run this method:
1412     * constant_pool_entries_satisfy_static_constraints() and every_class_has_an_accessible_superclass() have to be invoked
1413     * before (in that order).</B>
1414     *
1415     * @throws AssertionViolatedException Thrown if the class is missing.
1416     * @see #constantPoolEntriesSatisfyStaticConstraints()
1417     * @see #everyClassHasAnAccessibleSuperclass()
1418     */
1419    private void finalMethodsAreNotOverridden() {
1420        try {
1421            final Map<String, String> map = new HashMap<>();
1422            JavaClass jc = Repository.lookupClass(verifier.getClassName());
1423
1424            int supidx = -1;
1425            while (supidx != 0) {
1426                supidx = jc.getSuperclassNameIndex();
1427
1428                final Method[] methods = jc.getMethods();
1429                for (final Method method : methods) {
1430                    final String nameAndSig = method.getName() + method.getSignature();
1431
1432                    if (map.containsKey(nameAndSig) && method.isFinal()) {
1433                        if (!method.isPrivate()) {
1434                            throw new ClassConstraintException("Method '" + nameAndSig + "' in class '" + map.get(nameAndSig)
1435                                + "' overrides the final (not-overridable) definition in class '" + jc.getClassName() + "'.");
1436                        }
1437                        addMessage("Method '" + nameAndSig + "' in class '" + map.get(nameAndSig)
1438                            + "' overrides the final (not-overridable) definition in class '" + jc.getClassName()
1439                            + "'. This is okay, as the original definition was private; however this constraint leverage"
1440                            + " was introduced by JLS 8.4.6 (not vmspec2) and the behavior of the Sun verifiers.");
1441                    } else if (!method.isStatic()) { // static methods don't inherit
1442                        map.put(nameAndSig, jc.getClassName());
1443                    }
1444                }
1445
1446                jc = Repository.lookupClass(jc.getSuperclassName());
1447                // Well, for OBJECT this returns OBJECT so it works (could return anything but must not throw an Exception).
1448            }
1449
1450        } catch (final ClassNotFoundException e) {
1451            // FIXME: this might not be the best way to handle missing classes.
1452            throw new AssertionViolatedException("Missing class: " + e, e);
1453        }
1454
1455    }
1456
1457    /**
1458     * Returns a LocalVariablesInfo object containing information about the usage of the local variables in the Code
1459     * attribute of the said method or {@code null} if the class file this Pass2Verifier operates on could not be
1460     * pass-2-verified correctly. The method number method_nr is the method you get using
1461     * {@code Repository.lookupClass(myOwner.getClassname()).getMethods()[method_nr];}. You should not add own information.
1462     * Leave that to JustIce.
1463     *
1464     * @param methodNr The method number.
1465     * @return The LocalVariablesInfo object or null.
1466     */
1467    public LocalVariablesInfo getLocalVariablesInfo(final int methodNr) {
1468        if (verify() != VerificationResult.VR_OK) {
1469            return null; // It's cached, don't worry.
1470        }
1471        if (methodNr < 0 || methodNr >= localVariablesInfos.length) {
1472            throw new AssertionViolatedException("Method number out of range.");
1473        }
1474        return localVariablesInfos[methodNr];
1475    }
1476}