예제 #1
0
 public SearchResult run(RSClient data, HashMap<String, ClassGen> classes) {
   for (ClassGen c : classes.values()) {
     ConstantPoolGen cpg = c.getConstantPool();
     if (cpg.lookupFloat(16384.0000f) != -1) {
       for (Method m : c.getMethods()) {
         if (m.isStatic()) {
           MethodGen gen = new MethodGen(m, c.getClassName(), cpg);
           InstructionList il = gen.getInstructionList();
           if (il == null) continue;
           InstructionFinder f = new InstructionFinder(il);
           Iterator e = f.search("GETSTATIC LDC FSUB PUTSTATIC");
           if (e.hasNext()) {
             InstructionHandle[] handles = (InstructionHandle[]) e.next();
             data.addField(
                 "MapAngle",
                 ((GETSTATIC) handles[0].getInstruction()).getClassName(cpg)
                     + "."
                     + ((GETSTATIC) handles[0].getInstruction()).getFieldName(cpg));
             return SearchResult.Success;
           }
         }
       }
     }
   }
   return SearchResult.Failure;
 }
 public static @CheckForNull LocalVariableAnnotation findUniqueBestMatchingParameter(
     ClassContext classContext, Method method, String name, String signature) {
   LocalVariableAnnotation match = null;
   int localsThatAreParameters = PreorderVisitor.getNumberArguments(method.getSignature());
   int startIndex = 0;
   if (!method.isStatic()) startIndex = 1;
   SignatureParser parser = new SignatureParser(method.getSignature());
   Iterator<String> signatureIterator = parser.parameterSignatureIterator();
   int lowestCost = Integer.MAX_VALUE;
   for (int i = startIndex; i < localsThatAreParameters + startIndex; i++) {
     String sig = signatureIterator.next();
     if (signature.equals(sig)) {
       LocalVariableAnnotation potentialMatch =
           LocalVariableAnnotation.getLocalVariableAnnotation(method, i, 0, 0);
       if (!potentialMatch.isNamed()) continue;
       int distance = EditDistance.editDistance(name, potentialMatch.getName());
       if (distance < lowestCost) {
         match = potentialMatch;
         match.setDescription(DID_YOU_MEAN_ROLE);
         lowestCost = distance;
       } else if (distance == lowestCost) {
         // not unique best match
         match = null;
       }
       // signatures match
     }
   }
   if (lowestCost < 5) return match;
   return null;
 }
예제 #3
0
  @Override
  public void visit(Method obj) {
    if (getMethodName().equals("suite") && !obj.isStatic()) {
      bugReporter.reportBug(
          new BugInstance(this, "IJU_SUITE_NOT_STATIC", NORMAL_PRIORITY).addClassAndMethod(this));
    }

    if (getMethodName().equals("suite") && obj.getSignature().startsWith("()") && obj.isStatic()) {
      if ((!obj.getSignature().equals("()Ljunit/framework/Test;")
              && !obj.getSignature().equals("()Ljunit/framework/TestSuite;"))
          || !obj.isPublic()) {
        bugReporter.reportBug(
            new BugInstance(this, "IJU_BAD_SUITE_METHOD", NORMAL_PRIORITY).addClassAndMethod(this));
      }
    }
  }
  /* (non-Javadoc)
   * @see edu.umd.cs.findbugs.classfile.IAnalysisEngine#analyze(edu.umd.cs.findbugs.classfile.IAnalysisCache, java.lang.Object)
   */
  public Method analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor)
      throws CheckedAnalysisException {
    JavaClass jclass =
        analysisCache.getClassAnalysis(JavaClass.class, descriptor.getClassDescriptor());
    Method[] methodList = jclass.getMethods();

    Method result = null;

    // As a side-effect, cache all of the Methods for this JavaClass
    for (Method method : methodList) {
      MethodDescriptor methodDescriptor =
          DescriptorFactory.instance()
              .getMethodDescriptor(
                  descriptor.getSlashedClassName(),
                  method.getName(),
                  method.getSignature(),
                  method.isStatic());

      // Put in cache eagerly
      analysisCache.eagerlyPutMethodAnalysis(Method.class, methodDescriptor, method);

      if (methodDescriptor.equals(descriptor)) {
        result = method;
      }
    }

    return result;
  }
예제 #5
0
 /**
  * Construct a MethodDescriptor from JavaClass and method.
  *
  * @param jclass a JavaClass
  * @param method a Method belonging to the JavaClass
  * @return a MethodDescriptor identifying the method
  */
 public static MethodDescriptor getMethodDescriptor(JavaClass jclass, Method method) {
   return DescriptorFactory.instance()
       .getMethodDescriptor(
           jclass.getClassName().replace('.', '/'),
           method.getName(),
           method.getSignature(),
           method.isStatic());
 }
  /**
   * Constructor.
   *
   * @param method an XMethod specifying a specific method in a specific class
   * @throws ClassNotFoundException
   */
  public JavaClassAndMethod(XMethod method) throws ClassNotFoundException {

    this.javaClass = Repository.lookupClass(method.getClassName());
    for (Method m : javaClass.getMethods())
      if (m.getName().equals(method.getName())
          && m.getSignature().equals(method.getSignature())
          && m.isStatic() == method.isStatic()) {
        this.method = m;
        return;
      }
    throw new IllegalArgumentException("Can't find " + method);
  }
예제 #7
0
 /** is there a JUnit3TestSuite */
 private boolean hasSuite(Method[] methods) {
   for (Method m : methods) {
     if (m.getName().equals("suite")
         && m.isPublic()
         && m.isStatic()
         // && m.getReturnType().equals(junit.framework.Test.class)
         // && m.getArgumentTypes().length == 0
         && m.getSignature().equals("()Ljunit/framework/Test;")) {
       return true;
     }
   }
   return false;
 }
예제 #8
0
  /**
   * looks for methods that have it's parameters all follow the form arg0, arg1, arg2, or parm0,
   * parm1, parm2 etc, where the method actually has code in it
   *
   * @param cls the class to check
   */
  private void checkIDEGeneratedParmNames(JavaClass cls) {

    methods:
    for (Method m : cls.getMethods()) {
      if (!m.isPublic()) {
        continue;
      }

      String name = m.getName();
      if (Values.CONSTRUCTOR.equals(name) || Values.STATIC_INITIALIZER.equals(name)) {
        continue;
      }

      LocalVariableTable lvt = m.getLocalVariableTable();
      if (lvt == null) {
        continue;
      }

      if (m.getCode().getCode().length <= MAX_EMPTY_METHOD_SIZE) {
        continue;
      }

      int numArgs = m.getArgumentTypes().length;
      if (numArgs == 0) {
        continue;
      }

      int offset = m.isStatic() ? 0 : 1;

      for (int i = 0; i < numArgs; i++) {
        LocalVariable lv = lvt.getLocalVariable(offset + i, 0);
        if ((lv == null) || (lv.getName() == null)) {
          continue methods;
        }

        Matcher ma = ARG_PATTERN.matcher(lv.getName());
        if (!ma.matches()) {
          continue methods;
        }
      }

      bugReporter.reportBug(
          new BugInstance(
                  this,
                  BugType.IMC_IMMATURE_CLASS_IDE_GENERATED_PARAMETER_NAMES.name(),
                  NORMAL_PRIORITY)
              .addClass(cls)
              .addMethod(cls, m));
      return;
    }
  }
  public static @CheckForNull LocalVariableAnnotation findMatchingIgnoredParameter(
      ClassContext classContext, Method method, String name, String signature) {
    try {
      Dataflow<BitSet, LiveLocalStoreAnalysis> llsaDataflow =
          classContext.getLiveLocalStoreDataflow(method);
      CFG cfg;

      cfg = classContext.getCFG(method);
      LocalVariableAnnotation match = null;
      int lowestCost = Integer.MAX_VALUE;
      BitSet liveStoreSetAtEntry = llsaDataflow.getAnalysis().getResultFact(cfg.getEntry());
      int localsThatAreParameters = PreorderVisitor.getNumberArguments(method.getSignature());
      int startIndex = 0;
      if (!method.isStatic()) startIndex = 1;
      SignatureParser parser = new SignatureParser(method.getSignature());
      Iterator<String> signatureIterator = parser.parameterSignatureIterator();
      for (int i = startIndex; i < localsThatAreParameters + startIndex; i++) {
        String sig = signatureIterator.next();
        if (!liveStoreSetAtEntry.get(i) && signature.equals(sig)) {
          // parameter isn't live and signatures match
          LocalVariableAnnotation potentialMatch =
              LocalVariableAnnotation.getLocalVariableAnnotation(method, i, 0, 0);
          potentialMatch.setDescription(DID_YOU_MEAN_ROLE);
          if (!potentialMatch.isNamed()) return potentialMatch;
          int distance = EditDistance.editDistance(name, potentialMatch.getName());
          if (distance < lowestCost) {
            match = potentialMatch;
            match.setDescription(DID_YOU_MEAN_ROLE);
            lowestCost = distance;
          } else if (distance == lowestCost) {
            // not unique best match
            match = null;
          }
        }
      }
      return match;
    } catch (DataflowAnalysisException e) {
      AnalysisContext.logError("", e);
    } catch (CFGBuilderException e) {
      AnalysisContext.logError("", e);
    }
    return null;
  }
  @Override
  public void visit(Method obj) {

    int accessFlags = obj.getAccessFlags();
    boolean isSynchronized = (accessFlags & ACC_SYNCHRONIZED) != 0;
    if (getMethodName().equals("<init>")
        && getMethodSig().equals("()V")
        && (accessFlags & ACC_PUBLIC) != 0) hasPublicVoidConstructor = true;
    if (!getMethodName().equals("<init>") && isSynthetic(obj)) foundSynthetic = true;
    // System.out.println(methodName + isSynchronized);

    if (getMethodName().equals("readExternal")
        && getMethodSig().equals("(Ljava/io/ObjectInput;)V")) {
      sawReadExternal = true;
      if (DEBUG && !obj.isPrivate())
        System.out.println("Non-private readExternal method in: " + getDottedClassName());
    } else if (getMethodName().equals("writeExternal")
        && getMethodSig().equals("(Ljava/io/Objectoutput;)V")) {
      sawWriteExternal = true;
      if (DEBUG && !obj.isPrivate())
        System.out.println("Non-private writeExternal method in: " + getDottedClassName());
    } else if (getMethodName().equals("readResolve")
        && getMethodSig().startsWith("()")
        && isSerializable) {
      sawReadResolve = true;
      if (!getMethodSig().equals("()Ljava/lang/Object;"))
        bugReporter.reportBug(
            new BugInstance(this, "SE_READ_RESOLVE_MUST_RETURN_OBJECT", HIGH_PRIORITY)
                .addClassAndMethod(this));
      else if (obj.isStatic())
        bugReporter.reportBug(
            new BugInstance(this, "SE_READ_RESOLVE_IS_STATIC", HIGH_PRIORITY)
                .addClassAndMethod(this));
      else if (obj.isPrivate())
        try {
          Set<ClassDescriptor> subtypes =
              AnalysisContext.currentAnalysisContext()
                  .getSubtypes2()
                  .getSubtypes(getClassDescriptor());
          if (subtypes.size() > 1) {
            BugInstance bug =
                new BugInstance(this, "SE_PRIVATE_READ_RESOLVE_NOT_INHERITED", NORMAL_PRIORITY)
                    .addClassAndMethod(this);
            boolean nasty = false;
            for (ClassDescriptor subclass : subtypes)
              if (!subclass.equals(getClassDescriptor())) {

                XClass xSub = AnalysisContext.currentXFactory().getXClass(subclass);
                if (xSub != null
                    && xSub.findMethod("readResolve", "()Ljava/lang/Object;", false) == null
                    && xSub.findMethod("writeReplace", "()Ljava/lang/Object;", false) == null) {
                  bug.addClass(subclass).describe(ClassAnnotation.SUBCLASS_ROLE);
                  nasty = true;
                }
              }
            if (nasty) bug.setPriority(HIGH_PRIORITY);
            else if (!getThisClass().isPublic()) bug.setPriority(LOW_PRIORITY);
            bugReporter.reportBug(bug);
          }

        } catch (ClassNotFoundException e) {
          bugReporter.reportMissingClass(e);
        }

    } else if (getMethodName().equals("readObject")
        && getMethodSig().equals("(Ljava/io/ObjectInputStream;)V")
        && isSerializable) {
      sawReadObject = true;
      if (!obj.isPrivate())
        bugReporter.reportBug(
            new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", HIGH_PRIORITY)
                .addClassAndMethod(this));

    } else if (getMethodName().equals("readObjectNoData")
        && getMethodSig().equals("()V")
        && isSerializable) {

      if (!obj.isPrivate())
        bugReporter.reportBug(
            new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", HIGH_PRIORITY)
                .addClassAndMethod(this));

    } else if (getMethodName().equals("writeObject")
        && getMethodSig().equals("(Ljava/io/ObjectOutputStream;)V")
        && isSerializable) {
      sawWriteObject = true;
      if (!obj.isPrivate())
        bugReporter.reportBug(
            new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", HIGH_PRIORITY)
                .addClassAndMethod(this));
    }

    if (isSynchronized) {
      if (getMethodName().equals("readObject")
          && getMethodSig().equals("(Ljava/io/ObjectInputStream;)V")
          && isSerializable)
        bugReporter.reportBug(
            new BugInstance(this, "RS_READOBJECT_SYNC", NORMAL_PRIORITY).addClass(this));
      else if (getMethodName().equals("writeObject")
          && getMethodSig().equals("(Ljava/io/ObjectOutputStream;)V")
          && isSerializable) writeObjectIsSynchronized = true;
      else foundSynchronizedMethods = true;
    }
    super.visit(obj);
  }
 /**
  * Get the MethodDescriptor that (hopefully) uniqely names this method.
  *
  * @return the MethodDescriptor uniquely naming this method
  */
 public MethodDescriptor toMethodDescriptor() {
   return DescriptorFactory.instance()
       .getMethodDescriptor(
           getSlashedClassName(), method.getName(), method.getSignature(), method.isStatic());
 }