Package org.apache.bcel.classfile

Examples of org.apache.bcel.classfile.JavaClass


    }

    @Override
    public void visitClassContext(ClassContext classContext) {
        try {
            JavaClass cls = classContext.getJavaClass();
            String superClsName = cls.getSuperclassName();
            if ("java.lang.Object".equals(superClsName)) {
                return;
            }

            if (STRUTS_ACTION_NAME.equals(superClsName)) {
                mtClassName = STRUTS_ACTION_NAME;
                super.visitClassContext(classContext);
            } else if (SERVLET_NAME.equals(superClsName)) {
                mtClassName = SERVLET_NAME;
                super.visitClassContext(classContext);
            } else {
                for (JavaClass mtClass : getMtClasses()) {
                    /*
                     * note: We could just call cls.instanceOf(mtClass) and it
                     * would work for both classes and interfaces, but if
                     * mtClass is an interface it is more efficient to call
                     * cls.implementationOf() and since we're doing this on each
                     * visit that's what we'll do. also note:
                     * implementationOf(mtClass) throws an
                     * IllegalArgumentException when mtClass is not an
                     * interface. See bug#1428253.
                     */
                    if (mtClass.isClass() ? cls.instanceOf(mtClass) : cls.implementationOf(mtClass)) {
                        mtClassName = mtClass.getClassName();
                        super.visitClassContext(classContext);
                        return;
                    }
                }
View Full Code Here


      constraintViolated(o, "Stack top should be an object reference that's not an array reference, but is '"+objectref+"'.");
    }
   
    String field_name = o.getFieldName(cpg);
   
    JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName());
    Field[] fields = jc.getFields();
    Field f = null;
    for (int i=0; i<fields.length; i++){
      if (fields[i].getName().equals(field_name)){
          Type f_type = Type.getType(fields[i].getSignature());
          Type o_type = o.getType(cpg);
          /* TODO: Check if assignment compatibility is sufficient.
           * What does Sun do?
           */
          if (f_type.equals(o_type)){
            f = fields[i];
            break;
          }
      }
    }

    if (f == null){
      JavaClass[] superclasses = jc.getSuperClasses();
      outer:
      for (int j=0; j<superclasses.length; j++){
        fields = superclasses[j].getFields();
        for (int i=0; i<fields.length; i++){
          if (fields[i].getName().equals(field_name)){
View Full Code Here

      constraintViolated(o, "Stack next-to-top should be an object reference that's not an array reference, but is '"+objectref+"'.");
    }
   
    String field_name = o.getFieldName(cpg);
   
    JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName());
    Field[] fields = jc.getFields();
    Field f = null;
    for (int i=0; i<fields.length; i++){
      if (fields[i].getName().equals(field_name)){
          Type f_type = Type.getType(fields[i].getSignature());
          Type o_type = o.getType(cpg);
View Full Code Here

   * Ensures the specific preconditions of the said instruction.
   */
  public void visitPUTSTATIC(PUTSTATIC o){
      try {
    String field_name = o.getFieldName(cpg);
    JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName());
    Field[] fields = jc.getFields();
    Field f = null;
    for (int i=0; i<fields.length; i++){
      if (fields[i].getName().equals(field_name)){
          Type f_type = Type.getType(fields[i].getSignature());
          Type o_type = o.getType(cpg);
View Full Code Here

    }

    @Override
    public void visitClassContext(ClassContext classContext) {

        JavaClass javaClass = classContext.getJavaClass();
        if (!BCELUtil.preTiger(javaClass)) {
            javaClass.accept(this);
        }
    }
View Full Code Here

      return VerificationResult.VR_NOTYET;
    }

    // Pass 3a ran before, so it's safe to assume the JavaClass object is
    // in the BCEL repository.
    JavaClass jc;
    try {
      jc = Repository.lookupClass(myOwner.getClassName());
    } catch (ClassNotFoundException e) {
      // FIXME: maybe not the best way to handle this
      throw new AssertionViolatedException("Missing class: " + e.toString());
    }

    ConstantPoolGen constantPoolGen = new ConstantPoolGen(jc.getConstantPool());
    // Init Visitors
    InstConstraintVisitor icv = new InstConstraintVisitor();
    icv.setConstantPoolGen(constantPoolGen);
   
    ExecutionVisitor ev = new ExecutionVisitor();
    ev.setConstantPoolGen(constantPoolGen);
   
    Method[] methods = jc.getMethods(); // Method no "method_no" exists, we ran Pass3a before on it!

    try{

      MethodGen mg = new MethodGen(methods[method_no], myOwner.getClassName(), constantPoolGen);

      icv.setMethodGen(mg);
       
      ////////////// DFA BEGINS HERE ////////////////
      if (! (mg.isAbstract() || mg.isNative()) ){ // IF mg HAS CODE (See pass 2)
       
        ControlFlowGraph cfg = new ControlFlowGraph(mg);

        // Build the initial frame situation for this method.
        Frame f = new Frame(mg.getMaxLocals(),mg.getMaxStack());
        if ( !mg.isStatic() ){
          if (mg.getName().equals(Constants.CONSTRUCTOR_NAME)){
            Frame._this = new UninitializedObjectType(new ObjectType(jc.getClassName()));
            f.getLocals().set(0, Frame._this);
          }
          else{
            Frame._this = null;
            f.getLocals().set(0, new ObjectType(jc.getClassName()));
          }
        }
        Type[] argtypes = mg.getArgumentTypes();
        int twoslotoffset = 0;
        for (int j=0; j<argtypes.length; j++){
          if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE || argtypes[j] == Type.CHAR || argtypes[j] == Type.BOOLEAN){
            argtypes[j] = Type.INT;
          }
          f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), argtypes[j]);
          if (argtypes[j].getSize() == 2){
            twoslotoffset++;
            f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), Type.UNKNOWN);
          }
        }
        circulationPump(cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev);
      }
    }
    catch (VerifierConstraintViolatedException ce){
      ce.extendMessage("Constraint violated in method '"+methods[method_no]+"':\n","");
      return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage());
    }
    catch (RuntimeException re){
      // These are internal errors

      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      re.printStackTrace(pw);

      throw new AssertionViolatedException("Some RuntimeException occured while verify()ing class '"+jc.getClassName()+"', method '"+methods[method_no]+"'. Original RuntimeException's stack trace:\n---\n"+sw+"---\n");
    }
    return VerificationResult.VR_OK;
  }
View Full Code Here

    }

    @Override
    public void reportMatch(ClassContext classContext, Method method, ByteCodePatternMatch match) throws CFGBuilderException,
    DataflowAnalysisException {
        JavaClass javaClass = classContext.getJavaClass();
        MethodGen methodGen = classContext.getMethodGen(method);
        CFG cfg = classContext.getCFG(method);


        // Get the variable referenced in the pattern instance.
        BindingSet bindingSet = match.getBindingSet();
        Binding binding = bindingSet.lookup("f");

        // Look up the field as an XField.
        // If it is volatile, then the instance is not a bug.
        FieldVariable field = (FieldVariable) binding.getVariable();
        XField xfield = Hierarchy.findXField(field.getClassName(), field.getFieldName(), field.getFieldSig(),
                field.isStatic());
        if (!xfield.isResolved()) {
            return;
        }

        // XXX: for now, ignore lazy initialization of instance fields
        if (!xfield.isStatic()) {
            return;
        }

        // Definitely ignore synthetic class$ fields
        if (xfield.getName().startsWith("class$") || xfield.getName().startsWith("array$")) {
            if (DEBUG) {
                System.out.println("Ignoring field " + xfield.getName());
            }
            return;
        }

        // Ignore non-reference fields
        String signature = xfield.getSignature();
        if (!signature.startsWith("[") && !signature.startsWith("L")) {
            if (DEBUG) {
                System.out.println("Ignoring non-reference field " + xfield.getName());
            }
            return;
        }

        // Strings are (mostly) safe to pass by data race in 1.5
        if (signature.equals("Ljava/lang/String;")) {
            return;
        }

        // GUI types should not be accessed from multiple threads

        if (signature.charAt(0) == 'L') {
            ClassDescriptor fieldType = DescriptorFactory.createClassDescriptorFromFieldSignature(signature);

            while (fieldType != null) {
                XClass fieldClass;
                try {
                    fieldClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, fieldType);
                } catch (CheckedAnalysisException e) {
                    break;
                }

                String name = fieldClass.getClassDescriptor().getClassName();
                if (name.startsWith("java/awt") || name.startsWith("javax/swing")) {
                    return;
                }
                if (name.equals("java/lang/Object")) {
                    break;
                }
                fieldType = fieldClass.getSuperclassDescriptor();
            }
        }

        // Get locations matching the beginning of the object creation,
        // and the final field store.
        PatternElementMatch createBegin = match.getFirstLabeledMatch("createObject");
        PatternElementMatch store = match.getFirstLabeledMatch("end");
        PatternElementMatch test = match.getFirstLabeledMatch("test");
        InstructionHandle testInstructionHandle = test.getMatchedInstructionInstructionHandle();
        if (reported.get(testInstructionHandle.getPosition())) {
            return;
        }

        // Get all blocks
        //
        // (1) dominated by the wildcard instruction matching
        // the beginning of the instructions creating the object, and
        // (2) postdominated by the field store
        //
        // Exception edges are not considered in computing
        // dominators/postdominators.
        // We will consider this to be all of the code that creates
        // the object.
        DominatorsAnalysis domAnalysis = classContext.getNonExceptionDominatorsAnalysis(method);
        PostDominatorsAnalysis postDomAnalysis = classContext.getNonExceptionPostDominatorsAnalysis(method);
        BitSet extent = domAnalysis.getAllDominatedBy(createBegin.getBasicBlock());
        BitSet postDom = postDomAnalysis.getAllDominatedBy(store.getBasicBlock());
        // System.out.println("Extent: " + extent);
        if (DEBUG) {
            System.out.println("test  dominates: " + extent);
            System.out.println("Field store postdominates " + postDom);
        }
        extent.and(postDom);
        if (DEBUG) {
            System.out.println("extent: " + extent);
        }
        // Check all instructions in the object creation extent
        //
        // (1) to determine the common lock set, and
        // (2) to check for NEW and Invoke instructions that might create an
        // object
        //
        // We ignore matches where a lock is held consistently,
        // or if the extent does not appear to create a new object.
        LockDataflow lockDataflow = classContext.getLockDataflow(method);
        LockSet lockSet = null;
        boolean sawNEW = false, sawINVOKE = false;
        for (BasicBlock block : cfg.getBlocks(extent)) {
            for (Iterator<InstructionHandle> j = block.instructionIterator(); j.hasNext();) {
                InstructionHandle handle = j.next();
                if (handle.equals(store.getMatchedInstructionInstructionHandle())) {
                    break;
                }
                Location location = new Location(handle, block);

                // Keep track of whether we saw any instructions
                // that might actually have created a new object.
                Instruction ins = handle.getInstruction();
                if (DEBUG) {
                    System.out.println(location);
                }
                if (ins instanceof AllocationInstruction) {
                    sawNEW = true;
                } else if (ins instanceof InvokeInstruction) {
                    if (ins instanceof INVOKESTATIC
                            && ((INVOKESTATIC) ins).getMethodName(classContext.getConstantPoolGen()).startsWith("new")) {
                        sawNEW = true;
                    }
                    sawINVOKE = true;
                }

                // Compute lock set intersection for all matched
                // instructions.
                LockSet insLockSet = lockDataflow.getFactAtLocation(location);
                if (lockSet == null) {
                    lockSet = new LockSet();
                    lockSet.copyFrom(insLockSet);
                } else {
                    lockSet.intersectWith(insLockSet);
                }
            }
        }

        if (!(sawNEW || sawINVOKE)) {
            return;
        }
        if (lockSet == null) {
            throw new IllegalStateException("lock set is null");
        }
        if (!lockSet.isEmpty()) {
            return;
        }

        boolean sawGetStaticAfterPutStatic = false;
        check: if (signature.startsWith("[") || signature.startsWith("L")) {

            BitSet postStore = domAnalysis.getAllDominatedBy(store.getBasicBlock());
            for (BasicBlock block : cfg.getBlocks(postStore)) {
                for (Iterator<InstructionHandle> j = block.instructionIterator(); j.hasNext();) {
                    InstructionHandle handle = j.next();

                    InstructionHandle nextHandle = handle.getNext();
                    Instruction ins = handle.getInstruction();

                    if (ins instanceof GETSTATIC && potentialInitialization(nextHandle)) {
                        XField field2 = XFactory.createXField((FieldInstruction) ins, methodGen.getConstantPool());
                        if (xfield.equals(field2)) {
                            sawGetStaticAfterPutStatic = true;
                            break check;
                        }
                    }
                }
            }
        }

        // Compute the priority:
        // - ignore lazy initialization of instance fields
        // - when it's done in a public method, emit a high priority warning
        // - protected or default access method, emit a medium priority
        // warning
        // - otherwise, low priority

        if (!sawGetStaticAfterPutStatic && xfield.isVolatile()) {
            return;
        }
        int priority = LOW_PRIORITY;
        boolean isDefaultAccess = (method.getAccessFlags() & (Constants.ACC_PUBLIC | Constants.ACC_PRIVATE | Constants.ACC_PROTECTED)) == 0;
        if (method.isPublic()) {
            priority = NORMAL_PRIORITY;
        } else if (method.isProtected() || isDefaultAccess) {
            priority = NORMAL_PRIORITY;
        }
        if (signature.startsWith("[") || signature.startsWith("Ljava/util/")) {
            priority--;
        }
        if (!sawNEW) {
            priority++;
        }
        if (!sawGetStaticAfterPutStatic && priority < LOW_PRIORITY) {
            priority = LOW_PRIORITY;
        }
        if (classContext.getXClass().usesConcurrency()) {
            priority--;
        }
        // Report the bug.
        InstructionHandle start = match.getLabeledInstruction("start");
        InstructionHandle end = match.getLabeledInstruction("end");
        String sourceFile = javaClass.getSourceFileName();
        bugReporter.reportBug(new BugInstance(this, sawGetStaticAfterPutStatic ? "LI_LAZY_INIT_UPDATE_STATIC"
                : "LI_LAZY_INIT_STATIC", priority).addClassAndMethod(methodGen, sourceFile).addField(xfield)
                .describe("FIELD_ON").addSourceLine(classContext, methodGen, sourceFile, start, end));
        reported.set(testInstructionHandle.getPosition());
View Full Code Here

                    int priority = HIGH_PRIORITY;
                    boolean intentional = false;
                    XMethod m3 = null;
                    try {
                        JavaClass clazz = Repository.lookupClass(m.getClassName());
                        if ((m3 = definedIn(clazz, m2)) != null) {
                            // the method we don't override is also defined in
                            // our class
                            priority = NORMAL_PRIORITY;
                            intentional = true;
View Full Code Here

        this.bugReporter = bugReporter;
    }

    @Override
    public void visitClassContext(ClassContext classContext) {
        JavaClass cls = classContext.getJavaClass();
        clsName = cls.getClassName();
        if (clsName.indexOf('$') >= 0) {
            super.visitClassContext(classContext);
        }
    }
View Full Code Here

        this.bugAccumulator = new BugAccumulator(bugReporter);
    }

    @Override
    public void visitClassContext(ClassContext classContext) {
        JavaClass javaClass = classContext.getJavaClass();

        Method[] methodList = javaClass.getMethods();
        for (Method method : methodList) {
            if (method.getCode() == null) {
                continue;
            }
View Full Code Here

TOP

Related Classes of org.apache.bcel.classfile.JavaClass

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.