idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
3,200
public void sawOpcode ( int seen ) { try { stack . precomputation ( this ) ; if ( seen == Const . INVOKEINTERFACE ) { KeyType type = isKeyAccessMethod ( seen ) ; if ( type != null ) { int numParms = SignatureUtils . getNumParameters ( getSigConstantOperand ( ) ) ; if ( stack . getStackDepth ( ) >= numParms ) { OpcodeStack . Item item = stack . getStackItem ( numParms - 1 ) ; String parmName = ( String ) item . getConstant ( ) ; if ( parmName != null ) { String upperParmName = parmName . toUpperCase ( Locale . getDefault ( ) ) ; Map < String , Map < String , List < SourceInfo > > > typeMap = parmInfo . get ( KeyType . PARAMETER ) ; Map < String , List < SourceInfo > > parmCaseInfo = typeMap . get ( upperParmName ) ; if ( parmCaseInfo == null ) { parmCaseInfo = new HashMap < > ( ) ; typeMap . put ( upperParmName , parmCaseInfo ) ; } List < SourceInfo > annotations = parmCaseInfo . get ( parmName ) ; if ( annotations == null ) { annotations = new ArrayList < > ( ) ; parmCaseInfo . put ( parmName , annotations ) ; } annotations . add ( new SourceInfo ( getClassName ( ) , getMethodName ( ) , getMethodSig ( ) , getMethod ( ) . isStatic ( ) , SourceLineAnnotation . fromVisitedInstruction ( getClassContext ( ) , this , getPC ( ) ) ) ) ; } } } } } finally { stack . sawOpcode ( this , seen ) ; } }
implements the visitor to look for calls to HttpServletRequest . getParameter and collect what the name of the key is .
3,201
public void report ( ) { for ( Map . Entry < KeyType , Map < String , Map < String , List < SourceInfo > > > > entry : parmInfo . entrySet ( ) ) { KeyType type = entry . getKey ( ) ; Map < String , Map < String , List < SourceInfo > > > typeMap = entry . getValue ( ) ; for ( Map < String , List < SourceInfo > > parmCaseInfo : typeMap . values ( ) ) { if ( parmCaseInfo . size ( ) > 1 ) { BugInstance bi = new BugInstance ( this , type . getDescription ( ) , NORMAL_PRIORITY ) ; for ( Map . Entry < String , List < SourceInfo > > sourceInfos : parmCaseInfo . entrySet ( ) ) { for ( SourceInfo sourceInfo : sourceInfos . getValue ( ) ) { bi . addClass ( sourceInfo . clsName ) ; bi . addMethod ( sourceInfo . clsName , sourceInfo . methodName , sourceInfo . signature , sourceInfo . isStatic ) ; bi . addSourceLine ( sourceInfo . srcLine ) ; bi . addString ( sourceInfos . getKey ( ) ) ; } } bugReporter . reportBug ( bi ) ; } } } parmInfo . clear ( ) ; }
implements the visitor to look for the collected parm names and look for duplicates that are different in casing only .
3,202
public void visitClassContext ( ClassContext classContext ) { try { branchTargets = new BitSet ( ) ; catchTargets = new BitSet ( ) ; stack = new OpcodeStack ( ) ; super . visitClassContext ( classContext ) ; } finally { branchTargets = null ; catchTargets = null ; stack = null ; } }
implements the visitor to create and clear the branchTargets
3,203
public void visitCode ( Code obj ) { Method m = getMethod ( ) ; String sig = m . getSignature ( ) ; if ( ! Values . SIG_VOID . equals ( SignatureUtils . getReturnSignature ( sig ) ) ) { state = State . SEEN_NOTHING ; branchTargets . clear ( ) ; CodeException [ ] ces = obj . getExceptionTable ( ) ; catchTargets . clear ( ) ; stack . resetForMethodEntry ( this ) ; for ( CodeException ce : ces ) { if ( ce . getCatchType ( ) != 0 ) { catchTargets . set ( ce . getHandlerPC ( ) ) ; } } super . visitCode ( obj ) ; } }
implements the visitor to make sure method returns a value and then clears the targets
3,204
public void sawOpcode ( int seen ) { int lhsReg = - 1 ; try { stack . precomputation ( this ) ; switch ( state ) { case SEEN_NOTHING : if ( ! catchTargets . get ( getPC ( ) ) && lookForStore ( seen ) && ( stack . getStackDepth ( ) >= 1 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; Integer reg = ( Integer ) item . getUserValue ( ) ; if ( ( reg == null ) || ( reg . intValue ( ) != storeReg ) ) { state = State . SEEN_STORE ; } } break ; case SEEN_STORE : if ( branchTargets . get ( getPC ( ) ) ) { state = State . SEEN_NOTHING ; break ; } state = lookForLoad ( seen ) ? State . SEEN_LOAD : State . SEEN_NOTHING ; break ; case SEEN_LOAD : if ( ( seen >= Const . IRETURN ) && ( seen <= Const . ARETURN ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . USBR_UNNECESSARY_STORE_BEFORE_RETURN . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } state = State . SEEN_NOTHING ; break ; } if ( branchInstructions . get ( seen ) ) { branchTargets . set ( getBranchTarget ( ) ) ; } lhsReg = processBinOp ( seen ) ; } finally { TernaryPatcher . pre ( stack , seen ) ; stack . sawOpcode ( this , seen ) ; TernaryPatcher . post ( stack , seen ) ; if ( ( lhsReg > - 1 ) && ( stack . getStackDepth ( ) >= 1 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; item . setUserValue ( Integer . valueOf ( lhsReg ) ) ; } } }
implements the visitor to look for store of registers immediately before returns of that register
3,205
private boolean lookForStore ( int seen ) { if ( ! OpcodeUtils . isStore ( seen ) ) { return false ; } storeReg = RegisterUtils . getStoreReg ( this , seen ) ; return true ; }
checks if the current opcode is a store if so saves the register
3,206
private boolean lookForLoad ( int seen ) { int loadReg ; if ( ! OpcodeUtils . isLoad ( seen ) ) { return false ; } loadReg = RegisterUtils . getLoadReg ( this , seen ) ; return ( storeReg == loadReg ) ; }
looks for a load of the register that was just stored
3,207
public void visitCode ( Code obj ) { try { String signature = SignatureUtils . getReturnSignature ( getMethod ( ) . getSignature ( ) ) ; if ( signature . startsWith ( Values . SIG_QUALIFIED_CLASS_PREFIX ) && CollectionUtils . isListSetMap ( SignatureUtils . stripSignature ( signature ) ) ) { stack . resetForMethodEntry ( this ) ; imType = ImmutabilityType . UNKNOWN ; super . visitCode ( obj ) ; if ( ( imType == ImmutabilityType . IMMUTABLE ) || ( imType == ImmutabilityType . POSSIBLY_IMMUTABLE ) ) { Method m = getMethod ( ) ; Statistics . getStatistics ( ) . addImmutabilityStatus ( clsName , m . getName ( ) , m . getSignature ( ) , imType ) ; } } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } }
overrides the visitor to reset the stack for the new method then checks if the immutability field is set to immutable and if so reports it
3,208
public void sawOpcode ( int seen ) { ImmutabilityType seenImmutable = null ; try { stack . precomputation ( this ) ; switch ( seen ) { case Const . INVOKESTATIC : { String className = getClassConstantOperand ( ) ; String methodName = getNameConstantOperand ( ) ; if ( IMMUTABLE_PRODUCING_METHODS . contains ( className + '.' + methodName ) ) { seenImmutable = ImmutabilityType . IMMUTABLE ; break ; } } case Const . INVOKEINTERFACE : case Const . INVOKESPECIAL : case Const . INVOKEVIRTUAL : { String className = getClassConstantOperand ( ) ; String methodName = getNameConstantOperand ( ) ; String signature = getSigConstantOperand ( ) ; MethodInfo mi = Statistics . getStatistics ( ) . getMethodStatistics ( className , methodName , signature ) ; seenImmutable = mi . getImmutabilityType ( ) ; if ( seenImmutable == ImmutabilityType . UNKNOWN ) { seenImmutable = null ; } } break ; case Const . ARETURN : { processARreturn ( ) ; break ; } default : break ; } } finally { stack . sawOpcode ( this , seen ) ; if ( ( seenImmutable != null ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; item . setUserValue ( seenImmutable ) ; } } }
overrides the visitor to look for calls to static methods that are known to return immutable collections It records those variables and documents if what the method returns is one of those objects .
3,209
private boolean isJavaXExternal ( String className ) { if ( ! className . startsWith ( "javax/" ) ) { return false ; } if ( className . startsWith ( "javax/xml/" ) ) { return true ; } int lastSlashPos = className . lastIndexOf ( '/' ) ; String packageName = className . substring ( 0 , lastSlashPos ) ; ZipEntry ze = jdkZip . getEntry ( packageName ) ; if ( ze != null ) { return false ; } for ( String root : knownJDKJavaxPackageRoots ) { if ( className . startsWith ( root ) ) { return false ; } } return true ; }
checks to see if this class is a javax . xxxx . Foo class if so looks to see if the package is at least in the jdk if a whole new package comes into javax in rt . jar this will be missed . Need a better solution here .
3,210
public void visitClassContext ( ClassContext classContext ) { if ( ( collectionClass == null ) || ( iteratorClass == null ) ) { return ; } try { collectionGroups = new ArrayList < > ( ) ; groupToIterator = new HashMap < > ( ) ; loops = new HashMap < > ( 10 ) ; super . visitClassContext ( classContext ) ; } finally { collectionGroups = null ; groupToIterator = null ; loops = null ; endOfScopes = null ; } }
implements the visitor to setup the opcode stack collectionGroups groupToIterator and loops
3,211
public void visitCode ( Code obj ) { collectionGroups . clear ( ) ; groupToIterator . clear ( ) ; loops . clear ( ) ; buildVariableEndScopeMap ( ) ; super . visitCode ( obj ) ; }
implements the visitor to reset the stack collectionGroups groupToIterator and loops
3,212
private boolean breakFollows ( Loop loop , boolean needsPop ) { byte [ ] code = getCode ( ) . getCode ( ) ; int nextPC = getNextPC ( ) ; if ( needsPop ) { int popOp = CodeByteUtils . getbyte ( code , nextPC ++ ) ; if ( popOp != Const . POP ) { return false ; } } int gotoOp = CodeByteUtils . getbyte ( code , nextPC ) ; if ( ( gotoOp == Const . GOTO ) || ( gotoOp == Const . GOTO_W ) ) { int target = nextPC + CodeByteUtils . getshort ( code , nextPC + 1 ) ; if ( target > loop . getLoopFinish ( ) ) { return true ; } } return false ; }
looks to see if the following instruction is a GOTO preceded by potentially a pop
3,213
private static Comparable < ? > getGroupElement ( OpcodeStack . Item itm ) { Comparable < ? > groupElement = null ; int reg = itm . getRegisterNumber ( ) ; if ( reg >= 0 ) { groupElement = Integer . valueOf ( reg ) ; } else { XField field = itm . getXField ( ) ; if ( field != null ) { int regLoad = itm . getFieldLoadedFromRegister ( ) ; if ( regLoad >= 0 ) { groupElement = field . getName ( ) + ":{" + regLoad + '}' ; } } } return groupElement ; }
given an register or field look to see if this thing is associated with an already discovered loop
3,214
public void visitCode ( Code obj ) { Method m = getMethod ( ) ; if ( m . isSynthetic ( ) ) { return ; } if ( isEnum && "values" . equals ( m . getName ( ) ) ) { return ; } String sig = m . getSignature ( ) ; int sigPos = sig . indexOf ( ")[" ) ; if ( sigPos < 0 ) { return ; } if ( INITIAL_VALUE . equals ( m . getName ( ) ) ) { try { if ( ( THREAD_LOCAL_CLASS == null ) || getClassContext ( ) . getJavaClass ( ) . instanceOf ( THREAD_LOCAL_CLASS ) ) { return ; } } catch ( ClassNotFoundException e ) { bugReporter . reportMissingClass ( e ) ; return ; } } stack . resetForMethodEntry ( this ) ; returnArraySig = sig . substring ( sigPos + 1 ) ; uninitializedRegs . clear ( ) ; arrayAliases . clear ( ) ; storedUVs . clear ( ) ; super . visitCode ( obj ) ; }
overrides the visitor to check to see if the method returns an array and if so resets the stack for this method .
3,215
public void sawOpcode ( int seen ) { String methodInfo = null ; try { stack . precomputation ( this ) ; switch ( seen ) { case Const . INVOKEVIRTUAL : case Const . INVOKEINTERFACE : case Const . INVOKESTATIC : String sig = getSigConstantOperand ( ) ; if ( ! sig . endsWith ( Values . SIG_VOID ) ) { methodInfo = getClassConstantOperand ( ) + '@' + getNameConstantOperand ( ) + getSigConstantOperand ( ) ; } break ; case Const . POP : case Const . POP2 : if ( stack . getStackDepth ( ) > 0 ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; String mInfo = ( String ) item . getUserValue ( ) ; if ( mInfo != null ) { for ( Pattern p : IMMUTABLE_METHODS ) { Matcher m = p . matcher ( mInfo ) ; if ( m . matches ( ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . NPMC_NON_PRODUCTIVE_METHOD_CALL . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) . addString ( mInfo ) ) ; break ; } } } } break ; } } finally { stack . sawOpcode ( this , seen ) ; if ( ( methodInfo != null ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; item . setUserValue ( methodInfo ) ; } } }
implements the visitor to look for return values of common immutable method calls that are thrown away .
3,216
public void visitClassContext ( ClassContext classContext ) { try { classVersion = classContext . getJavaClass ( ) . getMajor ( ) ; if ( classVersion >= Const . MAJOR_1_4 ) { stack = new OpcodeStack ( ) ; super . visitClassContext ( classContext ) ; } } finally { stack = null ; } }
implements the visitor to make sure the class is at least 1 . 4 and if so continues reseting the opcode stack
3,217
public void sawOpcode ( int seen ) { try { stack . precomputation ( this ) ; switch ( seen ) { case Const . INVOKESPECIAL : case Const . INVOKESTATIC : case Const . INVOKEINTERFACE : case Const . INVOKEVIRTUAL : String encoding = null ; String className = getClassConstantOperand ( ) ; String methodName = getNameConstantOperand ( ) ; String methodSig = getSigConstantOperand ( ) ; FQMethod methodInfo = new FQMethod ( className , methodName , methodSig ) ; Integer stackOffset = REPLACEABLE_ENCODING_METHODS . get ( methodInfo ) ; if ( stackOffset != null ) { int offset = stackOffset . intValue ( ) ; if ( stack . getStackDepth ( ) > offset ) { OpcodeStack . Item item = stack . getStackItem ( offset ) ; encoding = ( String ) item . getConstant ( ) ; if ( encoding != null ) { encoding = encoding . toUpperCase ( Locale . ENGLISH ) ; if ( ( classVersion >= Const . MAJOR_1_7 ) && STANDARD_JDK7_ENCODINGS . contains ( encoding ) ) { String changedMethodSig = replaceNthArgWithCharsetString ( methodSig , offset ) ; bugReporter . reportBug ( new BugInstance ( this , BugType . CSI_CHAR_SET_ISSUES_USE_STANDARD_CHARSET . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) . addCalledMethod ( this ) . addCalledMethod ( className , methodName , changedMethodSig , seen == Const . INVOKESTATIC ) ) ; } } } } else { Integer offsetValue = UNREPLACEABLE_ENCODING_METHODS . get ( methodInfo ) ; if ( offsetValue != null ) { int offset = offsetValue . intValue ( ) ; if ( stack . getStackDepth ( ) > offset ) { OpcodeStack . Item item = stack . getStackItem ( offset ) ; encoding = ( String ) item . getConstant ( ) ; if ( encoding != null ) { encoding = encoding . toUpperCase ( Locale . ENGLISH ) ; if ( ( classVersion >= Const . MAJOR_1_7 ) && STANDARD_JDK7_ENCODINGS . contains ( encoding ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . CSI_CHAR_SET_ISSUES_USE_STANDARD_CHARSET_NAME . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) . addCalledMethod ( this ) ) ; } } } } } if ( encoding != null ) { try { Charset . forName ( encoding ) ; } catch ( IllegalArgumentException e ) { bugReporter . reportBug ( new BugInstance ( this , BugType . CSI_CHAR_SET_ISSUES_UNKNOWN_ENCODING . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) . addCalledMethod ( this ) . addString ( encoding ) ) ; } } break ; default : break ; } } finally { stack . sawOpcode ( this , seen ) ; } }
implements the visitor to look for method calls that take a parameter that either represents a encoding via a string or takes a Charset . If the method can take both and a string is presented for a standard charset available in jdk 7 and the code is compiled against 7 then report . It also looks for mistakes encodings that aren t recognized in the current jvm .
3,218
private static String replaceNthArgWithCharsetString ( String sig , int stackOffset ) { List < String > arguments = SignatureUtils . getParameterSignatures ( sig ) ; StringBuilder sb = new StringBuilder ( "(" ) ; int argumentIndexToReplace = ( arguments . size ( ) - stackOffset ) - 1 ; for ( int i = 0 ; i < arguments . size ( ) ; i ++ ) { if ( i == argumentIndexToReplace ) { sb . append ( CHARSET_SIG ) ; } else { sb . append ( arguments . get ( i ) ) ; } } sb . append ( sig . substring ( sig . lastIndexOf ( ')' ) , sig . length ( ) ) ) ; return sb . toString ( ) ; }
rebuilds a signature replacing a String argument at a specified spot with a Charset parameter .
3,219
@ PublicAPI ( "Used by fb-contrib-eclipse-quickfixes to determine type of fix to apply" ) public static Map < String , Integer > getUnreplaceableCharsetEncodings ( ) { Map < String , Integer > encodings = new HashMap < > ( ( int ) ( UNREPLACEABLE_ENCODING_METHODS . size ( ) * 1.6 ) ) ; for ( Map . Entry < FQMethod , Integer > entry : UNREPLACEABLE_ENCODING_METHODS . entrySet ( ) ) { encodings . put ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } return encodings ; }
used by external tools lists the method signature checked for for unreplaceable encoding methods
3,220
@ PublicAPI ( "Used by fb-contrib-eclipse-quickfixes to determine type of fix to apply" ) public static Map < String , Integer > getReplaceableCharsetEncodings ( ) { Map < String , Integer > encodings = new HashMap < > ( ( int ) ( REPLACEABLE_ENCODING_METHODS . size ( ) * 1.6 ) ) ; for ( Map . Entry < FQMethod , Integer > entry : REPLACEABLE_ENCODING_METHODS . entrySet ( ) ) { encodings . put ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } return encodings ; }
used by external tools lists the method signature checked for for replaceable encoding methods
3,221
public void visitCode ( Code obj ) { Method m = getMethod ( ) ; if ( ( ! m . isStatic ( ) || ! Values . STATIC_INITIALIZER . equals ( m . getName ( ) ) ) && ( ! m . getName ( ) . contains ( "enum constant" ) ) ) { byte [ ] code = obj . getCode ( ) ; if ( code . length >= UNJITABLE_CODE_LENGTH ) { bugReporter . reportBug ( new BugInstance ( this , BugType . UJM_UNJITABLE_METHOD . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addString ( "Code Bytes: " + code . length ) ) ; } } }
implements the visitor to look at the size of the method . static initializer are ignored as these will only be executed once anyway .
3,222
public boolean prescreen ( Method method ) { BitSet bytecodeSet = getClassContext ( ) . getBytecodeSet ( method ) ; return ( bytecodeSet != null ) && ( bytecodeSet . get ( Const . NEWARRAY ) || bytecodeSet . get ( Const . ANEWARRAY ) ) ; }
looks for methods that contain a NEWARRAY or ANEWARRAY opcodes
3,223
private void processLocalStore ( int seen ) { if ( stack . getStackDepth ( ) == 0 ) { return ; } OpcodeStack . Item itm = stack . getStackItem ( 0 ) ; String sig = itm . getSignature ( ) ; if ( sig . startsWith ( Values . SIG_ARRAY_PREFIX ) ) { int reg = RegisterUtils . getAStoreReg ( this , seen ) ; Integer elReg = ( Integer ) itm . getUserValue ( ) ; if ( elReg != null ) { wrappers . put ( Integer . valueOf ( reg ) , new WrapperInfo ( elReg . intValue ( ) ) ) ; } } else { Integer elReg = ( Integer ) itm . getUserValue ( ) ; if ( ( elReg != null ) && ( elReg . intValue ( ) == RegisterUtils . getAStoreReg ( this , seen ) ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . AWCBR_ARRAY_WRAPPED_CALL_BY_REFERENCE . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } } }
looks for stores to registers if that store is an array builds a wrapper info for it and stores it in the wrappers collection . If it is a regular store sees if this value came from a wrapper array passed into a method and if so reports it .
3,224
private Integer processArrayElementStore ( ) { if ( stack . getStackDepth ( ) >= 2 ) { OpcodeStack . Item itm = stack . getStackItem ( 2 ) ; int reg = itm . getRegisterNumber ( ) ; if ( reg != - 1 ) { WrapperInfo wi = wrappers . get ( Integer . valueOf ( reg ) ) ; if ( wi != null ) { OpcodeStack . Item elItm = stack . getStackItem ( 0 ) ; wi . wrappedReg = elItm . getRegisterNumber ( ) ; } } else { OpcodeStack . Item elItm = stack . getStackItem ( 0 ) ; reg = elItm . getRegisterNumber ( ) ; if ( reg != - 1 ) { return Integer . valueOf ( reg ) ; } } } return null ; }
processes a store to an array element to see if this array is being used as a wrapper array and if so records the register that is stored within it .
3,225
private void processMethodCall ( ) { if ( "invoke" . equals ( getNameConstantOperand ( ) ) && "java/lang/reflect/Method" . equals ( getClassConstantOperand ( ) ) ) { return ; } String sig = getSigConstantOperand ( ) ; List < String > args = SignatureUtils . getParameterSignatures ( sig ) ; if ( stack . getStackDepth ( ) >= args . size ( ) ) { for ( int i = 0 ; i < args . size ( ) ; i ++ ) { String argSig = args . get ( i ) ; if ( argSig . startsWith ( Values . SIG_ARRAY_PREFIX ) ) { OpcodeStack . Item itm = stack . getStackItem ( args . size ( ) - i - 1 ) ; int arrayReg = itm . getRegisterNumber ( ) ; WrapperInfo wi = wrappers . get ( Integer . valueOf ( arrayReg ) ) ; if ( wi != null ) { wi . wasArg = true ; } } } } }
processes a method call looking for parameters that are arrays . If this array was seen earlier as a simple wrapping array then it marks it as being having been used as a parameter .
3,226
private boolean isCallingOnThis ( String sig ) { if ( getMethod ( ) . isStatic ( ) ) { return false ; } int numParameters = SignatureUtils . getNumParameters ( sig ) ; if ( stack . getStackDepth ( ) <= numParameters ) { return false ; } OpcodeStack . Item item = stack . getStackItem ( numParameters ) ; return item . getRegisterNumber ( ) == 0 ; }
checks to see if an instance method is called on the this object
3,227
public void report ( ) { for ( Map . Entry < FQMethod , MethodInfo > entry : Statistics . getStatistics ( ) ) { MethodInfo mi = entry . getValue ( ) ; int declaredAccess = mi . getDeclaredAccess ( ) ; if ( ( declaredAccess & Const . ACC_PRIVATE ) != 0 ) { continue ; } if ( mi . wasCalledPublicly ( ) || ! mi . wasCalled ( ) ) { continue ; } FQMethod key = entry . getKey ( ) ; String methodName = key . getMethodName ( ) ; if ( isGetterSetter ( methodName , key . getSignature ( ) ) ) { continue ; } if ( isOverlyPermissive ( declaredAccess ) && ! isConstrainedByInterface ( key ) ) { try { String clsName = key . getClassName ( ) ; if ( ! isDerived ( Repository . lookupClass ( clsName ) , key ) ) { BugInstance bi = new BugInstance ( this , BugType . OPM_OVERLY_PERMISSIVE_METHOD . name ( ) , LOW_PRIORITY ) . addClass ( clsName ) . addMethod ( clsName , key . getMethodName ( ) , key . getSignature ( ) , ( declaredAccess & Const . ACC_STATIC ) != 0 ) ; String descr = String . format ( "- Method declared %s but could be declared %s" , getDeclaredAccessValue ( declaredAccess ) , getRequiredAccessValue ( mi ) ) ; bi . addString ( descr ) ; bugReporter . reportBug ( bi ) ; } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } } } }
after collecting all method calls build a report of all methods that have been called but in a way that is less permissive then is defined .
3,228
private boolean isConstrainedByInterface ( FQMethod fqMethod ) { try { JavaClass fqCls = Repository . lookupClass ( fqMethod . getClassName ( ) ) ; if ( fqCls . isInterface ( ) ) { return true ; } for ( JavaClass inf : fqCls . getAllInterfaces ( ) ) { for ( Method infMethod : inf . getMethods ( ) ) { if ( infMethod . getName ( ) . equals ( fqMethod . getMethodName ( ) ) ) { String infMethodSig = infMethod . getSignature ( ) ; String fqMethodSig = fqMethod . getSignature ( ) ; if ( infMethodSig . equals ( fqMethodSig ) ) { return true ; } List < String > infTypes = SignatureUtils . getParameterSignatures ( infMethodSig ) ; List < String > fqTypes = SignatureUtils . getParameterSignatures ( fqMethodSig ) ; if ( infTypes . size ( ) == fqTypes . size ( ) ) { boolean matches = true ; for ( int i = 0 ; i < infTypes . size ( ) ; i ++ ) { String infParmType = infTypes . get ( i ) ; String fqParmType = fqTypes . get ( i ) ; if ( infParmType . equals ( fqParmType ) ) { if ( ( infParmType . charAt ( 0 ) != 'L' ) || ( fqParmType . charAt ( 0 ) != 'L' ) ) { matches = false ; break ; } JavaClass infParmClass = Repository . lookupClass ( SignatureUtils . stripSignature ( infParmType ) ) ; JavaClass fqParmClass = Repository . lookupClass ( SignatureUtils . stripSignature ( fqParmType ) ) ; if ( ! fqParmClass . instanceOf ( infParmClass ) ) { matches = false ; break ; } } } if ( matches ) { return true ; } } } } } return false ; } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; return true ; } }
looks to see if this method is an implementation of a method in an interface including generic specified interface methods .
3,229
private boolean isDerived ( JavaClass fqCls , FQMethod key ) { try { for ( JavaClass infCls : fqCls . getInterfaces ( ) ) { for ( Method infMethod : infCls . getMethods ( ) ) { if ( key . getMethodName ( ) . equals ( infMethod . getName ( ) ) ) { if ( infMethod . getGenericSignature ( ) != null ) { if ( SignatureUtils . compareGenericSignature ( infMethod . getGenericSignature ( ) , key . getSignature ( ) ) ) { return true ; } } else if ( infMethod . getSignature ( ) . equals ( key . getSignature ( ) ) ) { return true ; } } } } JavaClass superClass = fqCls . getSuperClass ( ) ; if ( ( superClass == null ) || Values . DOTTED_JAVA_LANG_OBJECT . equals ( superClass . getClassName ( ) ) ) { return false ; } for ( Method superMethod : superClass . getMethods ( ) ) { if ( key . getMethodName ( ) . equals ( superMethod . getName ( ) ) ) { if ( superMethod . getGenericSignature ( ) != null ) { if ( SignatureUtils . compareGenericSignature ( superMethod . getGenericSignature ( ) , key . getSignature ( ) ) ) { return true ; } } else if ( superMethod . getSignature ( ) . equals ( key . getSignature ( ) ) ) { return true ; } } } return isDerived ( superClass , key ) ; } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; return true ; } }
looks to see if this method described by key is derived from a superclass or interface
3,230
public void visitCode ( Code obj ) { stack . resetForMethodEntry ( this ) ; localSpecialObjects . clear ( ) ; sawTernary = false ; super . visitCode ( obj ) ; for ( Integer pc : localSpecialObjects . values ( ) ) { bugReporter . reportBug ( makeLocalBugInstance ( ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this , pc . intValue ( ) ) ) ; } }
overrides the visitor reset the stack
3,231
protected void processMethodParms ( ) { String sig = getSigConstantOperand ( ) ; int numParms = SignatureUtils . getNumParameters ( sig ) ; if ( ( numParms > 0 ) && ( stack . getStackDepth ( ) >= numParms ) ) { for ( int i = 0 ; i < numParms ; i ++ ) { clearUserValue ( stack . getStackItem ( i ) ) ; } } }
Checks to see if any of the locals or fields that we are tracking are passed into another method . If they are we clear out our tracking of them because we can t easily track their progress into the method .
3,232
public void visitClassContext ( ClassContext classContext ) { try { guiInterfaces = new HashSet < > ( ) ; JavaClass cls = classContext . getJavaClass ( ) ; JavaClass [ ] infs = cls . getAllInterfaces ( ) ; for ( JavaClass inf : infs ) { String name = inf . getClassName ( ) ; if ( ( name . startsWith ( "java.awt." ) || name . startsWith ( "javax.swing." ) ) && name . endsWith ( "Listener" ) ) { guiInterfaces . add ( inf ) ; } } if ( ! guiInterfaces . isEmpty ( ) ) { listenerCode = new LinkedHashMap < > ( ) ; expensiveThisCalls = new HashSet < > ( ) ; super . visitClassContext ( classContext ) ; } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } finally { guiInterfaces = null ; listenerCode = null ; expensiveThisCalls = null ; } }
overrides the visitor to reset look for gui interfaces
3,233
public void visitAfter ( JavaClass obj ) { isListenerMethod = true ; for ( Code l : listenerCode . keySet ( ) ) { try { super . visitCode ( l ) ; } catch ( StopOpcodeParsingException e ) { } } super . visitAfter ( obj ) ; }
overrides the visitor to visit all of the collected listener methods
3,234
public void visitMethod ( Method obj ) { methodName = obj . getName ( ) ; methodSig = obj . getSignature ( ) ; }
overrides the visitor collect method info
3,235
public void visitCode ( Code obj ) { try { for ( JavaClass inf : guiInterfaces ) { Method [ ] methods = inf . getMethods ( ) ; for ( Method m : methods ) { if ( m . getName ( ) . equals ( methodName ) && m . getSignature ( ) . equals ( methodSig ) ) { listenerCode . put ( obj , this . getMethod ( ) ) ; return ; } } } isListenerMethod = false ; super . visitCode ( obj ) ; } catch ( StopOpcodeParsingException e ) { } }
overrides the visitor to segregate method into two those that implement listeners and those that don t . The ones that don t are processed first .
3,236
public void sawOpcode ( int seen ) { if ( ( seen == Const . INVOKEINTERFACE ) || ( seen == Const . INVOKEVIRTUAL ) || ( seen == Const . INVOKESPECIAL ) || ( seen == Const . INVOKESTATIC ) ) { String clsName = getClassConstantOperand ( ) ; String mName = getNameConstantOperand ( ) ; String methodInfo = clsName + ':' + mName ; String thisMethodInfo = ( clsName . equals ( getClassName ( ) ) ) ? ( mName + ':' + methodSig ) : "0" ; if ( expensiveCalls . contains ( methodInfo ) || expensiveThisCalls . contains ( thisMethodInfo ) ) { if ( isListenerMethod ) { bugReporter . reportBug ( new BugInstance ( this , BugType . SG_SLUGGISH_GUI . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this . getClassContext ( ) . getJavaClass ( ) , listenerCode . get ( this . getCode ( ) ) ) ) ; } else { expensiveThisCalls . add ( getMethodName ( ) + ':' + getMethodSig ( ) ) ; } throw new StopOpcodeParsingException ( ) ; } } }
overrides the visitor to look for the execution of expensive calls
3,237
public static void println ( int pc , Object obj ) { out . printf ( "[PC:%d] %s%n" , Integer . valueOf ( pc ) , obj ) ; }
Like println but will print PC if it s passed in
3,238
public static boolean isValidLineNumber ( Code obj , int pc ) { LineNumberTable lnt = obj . getLineNumberTable ( ) ; if ( lnt == null ) return true ; LineNumber [ ] lineNumbers = lnt . getLineNumberTable ( ) ; if ( lineNumbers == null ) return true ; int lo = 0 ; int hi = lineNumbers . length - 1 ; int mid = 0 ; int linePC = 0 ; while ( lo <= hi ) { mid = ( lo + hi ) >>> 1 ; linePC = lineNumbers [ mid ] . getStartPC ( ) ; if ( linePC == pc ) break ; if ( linePC < pc ) lo = mid + 1 ; else hi = mid - 1 ; } int lineNo = lineNumbers [ mid ] . getLineNumber ( ) ; for ( int i = 0 ; i < lineNumbers . length ; i ++ ) { if ( ( mid != i ) && ( lineNumbers [ i ] . getLineNumber ( ) == lineNo ) ) return false ; } return true ; }
returns whether the pc is at a line number that also appears for a another byte code offset later on in the method . If this occurs we are in a jdk6 finally replicated block and so don t report this . If the code has no line number table then just report it .
3,239
public void visitClassContext ( ClassContext classContext ) { try { if ( ( collectionClass != null ) && ( mapClass != null ) ) { collectionFields = new HashMap < > ( ) ; aliases = new HashMap < > ( ) ; stack = new OpcodeStack ( ) ; JavaClass cls = classContext . getJavaClass ( ) ; className = cls . getClassName ( ) ; super . visitClassContext ( classContext ) ; for ( FieldInfo fi : collectionFields . values ( ) ) { if ( fi . isSynchronized ( ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . NMCS_NEEDLESS_MEMBER_COLLECTION_SYNCHRONIZATION . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addField ( fi . getFieldAnnotation ( ) ) ) ; } } } } finally { collectionFields = null ; aliases = null ; stack = null ; } }
implements the visitor to clear the collectionFields and stack and to report collections that remain unmodified out of clinit or init
3,240
public void visitField ( Field obj ) { if ( obj . isPrivate ( ) ) { String signature = obj . getSignature ( ) ; if ( signature . startsWith ( Values . SIG_QUALIFIED_CLASS_PREFIX ) ) { try { JavaClass cls = Repository . lookupClass ( SignatureUtils . stripSignature ( signature ) ) ; if ( cls . implementationOf ( collectionClass ) || cls . implementationOf ( mapClass ) ) { FieldAnnotation fa = FieldAnnotation . fromVisitedField ( this ) ; collectionFields . put ( fa . getFieldName ( ) , new FieldInfo ( fa ) ) ; } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } } } }
implements the visitor to find collection fields
3,241
public void visitCode ( Code obj ) { if ( collectionFields . isEmpty ( ) ) { return ; } aliases . clear ( ) ; String methodName = getMethodName ( ) ; if ( Values . STATIC_INITIALIZER . equals ( methodName ) ) { state = State . IN_CLINIT ; } else if ( Values . CONSTRUCTOR . equals ( methodName ) ) { state = State . IN_INIT ; } else { state = State . IN_METHOD ; } stack . resetForMethodEntry ( this ) ; super . visitCode ( obj ) ; }
implements the visitor to set the state based on the type of method being parsed
3,242
public void sawOpcode ( int seen ) { switch ( state ) { case IN_CLINIT : sawCLInitOpcode ( seen ) ; break ; case IN_INIT : sawInitOpcode ( seen ) ; break ; case IN_METHOD : sawMethodOpcode ( seen ) ; break ; } }
implements the visitor to call the approriate visitor based on state
3,243
private void sawMethodOpcode ( int seen ) { boolean isSyncCollection = false ; try { stack . mergeJumps ( this ) ; isSyncCollection = isSyncCollectionCreation ( seen ) ; switch ( seen ) { case Const . INVOKEVIRTUAL : case Const . INVOKEINTERFACE : String methodName = getNameConstantOperand ( ) ; if ( modifyingMethods . contains ( methodName ) ) { String signature = getSigConstantOperand ( ) ; int parmCount = SignatureUtils . getNumParameters ( signature ) ; if ( stack . getStackDepth ( ) > parmCount ) { OpcodeStack . Item item = stack . getStackItem ( parmCount ) ; XField field = item . getXField ( ) ; if ( field != null ) { collectionFields . remove ( field . getName ( ) ) ; } else { int reg = item . getRegisterNumber ( ) ; if ( reg >= 0 ) { Integer register = Integer . valueOf ( reg ) ; String fName = aliases . get ( register ) ; if ( fName != null ) { collectionFields . remove ( fName ) ; aliases . remove ( register ) ; } } } } } removeCollectionParameters ( ) ; break ; case Const . INVOKESTATIC : removeCollectionParameters ( ) ; break ; case Const . ARETURN : if ( stack . getStackDepth ( ) > 0 ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; XField field = item . getXField ( ) ; if ( field != null ) { collectionFields . remove ( field . getName ( ) ) ; } } break ; case Const . PUTFIELD : case Const . PUTSTATIC : String fieldName = getNameConstantOperand ( ) ; collectionFields . remove ( fieldName ) ; break ; case Const . GOTO : case Const . GOTO_W : if ( stack . getStackDepth ( ) > 0 ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; XField field = item . getXField ( ) ; if ( field != null ) { collectionFields . remove ( field . getName ( ) ) ; } } break ; default : break ; } } finally { TernaryPatcher . pre ( stack , seen ) ; stack . sawOpcode ( this , seen ) ; TernaryPatcher . post ( stack , seen ) ; if ( isSyncCollection && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; item . setUserValue ( Boolean . TRUE ) ; } } }
handles regular methods by looking for methods on collections that are modifying and removes those collections from the ones under review
3,244
private boolean isSyncCollectionCreation ( int seen ) { if ( seen == Const . INVOKESPECIAL ) { if ( Values . CONSTRUCTOR . equals ( getNameConstantOperand ( ) ) ) { return ( syncCollections . contains ( getClassConstantOperand ( ) ) ) ; } } else if ( ( seen == Const . INVOKESTATIC ) && "java/util/Collections" . equals ( getClassConstantOperand ( ) ) ) { String methodName = getNameConstantOperand ( ) ; return ( "synchronizedMap" . equals ( methodName ) || "synchronizedSet" . equals ( methodName ) ) ; } return false ; }
returns whether this instruction is creating a synchronized collection
3,245
private void processCollectionStore ( ) { String fieldClassName = getDottedClassConstantOperand ( ) ; if ( fieldClassName . equals ( className ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; if ( item . getUserValue ( ) != null ) { String fieldName = getNameConstantOperand ( ) ; if ( fieldName != null ) { FieldInfo fi = collectionFields . get ( fieldName ) ; if ( fi != null ) { fi . getFieldAnnotation ( ) . setSourceLines ( SourceLineAnnotation . fromVisitedInstruction ( this ) ) ; fi . setSynchronized ( ) ; } } } } }
sets the source line annotation of a store to a collection if that collection is synchronized .
3,246
private void removeCollectionParameters ( ) { int parmCount = SignatureUtils . getNumParameters ( getSigConstantOperand ( ) ) ; if ( stack . getStackDepth ( ) >= parmCount ) { for ( int i = 0 ; i < parmCount ; i ++ ) { OpcodeStack . Item item = stack . getStackItem ( i ) ; XField field = item . getXField ( ) ; if ( field != null ) { collectionFields . remove ( field . getName ( ) ) ; } } } }
removes collection fields that are passed to other methods as arguments
3,247
public void visitClassContext ( ClassContext classContext ) { try { bloatableCandidates = new HashMap < > ( ) ; bloatableFields = new HashMap < > ( ) ; threadLocalNonStaticFields = new HashSet < > ( ) ; userValues = new HashMap < > ( ) ; jaxbContextRegs = new HashMap < > ( ) ; parseFields ( classContext ) ; stack = new OpcodeStack ( ) ; super . visitClassContext ( classContext ) ; reportMemoryBloatBugs ( ) ; reportThreadLocalBugs ( ) ; } finally { stack = null ; bloatableCandidates = null ; bloatableFields = null ; userValues = null ; threadLocalNonStaticFields = null ; jaxbContextRegs = null ; } }
collects static fields that are likely bloatable objects and if found allows the visitor to proceed at the end report all leftover fields
3,248
public void visitClassContext ( ClassContext clsContext ) { try { stack = new OpcodeStack ( ) ; super . visitClassContext ( clsContext ) ; } finally { stack = null ; } }
overrides the visitor to setup the opcode stack
3,249
public void visitCode ( Code obj ) { stack . resetForMethodEntry ( this ) ; conditionalTarget = - 1 ; sawMethodWeight = 0 ; super . visitCode ( obj ) ; }
overrides the visitor to reset the opcode stack and initialize vars
3,250
public void visitClassContext ( ClassContext classContext ) { try { JavaClass cls = classContext . getJavaClass ( ) ; if ( isSerializable ( cls ) ) { JavaClass superCls = cls . getSuperClass ( ) ; if ( ! isSerializable ( superCls ) && hasSerializableFields ( superCls ) && ! hasSerializingMethods ( cls ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . PIS_POSSIBLE_INCOMPLETE_SERIALIZATION . name ( ) , NORMAL_PRIORITY ) . addClass ( cls ) ) ; } } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } }
implements the visitor to look for classes that are serializable and are derived from non serializable classes and don t either implement methods in Externalizable or Serializable to save parent class fields .
3,251
private static boolean isSerializable ( JavaClass cls ) throws ClassNotFoundException { JavaClass [ ] infs = cls . getAllInterfaces ( ) ; for ( JavaClass inf : infs ) { String clsName = inf . getClassName ( ) ; if ( "java.io.Serializable" . equals ( clsName ) || "java.io.Externalizable" . equals ( clsName ) ) { return true ; } } return false ; }
returns if the class implements Serializable or Externalizable
3,252
private static boolean hasSerializableFields ( JavaClass cls ) { Field [ ] fields = cls . getFields ( ) ; for ( Field f : fields ) { if ( ! f . isStatic ( ) && ! f . isTransient ( ) && ! f . isSynthetic ( ) ) { return true ; } } return false ; }
looks for fields that are candidates for serialization
3,253
private static boolean hasSerializingMethods ( JavaClass cls ) { Method [ ] methods = cls . getMethods ( ) ; for ( Method m : methods ) { if ( ! m . isStatic ( ) ) { String methodName = m . getName ( ) ; String methodSig = m . getSignature ( ) ; if ( "writeObject" . equals ( methodName ) && SIG_OBJECT_OUTPUT_STREAM_TO_VOID . equals ( methodSig ) ) { return true ; } if ( "writeExternal" . equals ( methodName ) && SIG_OBJECT_OUTPUT_TO_VOID . equals ( methodSig ) ) { return true ; } } } return false ; }
looks to see if this class implements method described by Serializable or Externalizable
3,254
public void sawOpcode ( int seen ) { try { stack . precomputation ( this ) ; if ( seen == Const . INVOKESTATIC ) { String clsName = getClassConstantOperand ( ) ; if ( "java/util/Arrays" . equals ( clsName ) ) { String methodName = getNameConstantOperand ( ) ; if ( "asList" . equals ( methodName ) && ( stack . getStackDepth ( ) >= 1 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; String sig = item . getSignature ( ) ; if ( PRIMITIVE_ARRAYS . contains ( sig ) ) { Object con = item . getConstant ( ) ; if ( ! ( con instanceof Integer ) || ( ( ( Integer ) con ) . intValue ( ) <= 1 ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . CAAL_CONFUSING_ARRAY_AS_LIST . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } } } } } } finally { stack . sawOpcode ( this , seen ) ; } }
implements the visitor to find calls to Arrays . asList with a primitive array
3,255
public void visitCode ( Code obj ) { state = State . SEEN_NOTHING ; beanReference1 = null ; beanReference2 = null ; propName = null ; propType = null ; sawField = false ; super . visitCode ( obj ) ; }
overrides the visitor to reset the state to SEEN_NOTHING and clear the beanReference propName and propType
3,256
public void sawOpcode ( int seen ) { boolean reset = true ; switch ( state ) { case SEEN_NOTHING : reset = sawOpcodeAfterNothing ( seen ) ; break ; case SEEN_ALOAD : reset = sawOpcodeAfterLoad ( seen ) ; break ; case SEEN_GETFIELD : reset = sawOpcodeAfterGetField ( seen ) ; break ; case SEEN_DUAL_LOADS : reset = sawOpcodeAfterDualLoads ( seen ) ; break ; case SEEN_INVOKEVIRTUAL : if ( seen == Const . INVOKEVIRTUAL ) { checkForSGSU ( ) ; } break ; } if ( reset ) { beanReference1 = null ; beanReference2 = null ; propType = null ; propName = null ; sawField = false ; state = State . SEEN_NOTHING ; } }
overrides the visitor to look for a setXXX with the value returned from a getXXX using the same base object .
3,257
public void visitClassContext ( ClassContext classContext ) { try { if ( ( invocationHandlerClass != null ) && classContext . getJavaClass ( ) . implementationOf ( invocationHandlerClass ) ) { return ; } iConst0Looped = new BitSet ( ) ; stack = new OpcodeStack ( ) ; super . visitClassContext ( classContext ) ; } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } finally { iConst0Looped = null ; stack = null ; } }
implements the visitor to create and clear the const0loop set
3,258
private static boolean isArrayFromUbiquitousMethod ( OpcodeStack . Item item ) { XMethod method = item . getReturnValueOf ( ) ; if ( method == null ) { return false ; } FQMethod methodDesc = new FQMethod ( method . getClassName ( ) . replace ( '.' , '/' ) , method . getName ( ) , method . getSignature ( ) ) ; return ubiquitousMethods . contains ( methodDesc ) ; }
returns whether the array item was returned from a common method that the user can t do anything about and so don t report CLI in this case .
3,259
public void visitClassContext ( ClassContext classContext ) { try { unusedParms = new BitSet ( ) ; regToParm = new HashMap < > ( ) ; stack = new OpcodeStack ( ) ; super . visitClassContext ( classContext ) ; } finally { stack = null ; regToParm = null ; unusedParms . clear ( ) ; } }
implements the visitor to create parm bitset
3,260
public void visitCode ( Code obj ) { unusedParms . clear ( ) ; regToParm . clear ( ) ; stack . resetForMethodEntry ( this ) ; Method m = getMethod ( ) ; String methodName = m . getName ( ) ; if ( IGNORE_METHODS . contains ( methodName ) ) { return ; } int accessFlags = m . getAccessFlags ( ) ; if ( ( ( accessFlags & ( Const . ACC_STATIC | Const . ACC_PRIVATE ) ) == 0 ) || ( ( accessFlags & Const . ACC_SYNTHETIC ) != 0 ) ) { return ; } List < String > parmTypes = SignatureUtils . getParameterSignatures ( m . getSignature ( ) ) ; if ( parmTypes . isEmpty ( ) ) { return ; } int firstReg = 0 ; if ( ( accessFlags & Const . ACC_STATIC ) == 0 ) { ++ firstReg ; } int reg = firstReg ; for ( int i = 0 ; i < parmTypes . size ( ) ; ++ i ) { unusedParms . set ( reg ) ; regToParm . put ( Integer . valueOf ( reg ) , Integer . valueOf ( i + 1 ) ) ; String parmSig = parmTypes . get ( i ) ; reg += SignatureUtils . getSignatureSize ( parmSig ) ; } try { super . visitCode ( obj ) ; if ( ! unusedParms . isEmpty ( ) ) { LocalVariableTable lvt = m . getLocalVariableTable ( ) ; reg = unusedParms . nextSetBit ( firstReg ) ; while ( reg >= 0 ) { LocalVariable lv = ( lvt == null ) ? null : lvt . getLocalVariable ( reg , 0 ) ; if ( lv != null ) { String parmName = lv . getName ( ) ; bugReporter . reportBug ( new BugInstance ( this , BugType . UP_UNUSED_PARAMETER . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addString ( "Parameter " + regToParm . get ( Integer . valueOf ( reg ) ) + ": " + parmName ) ) ; } reg = unusedParms . nextSetBit ( reg + 1 ) ; } } } catch ( StopOpcodeParsingException e ) { } }
implements the visitor to clear the parm set and check for potential methods
3,261
public void sawOpcode ( int seen ) { try { stack . precomputation ( this ) ; if ( OpcodeUtils . isStore ( seen ) || OpcodeUtils . isLoad ( seen ) ) { int reg = getRegisterOperand ( ) ; unusedParms . clear ( reg ) ; } else if ( OpcodeUtils . isReturn ( seen ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; int reg = item . getRegisterNumber ( ) ; if ( reg >= 0 ) { unusedParms . clear ( reg ) ; } } if ( unusedParms . isEmpty ( ) ) { throw new StopOpcodeParsingException ( ) ; } } finally { stack . sawOpcode ( this , seen ) ; } }
implements the visitor to look for usage of parmeter registers .
3,262
public static String getPackageName ( final String className ) { int dotPos = className . lastIndexOf ( '.' ) ; if ( dotPos < 0 ) { return "" ; } return className . substring ( 0 , dotPos ) ; }
parses the package name from a fully qualified class name
3,263
public static boolean similarPackages ( String packName1 , String packName2 , int depth ) { if ( depth == 0 ) { return true ; } String dottedPackName1 = packName1 . replace ( '/' , '.' ) ; String dottedPackName2 = packName2 . replace ( '/' , '.' ) ; int dot1 = dottedPackName1 . indexOf ( '.' ) ; int dot2 = dottedPackName2 . indexOf ( '.' ) ; if ( dot1 < 0 ) { return ( dot2 < 0 ) ; } else if ( dot2 < 0 ) { return false ; } String s1 = dottedPackName1 . substring ( 0 , dot1 ) ; String s2 = dottedPackName2 . substring ( 0 , dot2 ) ; if ( ! s1 . equals ( s2 ) ) { return false ; } return similarPackages ( dottedPackName1 . substring ( dot1 + 1 ) , dottedPackName2 . substring ( dot2 + 1 ) , depth - 1 ) ; }
returns whether or not the two packages have the same first depth parts if they exist
3,264
public static String getTypeCodeSignature ( int typeCode ) { String signature = Values . PRIMITIVE_TYPE_CODE_SIGS . get ( ( byte ) typeCode ) ; return signature == null ? Values . SIG_JAVA_LANG_OBJECT : signature ; }
converts a primitive type code to a signature
3,265
public static Map < Integer , String > getParameterSlotAndSignatures ( boolean methodIsStatic , String methodSignature ) { int start = methodSignature . indexOf ( '(' ) + 1 ; int limit = methodSignature . lastIndexOf ( ')' ) ; if ( ( limit - start ) == 0 ) { return Collections . emptyMap ( ) ; } Map < Integer , String > slotIndexToParms = new LinkedHashMap < > ( ) ; int slot = methodIsStatic ? 0 : 1 ; int sigStart = start ; for ( int i = start ; i < limit ; i ++ ) { if ( ! methodSignature . startsWith ( Values . SIG_ARRAY_PREFIX , i ) ) { String parmSignature = null ; if ( methodSignature . startsWith ( Values . SIG_QUALIFIED_CLASS_PREFIX , i ) ) { int semiPos = methodSignature . indexOf ( Values . SIG_QUALIFIED_CLASS_SUFFIX_CHAR , i + 1 ) ; parmSignature = methodSignature . substring ( sigStart , semiPos + 1 ) ; slotIndexToParms . put ( Integer . valueOf ( slot ) , parmSignature ) ; i = semiPos ; } else if ( isWonkyEclipseSignature ( methodSignature , i ) ) { sigStart ++ ; continue ; } else { parmSignature = methodSignature . substring ( sigStart , i + 1 ) ; slotIndexToParms . put ( Integer . valueOf ( slot ) , parmSignature ) ; } sigStart = i + 1 ; slot += getSignatureSize ( parmSignature ) ; } } return slotIndexToParms ; }
returns a Map that represents the type of the parameter in slot x
3,266
public static List < String > getParameterSignatures ( String methodSignature ) { int start = methodSignature . indexOf ( '(' ) + 1 ; int limit = methodSignature . lastIndexOf ( ')' ) ; if ( ( limit - start ) == 0 ) { return Collections . emptyList ( ) ; } List < String > parmSignatures = new ArrayList < > ( ) ; int sigStart = start ; for ( int i = start ; i < limit ; i ++ ) { if ( ! methodSignature . startsWith ( Values . SIG_ARRAY_PREFIX , i ) ) { if ( methodSignature . startsWith ( Values . SIG_QUALIFIED_CLASS_PREFIX , i ) ) { int semiPos = methodSignature . indexOf ( Values . SIG_QUALIFIED_CLASS_SUFFIX_CHAR , i + 1 ) ; parmSignatures . add ( methodSignature . substring ( sigStart , semiPos + 1 ) ) ; i = semiPos ; } else if ( ! isWonkyEclipseSignature ( methodSignature , i ) ) { parmSignatures . add ( methodSignature . substring ( sigStart , i + 1 ) ) ; } sigStart = i + 1 ; } } return parmSignatures ; }
returns a List of parameter signatures
3,267
public static String getReturnSignature ( String methodSig ) { int parenPos = methodSig . indexOf ( ')' ) ; if ( parenPos < 0 ) { return "?" ; } return methodSig . substring ( parenPos + 1 ) ; }
gets the return type signature from a method signature
3,268
public static int getNumParameters ( String methodSignature ) { int start = methodSignature . indexOf ( '(' ) + 1 ; int limit = methodSignature . lastIndexOf ( ')' ) ; if ( ( limit - start ) == 0 ) { return 0 ; } int numParms = 0 ; for ( int i = start ; i < limit ; i ++ ) { if ( ! methodSignature . startsWith ( Values . SIG_ARRAY_PREFIX , i ) ) { if ( methodSignature . startsWith ( Values . SIG_QUALIFIED_CLASS_PREFIX , i ) ) { i = methodSignature . indexOf ( Values . SIG_QUALIFIED_CLASS_SUFFIX_CHAR , i + 1 ) ; } else if ( isWonkyEclipseSignature ( methodSignature , i ) ) { continue ; } numParms ++ ; } } return numParms ; }
returns the number of parameters in this method signature
3,269
public static int getFirstRegisterSlot ( Method m ) { Type [ ] parms = m . getArgumentTypes ( ) ; int first = m . isStatic ( ) ? 0 : 1 ; for ( Type t : parms ) { first += getSignatureSize ( t . getSignature ( ) ) ; } return first ; }
returns the first open register slot after parameters
3,270
public static String toArraySignature ( String typeName ) { String sig = classToSignature ( typeName ) ; if ( ( sig == null ) || ( sig . length ( ) == 0 ) ) { return sig ; } return Values . SIG_ARRAY_PREFIX + sig ; }
Converts a type name into an array signature . Accepts slashed or dotted classnames or type signatures .
3,271
private static boolean isWonkyEclipseSignature ( String sig , int startIndex ) { return ( sig . length ( ) > startIndex ) && ( ECLIPSE_WEIRD_SIG_CHARS . indexOf ( sig . charAt ( startIndex ) ) >= 0 ) ; }
Eclipse makes weird class signatures .
3,272
public void visitClassContext ( ClassContext classContext ) { try { JavaClass cls = classContext . getJavaClass ( ) ; int major = cls . getMajor ( ) ; if ( major >= Const . MAJOR_1_5 ) { stack = new OpcodeStack ( ) ; super . visitClassContext ( classContext ) ; } } finally { stack = null ; } }
implements the visitor to check for class file version 1 . 5 or better
3,273
public void sawOpcode ( int seen ) { try { stack . precomputation ( this ) ; if ( ( seen != Const . INVOKEVIRTUAL ) || ! "wait" . equals ( getNameConstantOperand ( ) ) || stack . getStackDepth ( ) == 0 ) { return ; } JavaClass cls = stack . getStackItem ( 0 ) . getJavaClass ( ) ; if ( cls != null ) { String clsName = cls . getClassName ( ) ; if ( concurrentAwaitClasses . contains ( clsName ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . SWCO_SUSPICIOUS_WAIT_ON_CONCURRENT_OBJECT . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } finally { stack . sawOpcode ( this , seen ) ; } }
implements the visitor to look for calls to wait on java . util . concurrent classes that define await .
3,274
public void sawOpcode ( int seen ) { String strCon = null ; try { stack . precomputation ( this ) ; if ( seen == Const . INVOKESPECIAL ) { String clsName = getClassConstantOperand ( ) ; if ( SignatureUtils . isPlainStringConvertableClass ( clsName ) ) { String methodName = getNameConstantOperand ( ) ; String methodSig = getSigConstantOperand ( ) ; if ( Values . CONSTRUCTOR . equals ( methodName ) && XML_SIG_BUILDER . withReturnType ( "V" ) . toString ( ) . equals ( methodSig ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item itm = stack . getStackItem ( 0 ) ; strCon = ( String ) itm . getConstant ( ) ; } } } else if ( seen == Const . INVOKEVIRTUAL ) { String clsName = getClassConstantOperand ( ) ; if ( SignatureUtils . isPlainStringConvertableClass ( clsName ) ) { String methodName = getNameConstantOperand ( ) ; String methodSig = getSigConstantOperand ( ) ; if ( "append" . equals ( methodName ) && XML_SIG_BUILDER . withReturnType ( clsName ) . toString ( ) . equals ( methodSig ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item itm = stack . getStackItem ( 0 ) ; strCon = ( String ) itm . getConstant ( ) ; } } } if ( strCon != null ) { strCon = strCon . trim ( ) ; if ( strCon . length ( ) == 0 ) { return ; } for ( XMLPattern pattern : xmlPatterns ) { Matcher m = pattern . getPattern ( ) . matcher ( strCon ) ; if ( m . matches ( ) ) { xmlItemCount ++ ; if ( pattern . isConfident ( ) ) { xmlConfidentCount ++ ; } if ( ( firstPC < 0 ) && ( xmlConfidentCount > 0 ) ) { firstPC = getPC ( ) ; } break ; } } } } finally { stack . sawOpcode ( this , seen ) ; } }
overrides the visitor to find String concatenations including xml strings
3,275
public void sawOpcode ( int seen ) { try { switch ( state ) { case SAW_NOTHING : sawOpcodeAfterNothing ( seen ) ; break ; case SAW_EQUALS : sawOpcodeAfterEquals ( seen ) ; break ; case SAW_IFEQ : sawOpcodeAfterBranch ( seen ) ; break ; } processLoad ( seen ) ; processLoop ( seen ) ; } finally { stack . sawOpcode ( this , seen ) ; } }
implements the visitor to find continuations after finding a search result in a loop .
3,276
public void visitClassContext ( ClassContext classContext ) { try { stack = new OpcodeStack ( ) ; graphicsRegs = new HashMap < Integer , Integer > ( 5 ) ; super . visitClassContext ( classContext ) ; } finally { stack = null ; graphicsRegs = null ; } }
overrides the visitor to set up the opcode stack
3,277
public void visitCode ( Code obj ) { try { Method m = getMethod ( ) ; if ( m . isSynthetic ( ) ) { return ; } if ( m . isStatic ( ) || m . isPrivate ( ) || Values . CONSTRUCTOR . equals ( m . getName ( ) ) ) { parmSigs = SignatureUtils . getParameterSlotAndSignatures ( m . isStatic ( ) , m . getSignature ( ) ) ; if ( ! parmSigs . isEmpty ( ) && prescreen ( m ) ) { state = State . SAW_NOTHING ; bugs = new HashMap < > ( ) ; downwardBranchTarget = - 1 ; super . visitCode ( obj ) ; for ( BugInfo bi : bugs . values ( ) ) { bugReporter . reportBug ( bi . bug ) ; } } } } finally { bugs = null ; } }
implements the visitor to see if the method has parameters
3,278
public void sawOpcode ( int seen ) { if ( downwardBranchTarget == - 1 ) { switch ( state ) { case SAW_NOTHING : sawOpcodeAfterNothing ( seen ) ; break ; case SAW_LOAD : sawOpcodeAfterLoad ( seen ) ; break ; case SAW_CHECKCAST : sawOpcodeAfterCheckCast ( seen ) ; break ; } int insTarget = - 1 ; if ( ( ( seen >= Const . IFEQ ) && ( seen <= Const . IF_ACMPNE ) ) || ( seen == Const . GOTO ) || ( seen == Const . GOTO_W ) ) { insTarget = getBranchTarget ( ) ; if ( insTarget < getPC ( ) ) { insTarget = - 1 ; } } else if ( ( seen == Const . LOOKUPSWITCH ) || ( seen == Const . TABLESWITCH ) ) { insTarget = this . getDefaultSwitchOffset ( ) + getPC ( ) ; } if ( insTarget > downwardBranchTarget ) { downwardBranchTarget = insTarget ; } } else { state = State . SAW_NOTHING ; if ( getPC ( ) >= downwardBranchTarget ) { downwardBranchTarget = - 1 ; } } }
implements the visitor to look for check casts of parameters to more specific types
3,279
public void visitClassContext ( ClassContext classContext ) { try { currentClass = classContext . getJavaClass ( ) ; stack = new OpcodeStack ( ) ; returnTypes = new HashMap < > ( ) ; super . visitClassContext ( classContext ) ; } finally { currentClass = null ; stack = null ; returnTypes = null ; } }
implements the visitor to create and destroy the stack and return types
3,280
public void visitCode ( Code obj ) { Method m = getMethod ( ) ; if ( m . isSynthetic ( ) ) { return ; } String signature = m . getSignature ( ) ; if ( ! signature . endsWith ( ")Ljava/lang/Object;" ) ) { return ; } stack . resetForMethodEntry ( this ) ; returnTypes . clear ( ) ; super . visitCode ( obj ) ; if ( returnTypes . size ( ) <= 1 ) { return ; } String methodName = m . getName ( ) ; try { boolean isInherited = SignatureUtils . isInheritedMethod ( currentClass , methodName , signature ) ; int priority = NORMAL_PRIORITY ; for ( JavaClass cls : returnTypes . keySet ( ) ) { if ( ( cls != null ) && Values . DOTTED_JAVA_LANG_OBJECT . equals ( cls . getClassName ( ) ) ) { priority = LOW_PRIORITY ; break ; } } JavaClass cls = findCommonType ( returnTypes . keySet ( ) ) ; BugInstance bug ; if ( isInherited ) { bug = new BugInstance ( this , BugType . URV_INHERITED_METHOD_WITH_RELATED_TYPES . name ( ) , priority ) . addClass ( this ) . addMethod ( this ) ; if ( cls != null ) { bug . addString ( cls . getClassName ( ) ) ; } } else if ( cls == null ) { bug = new BugInstance ( this , BugType . URV_UNRELATED_RETURN_VALUES . name ( ) , priority ) . addClass ( this ) . addMethod ( this ) ; } else { bug = new BugInstance ( this , BugType . URV_CHANGE_RETURN_TYPE . name ( ) , priority ) . addClass ( this ) . addMethod ( this ) ; bug . addString ( cls . getClassName ( ) ) ; } for ( Integer pc : returnTypes . values ( ) ) { bug . addSourceLine ( this , pc . intValue ( ) ) ; } bugReporter . reportBug ( bug ) ; } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } }
implements the visitor to see if the method returns Object and if the method is defined in a superclass or interface .
3,281
public void sawOpcode ( int seen ) { try { stack . precomputation ( this ) ; if ( ( seen == Const . ARETURN ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item itm = stack . getStackItem ( 0 ) ; if ( ! itm . isNull ( ) ) { returnTypes . put ( itm . getJavaClass ( ) , Integer . valueOf ( getPC ( ) ) ) ; } } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } finally { stack . sawOpcode ( this , seen ) ; } }
implements the visitor to find return values where the types of objects returned from the method are related only by object .
3,282
private static JavaClass findCommonType ( Set < JavaClass > classes ) throws ClassNotFoundException { Set < JavaClass > possibleCommonTypes = new HashSet < > ( ) ; boolean populate = true ; for ( JavaClass cls : classes ) { if ( cls == null ) { return null ; } if ( Values . SLASHED_JAVA_LANG_OBJECT . equals ( cls . getClassName ( ) ) ) { continue ; } JavaClass [ ] infs = cls . getAllInterfaces ( ) ; JavaClass [ ] supers = cls . getSuperClasses ( ) ; if ( populate ) { possibleCommonTypes . addAll ( Arrays . asList ( infs ) ) ; possibleCommonTypes . addAll ( Arrays . asList ( supers ) ) ; possibleCommonTypes . remove ( Repository . lookupClass ( Values . SLASHED_JAVA_LANG_OBJECT ) ) ; populate = false ; } else { Set < JavaClass > retain = new HashSet < > ( ) ; retain . addAll ( Arrays . asList ( infs ) ) ; retain . addAll ( Arrays . asList ( supers ) ) ; possibleCommonTypes . retainAll ( retain ) ; } } if ( possibleCommonTypes . isEmpty ( ) ) { return null ; } for ( JavaClass cls : possibleCommonTypes ) { if ( cls . isInterface ( ) ) { return cls ; } } return possibleCommonTypes . iterator ( ) . next ( ) ; }
looks for a common superclass or interface for all the passed in types
3,283
public void visitCode ( Code obj ) { state = State . SAW_NOTHING ; stack . resetForMethodEntry ( this ) ; super . visitCode ( obj ) ; }
overrides the visitor to reset the state and reset the opcode stack
3,284
public void sawOpcode ( int seen ) { int pc = 0 ; try { stack . precomputation ( this ) ; switch ( state ) { case SAW_NOTHING : pc = sawOpcodeAfterNothing ( seen ) ; break ; case SAW_CTOR : if ( ( seen == Const . POP ) || ( seen == Const . RETURN ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . SEC_SIDE_EFFECT_CONSTRUCTOR . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } state = State . SAW_NOTHING ; break ; } } finally { TernaryPatcher . pre ( stack , seen ) ; stack . sawOpcode ( this , seen ) ; TernaryPatcher . post ( stack , seen ) ; if ( ( pc != 0 ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; item . setUserValue ( Integer . valueOf ( pc ) ) ; } } }
overrides the visitor to look for constructors who s value is popped off the stack and not assigned before the pop of the value or if a return is issued with that object still on the stack .
3,285
public void visitClassContext ( final ClassContext classContext ) { try { JavaClass cls = classContext . getJavaClass ( ) ; packageName = cls . getPackageName ( ) ; clsName = cls . getClassName ( ) ; parentClassName = cls . getSuperclassName ( ) ; stack = new OpcodeStack ( ) ; super . visitClassContext ( classContext ) ; } finally { stack = null ; clsAccessCount = null ; packageName = null ; clsName = null ; parentClassName = null ; } }
overrides the visitor to collect package and class names
3,286
public void visitMethod ( final Method obj ) { methodName = obj . getName ( ) ; methodIsStatic = obj . isStatic ( ) ; }
overrides the visitor to check whether the method is static
3,287
@ SuppressWarnings ( "unchecked" ) public void visitCode ( final Code obj ) { stack . resetForMethodEntry ( this ) ; thisClsAccessCount = 0 ; if ( Values . STATIC_INITIALIZER . equals ( methodName ) ) { return ; } clsAccessCount = new HashMap < > ( ) ; super . visitCode ( obj ) ; if ( clsAccessCount . isEmpty ( ) ) { return ; } Map . Entry < String , BitSet > [ ] envies = clsAccessCount . entrySet ( ) . toArray ( new Map . Entry [ clsAccessCount . size ( ) ] ) ; Arrays . sort ( envies , ACCESS_COUNT_COMPARATOR ) ; Map . Entry < String , BitSet > bestEnvyEntry = envies [ 0 ] ; int bestEnvyCount = bestEnvyEntry . getValue ( ) . cardinality ( ) ; if ( bestEnvyCount < minEnvy ) { return ; } double bestPercent = ( ( double ) bestEnvyCount ) / ( ( double ) ( bestEnvyCount + thisClsAccessCount ) ) ; if ( bestPercent > envyPercent ) { String bestEnvy = bestEnvyEntry . getKey ( ) ; if ( implementsCommonInterface ( bestEnvy ) ) { return ; } if ( envies . length > 1 ) { int runnerUpEnvyCount = 0 ; for ( int i = 1 ; i < envies . length ; i ++ ) { runnerUpEnvyCount += envies [ i ] . getValue ( ) . cardinality ( ) ; } if ( ( 2 * runnerUpEnvyCount ) > bestEnvyCount ) { return ; } } bugReporter . reportBug ( new BugInstance ( this , BugType . CE_CLASS_ENVY . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLineRange ( this , 0 , obj . getCode ( ) . length - 1 ) . addString ( bestEnvy ) ) ; } }
overrides the visitor to look for the method that uses another class the most and if it exceeds the threshold reports it
3,288
public void sawOpcode ( final int seen ) { try { stack . precomputation ( this ) ; if ( OpcodeUtils . isStandardInvoke ( seen ) ) { String calledClass = getDottedClassConstantOperand ( ) ; if ( seen == Const . INVOKEINTERFACE ) { int parmCount = SignatureUtils . getNumParameters ( this . getSigConstantOperand ( ) ) ; if ( ! countClassAccess ( parmCount ) ) { countClassAccess ( calledClass ) ; } } else { countClassAccess ( calledClass ) ; } } else if ( seen == Const . PUTFIELD ) { countClassAccess ( 1 ) ; } else if ( seen == Const . GETFIELD ) { countClassAccess ( 0 ) ; } else if ( ( seen == Const . PUTSTATIC ) || ( seen == Const . GETSTATIC ) ) { countClassAccess ( getDottedClassConstantOperand ( ) ) ; } else if ( ( seen == Const . ALOAD_0 ) && ( ! methodIsStatic ) ) { countClassAccess ( clsName ) ; } } finally { stack . sawOpcode ( this , seen ) ; } }
overrides the visitor to look for method calls and populate a class access count map based on the owning class of methods called .
3,289
private boolean implementsCommonInterface ( String name ) { try { JavaClass cls = Repository . lookupClass ( name ) ; JavaClass [ ] infs = cls . getAllInterfaces ( ) ; for ( JavaClass inf : infs ) { String infName = inf . getClassName ( ) ; if ( ignorableInterfaces . contains ( infName ) ) { continue ; } if ( infName . startsWith ( "java." ) ) { return true ; } } return false ; } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; return true ; } }
return whether or not a class implements a common or marker interface
3,290
private boolean countClassAccess ( final int classAtStackIndex ) { String calledClass ; try { if ( stack . getStackDepth ( ) > classAtStackIndex ) { OpcodeStack . Item itm = stack . getStackItem ( classAtStackIndex ) ; JavaClass cls = itm . getJavaClass ( ) ; if ( cls != null ) { calledClass = cls . getClassName ( ) ; countClassAccess ( calledClass ) ; return true ; } } } catch ( ClassNotFoundException cfne ) { bugReporter . reportMissingClass ( cfne ) ; } return false ; }
increment the count of class access of the class on the stack
3,291
private void countClassAccess ( final String calledClass ) { if ( calledClass . equals ( clsName ) || isAssociatedClass ( calledClass ) ) { if ( getPrevOpcode ( 1 ) != Const . ALOAD_0 ) { thisClsAccessCount ++ ; } } else { String calledPackage = SignatureUtils . getPackageName ( calledClass ) ; if ( SignatureUtils . similarPackages ( calledPackage , packageName , 2 ) && ! generalPurpose ( calledClass ) ) { BitSet lineNumbers = clsAccessCount . get ( calledClass ) ; if ( lineNumbers == null ) { lineNumbers = new BitSet ( ) ; addLineNumber ( lineNumbers ) ; clsAccessCount . put ( calledClass , lineNumbers ) ; } else { addLineNumber ( lineNumbers ) ; } } } }
increment the count of class access of the specified class if it is in a similar package to the caller and is not general purpose
3,292
private void addLineNumber ( BitSet lineNumbers ) { LineNumberTable lnt = getCode ( ) . getLineNumberTable ( ) ; if ( lnt == null ) { lineNumbers . set ( 0 ) ; } else { int line = lnt . getSourceLine ( getPC ( ) ) ; if ( line < 0 ) { lineNumbers . set ( lineNumbers . size ( ) ) ; } else { lineNumbers . set ( line ) ; } } }
add the current line number to a set of line numbers
3,293
@ edu . umd . cs . findbugs . annotations . SuppressFBWarnings ( value = "EXS_EXCEPTION_SOFTENING_RETURN_FALSE" , justification = "No other simple way to determine whether class exists" ) private boolean generalPurpose ( final String className ) { if ( className . startsWith ( "java." ) || className . startsWith ( "javax." ) ) { return true ; } try { JavaClass cls = Repository . lookupClass ( className ) ; JavaClass [ ] infs = cls . getAllInterfaces ( ) ; for ( JavaClass inf : infs ) { String infName = inf . getClassName ( ) ; if ( "java.io.Serializable" . equals ( infName ) || "java.lang.Cloneable" . equals ( infName ) || "java.lang.Comparable" . equals ( infName ) || "java.lang.Runnable" . equals ( infName ) ) { continue ; } if ( infName . startsWith ( "java.lang." ) || infName . startsWith ( "javax.lang." ) ) { return true ; } } JavaClass [ ] sups = cls . getSuperClasses ( ) ; for ( JavaClass sup : sups ) { String supName = sup . getClassName ( ) ; if ( Values . DOTTED_JAVA_LANG_OBJECT . equals ( supName ) || Values . DOTTED_JAVA_LANG_EXCEPTION . equals ( supName ) || Values . DOTTED_JAVA_LANG_RUNTIMEEXCEPTION . equals ( supName ) || "java.lang.Throwable" . equals ( supName ) ) { continue ; } if ( supName . startsWith ( "java.lang." ) || supName . startsWith ( "javax.lang." ) ) { return true ; } } } catch ( ClassNotFoundException cfne ) { bugReporter . reportMissingClass ( cfne ) ; return true ; } return false ; }
checks to see if the specified class is a built in class or implements a simple interface
3,294
public void visitClassContext ( ClassContext classContext ) { try { stack = new OpcodeStack ( ) ; localClassTypes = new HashMap < > ( ) ; fieldClassTypes = new HashMap < > ( ) ; JavaClass cls = classContext . getJavaClass ( ) ; Method staticInit = findStaticInitializer ( cls ) ; if ( staticInit != null ) { setupVisitorForClass ( cls ) ; doVisitMethod ( staticInit ) ; } super . visitClassContext ( classContext ) ; } finally { stack = null ; localClassTypes = null ; fieldClassTypes = null ; } }
implements the visitor to create the stack and local and field maps for Class arrays to be used for getting the reflection method
3,295
private static Method findStaticInitializer ( JavaClass cls ) { Method [ ] methods = cls . getMethods ( ) ; for ( Method m : methods ) { if ( Values . STATIC_INITIALIZER . equals ( m . getName ( ) ) ) { return m ; } } return null ; }
finds the method that is the static initializer for the class
3,296
public void visitClassContext ( ClassContext classContext ) { try { stack = new OpcodeStack ( ) ; ifBlocks = new IfBlocks ( ) ; gotoBranchPCs = new BitSet ( ) ; casePositions = new BitSet ( ) ; super . visitClassContext ( classContext ) ; } finally { stack = null ; ifBlocks = null ; catchPCs = null ; gotoBranchPCs = null ; casePositions = null ; } }
implements the visitor to reset the opcode stack and initialize if tracking collections
3,297
private boolean isResetOp ( int seen ) { return resetOps . get ( seen ) || OpcodeUtils . isStore ( seen ) || OpcodeUtils . isReturn ( seen ) || ( ( OpcodeUtils . isInvoke ( seen ) && getSigConstantOperand ( ) . endsWith ( ")V" ) ) || ( isBranch ( seen ) && ( getBranchOffset ( ) < 0 ) ) ) ; }
determines if this opcode couldn t be part of a conditional expression or at least is very unlikely to be so .
3,298
public void visitCode ( Code obj ) { try { stack . resetForMethodEntry ( this ) ; reportedType = ImmutabilityType . UNKNOWN ; super . visitCode ( obj ) ; } catch ( StopOpcodeParsingException e ) { } }
overrides the visitor to reset the opcode stack and reset the reported immutability of the method
3,299
public void sawOpcode ( int seen ) { ImmutabilityType imType = null ; try { stack . precomputation ( this ) ; switch ( seen ) { case Const . INVOKESTATIC : case Const . INVOKEINTERFACE : case Const . INVOKESPECIAL : case Const . INVOKEVIRTUAL : { String className = getClassConstantOperand ( ) ; String methodName = getNameConstantOperand ( ) ; String signature = getSigConstantOperand ( ) ; MethodInfo mi = Statistics . getStatistics ( ) . getMethodStatistics ( className , methodName , signature ) ; imType = mi . getImmutabilityType ( ) ; if ( seen == Const . INVOKEINTERFACE ) { Integer collectionOffset = MODIFYING_METHODS . get ( new QMethod ( methodName , signature ) ) ; if ( ( collectionOffset != null ) && CollectionUtils . isListSetMap ( className ) && ( stack . getStackDepth ( ) > collectionOffset . intValue ( ) ) ) { OpcodeStack . Item item = stack . getStackItem ( collectionOffset . intValue ( ) ) ; ImmutabilityType type = ( ImmutabilityType ) item . getUserValue ( ) ; if ( ( type == ImmutabilityType . IMMUTABLE ) || ( ( type == ImmutabilityType . POSSIBLY_IMMUTABLE ) && ( reportedType != ImmutabilityType . POSSIBLY_IMMUTABLE ) ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . MUC_MODIFYING_UNMODIFIABLE_COLLECTION . name ( ) , ( type == ImmutabilityType . IMMUTABLE ) ? HIGH_PRIORITY : NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; if ( type == ImmutabilityType . IMMUTABLE ) { throw new StopOpcodeParsingException ( ) ; } reportedType = type ; } } } } break ; default : break ; } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } finally { stack . sawOpcode ( this , seen ) ; if ( ( imType != null ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; item . setUserValue ( imType ) ; } } }
overrides the visitor to find method mutations on collections that have previously been determined to have been created as immutable collections