1 19 20 package edu.umd.cs.findbugs.detect; 21 22 23 import java.util.HashSet ; 24 import java.util.Iterator ; 25 import java.util.Set ; 26 27 import org.apache.bcel.classfile.Code; 28 29 import edu.umd.cs.findbugs.BugInstance; 30 import edu.umd.cs.findbugs.BugReporter; 31 import edu.umd.cs.findbugs.BytecodeScanningDetector; 32 import edu.umd.cs.findbugs.StatelessDetector; 33 import edu.umd.cs.findbugs.ba.SignatureParser; 34 35 public class FindFieldSelfAssignment extends BytecodeScanningDetector implements StatelessDetector { 36 private BugReporter bugReporter; 37 int state; 38 39 40 public FindFieldSelfAssignment(BugReporter bugReporter) { 41 this.bugReporter = bugReporter; 42 } 43 44 45 46 @Override 47 public void visit(Code obj) { 48 state = 0; 49 super.visit(obj); 50 initializedFields.clear(); 51 } 52 53 54 String f; 55 String className; 56 Set <String > initializedFields = new HashSet <String >(); 57 58 @Override 59 public void sawOpcode(int seen) { 60 61 switch (state) { 62 case 0: 63 if (seen == ALOAD_0) 64 state = 1; 65 break; 66 case 1: 67 if (seen == ALOAD_0) 68 state = 2; 69 else 70 state = 0; 71 break; 72 case 2: 73 if (seen == GETFIELD) { 74 state = 3; 75 f = getRefConstantOperand(); 76 className = getClassConstantOperand(); 77 } else 78 state = 0; 79 break; 80 case 3: 81 if (seen == PUTFIELD && getRefConstantOperand().equals(f) && getClassConstantOperand().equals(className)) { 82 83 int priority = NORMAL_PRIORITY; 84 SignatureParser parser = new SignatureParser(getMethodSig()); 85 boolean foundMatch = false; 86 for(Iterator <String > i = parser.parameterSignatureIterator(); i.hasNext(); ) { 87 String s = i.next(); 88 if (s.equals(getSigConstantOperand())) { 89 foundMatch = true; 90 break; 91 } 92 } 93 if (getMethodName().equals("<init>") && !initializedFields.contains(getRefConstantOperand()) && foundMatch) 94 priority = HIGH_PRIORITY; 95 96 bugReporter.reportBug(new BugInstance(this, "SA_FIELD_SELF_ASSIGNMENT", priority) 97 .addClassAndMethod(this) 98 .addReferencedField(this) 99 .addSourceLine(this)); 100 } 101 state = 0; 102 } 103 104 if (seen == PUTFIELD && getClassConstantOperand().equals(className)) 105 initializedFields.add(getRefConstantOperand()); 106 107 } 108 109 } 110 | Popular Tags |