idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
153,200
public static void addFiles ( final Project findBugsProject , File clzDir , final Pattern pat ) { if ( clzDir . isDirectory ( ) ) { clzDir . listFiles ( new FileCollector ( pat , findBugsProject ) ) ; } }
recurse add all the files matching given name pattern inside the given directory and all subdirectories
58
19
153,201
private static void mapResource ( WorkItem resource , Map < IProject , List < WorkItem > > projectsMap , boolean checkJavaProject ) { IProject project = resource . getProject ( ) ; if ( checkJavaProject && ! ProjectUtilities . isJavaProject ( project ) ) { // non java projects: can happen only for changesets return ; } List < WorkItem > resources = projectsMap . get ( project ) ; if ( resources == null ) { resources = new ArrayList <> ( ) ; projectsMap . put ( project , resources ) ; } // do not need to check for duplicates, cause user cannot select // the same element twice if ( ! containsParents ( resources , resource ) ) { resources . add ( resource ) ; } }
Maps the resource into its project
157
6
153,202
@ SuppressWarnings ( "restriction" ) public static List < WorkItem > getResources ( ChangeSet set ) { if ( set != null && ! set . isEmpty ( ) ) { IResource [ ] resources = set . getResources ( ) ; List < WorkItem > filtered = new ArrayList <> ( ) ; for ( IResource resource : resources ) { if ( resource . getType ( ) == IResource . FILE && ! Util . isJavaArtifact ( resource ) ) { // Ignore non java files continue ; } if ( resource . exists ( ) ) { // add only resources which are NOT deleted filtered . add ( new WorkItem ( resource ) ) ; } } return filtered ; } return EMPTY ; }
Extracts only files from a change set
154
9
153,203
@ javax . annotation . CheckForNull public static IResource getResource ( Object element ) { if ( element instanceof IJavaElement ) { return ( ( IJavaElement ) element ) . getResource ( ) ; } return Util . getAdapter ( IResource . class , element ) ; }
Convenient method to get resources from adaptables
63
9
153,204
private ClassDescriptor getNullnessAnnotationClassDescriptor ( NullnessAnnotation n ) { if ( n == NullnessAnnotation . CHECK_FOR_NULL ) { return JSR305NullnessAnnotations . CHECK_FOR_NULL ; } else if ( n == NullnessAnnotation . NONNULL ) { return JSR305NullnessAnnotations . NONNULL ; } else if ( n == NullnessAnnotation . NULLABLE ) { return JSR305NullnessAnnotations . NULLABLE ; } else if ( n == NullnessAnnotation . UNKNOWN_NULLNESS ) { return JSR305NullnessAnnotations . NULLABLE ; } else { throw new IllegalArgumentException ( "Unknown NullnessAnnotation: " + n ) ; } }
Convert a NullnessAnnotation into the ClassDescriptor of the equivalent JSR - 305 nullness type qualifier .
163
25
153,205
public void addAll ( Collection < BugInstance > collection , boolean updateActiveTime ) { for ( BugInstance warning : collection ) { add ( warning , updateActiveTime ) ; } }
Add a Collection of BugInstances to this BugCollection object .
38
13
153,206
@ Override public AppVersion getCurrentAppVersion ( ) { return new AppVersion ( getSequenceNumber ( ) ) . setReleaseName ( getReleaseName ( ) ) . setTimestamp ( getTimestamp ( ) ) . setNumClasses ( getProjectStats ( ) . getNumClasses ( ) ) . setCodeSize ( getProjectStats ( ) . getCodeSize ( ) ) ; }
Get the current AppVersion .
85
6
153,207
public void readXML ( File file ) throws IOException , DocumentException { project . setCurrentWorkingDirectory ( file . getParentFile ( ) ) ; dataSource = file . getAbsolutePath ( ) ; InputStream in = progessMonitoredInputStream ( file , "Loading analysis" ) ; try { readXML ( in , file ) ; } catch ( IOException e ) { throw newIOException ( file , e ) ; } catch ( DocumentException e ) { throw new DocumentException ( "Failing reading " + file , e ) ; } }
Read XML data from given file into this object populating given Project as a side effect .
118
18
153,208
@ Override public Document toDocument ( ) { // if (project == null) throw new NullPointerException("No project"); assert project != null ; DocumentFactory docFactory = new DocumentFactory ( ) ; Document document = docFactory . createDocument ( ) ; Dom4JXMLOutput treeBuilder = new Dom4JXMLOutput ( document ) ; try { writeXML ( treeBuilder ) ; } catch ( IOException e ) { // Can't happen } return document ; }
Convert the BugCollection into a dom4j Document object .
101
13
153,209
public static void cloneAll ( Collection < BugInstance > dest , Collection < BugInstance > source ) { for ( BugInstance obj : source ) { dest . add ( ( BugInstance ) obj . clone ( ) ) ; } }
Clone all of the BugInstance objects in the source Collection and add them to the destination Collection .
47
20
153,210
public static void writeXML ( XMLOutput xmlOutput , String elementName , BugAnnotation annotation , XMLAttributeList attributeList , boolean addMessages ) throws IOException { SourceLineAnnotation src = null ; if ( annotation instanceof BugAnnotationWithSourceLines ) { src = ( ( BugAnnotationWithSourceLines ) annotation ) . getSourceLines ( ) ; } if ( addMessages || src != null ) { xmlOutput . openTag ( elementName , attributeList ) ; if ( src != null ) { src . writeXML ( xmlOutput , addMessages , false ) ; } if ( addMessages ) { xmlOutput . openTag ( BugAnnotation . MESSAGE_TAG ) ; xmlOutput . writeText ( annotation . toString ( ) ) ; xmlOutput . closeTag ( BugAnnotation . MESSAGE_TAG ) ; } xmlOutput . closeTag ( elementName ) ; } else { xmlOutput . openCloseTag ( elementName , attributeList ) ; } }
Write a BugAnnotation as XML .
216
8
153,211
public InnerClassAccess getInnerClassAccess ( String className , String methodName ) throws ClassNotFoundException { Map < String , InnerClassAccess > map = getAccessMapForClass ( className ) ; return map . get ( methodName ) ; }
Get the InnerClassAccess in given class with the given method name .
54
14
153,212
public InnerClassAccess getInnerClassAccess ( INVOKESTATIC inv , ConstantPoolGen cpg ) throws ClassNotFoundException { String methodName = inv . getMethodName ( cpg ) ; if ( methodName . startsWith ( "access$" ) ) { String className = inv . getClassName ( cpg ) ; return getInnerClassAccess ( className , methodName ) ; } return null ; }
Get the inner class access object for given invokestatic instruction . Returns null if the called method is not an inner class access .
91
27
153,213
private Map < String , InnerClassAccess > getAccessMapForClass ( String className ) throws ClassNotFoundException { Map < String , InnerClassAccess > map = classToAccessMap . get ( className ) ; if ( map == null ) { map = new HashMap <> ( 3 ) ; if ( ! className . startsWith ( "[" ) ) { JavaClass javaClass = Repository . lookupClass ( className ) ; Method [ ] methodList = javaClass . getMethods ( ) ; for ( Method method : methodList ) { String methodName = method . getName ( ) ; if ( ! methodName . startsWith ( "access$" ) ) { continue ; } Code code = method . getCode ( ) ; if ( code == null ) { continue ; } if ( DEBUG ) { System . out . println ( "Analyzing " + className + "." + method . getName ( ) + " as an inner-class access method..." ) ; } byte [ ] instructionList = code . getCode ( ) ; String methodSig = method . getSignature ( ) ; InstructionCallback callback = new InstructionCallback ( javaClass , methodName , methodSig , instructionList ) ; // try { new BytecodeScanner ( ) . scan ( instructionList , callback ) ; // } catch (LookupFailure lf) { // throw lf.getException(); // } InnerClassAccess access = callback . getAccess ( ) ; if ( DEBUG ) { System . out . println ( ( access != null ? "IS" : "IS NOT" ) + " an inner-class access method" ) ; } if ( access != null ) { map . put ( methodName , access ) ; } } } if ( map . size ( ) == 0 ) { map = Collections . emptyMap ( ) ; } else { map = new HashMap <> ( map ) ; } classToAccessMap . put ( className , map ) ; } return map ; }
Return a map of inner - class member access method names to the fields that they access for given class name .
417
22
153,214
public int getMnemonic ( ) { int mnemonic = KeyEvent . VK_UNDEFINED ; if ( ! MAC_OS_X ) { int index = getMnemonicIndex ( ) ; if ( ( index >= 0 ) && ( ( index + 1 ) < myAnnotatedString . length ( ) ) ) { mnemonic = Character . toUpperCase ( myAnnotatedString . charAt ( index + 1 ) ) ; } } return mnemonic ; }
Return the appropriate mnemonic character for this string . If no mnemonic should be displayed KeyEvent . VK_UNDEFINED is returned .
106
31
153,215
public static void localiseButton ( AbstractButton button , String key , String defaultString , boolean setMnemonic ) { AnnotatedString as = new AnnotatedString ( L10N . getLocalString ( key , defaultString ) ) ; button . setText ( as . toString ( ) ) ; int mnemonic ; if ( setMnemonic && ( mnemonic = as . getMnemonic ( ) ) != KeyEvent . VK_UNDEFINED ) { button . setMnemonic ( mnemonic ) ; button . setDisplayedMnemonicIndex ( as . getMnemonicIndex ( ) ) ; } }
Localise the given AbstractButton setting the text and optionally mnemonic Note that AbstractButton includes menus and menu items .
138
24
153,216
public MethodHash computeHash ( Method method ) { final MessageDigest digest = Util . getMD5Digest ( ) ; byte [ ] code ; if ( method . getCode ( ) == null || method . getCode ( ) . getCode ( ) == null ) { code = new byte [ 0 ] ; } else { code = method . getCode ( ) . getCode ( ) ; } BytecodeScanner . Callback callback = ( opcode , index ) -> digest . update ( ( byte ) opcode ) ; BytecodeScanner bytecodeScanner = new BytecodeScanner ( ) ; bytecodeScanner . scan ( code , callback ) ; hash = digest . digest ( ) ; return this ; }
Compute hash on given method .
152
7
153,217
static int compareGroups ( BugGroup m1 , BugGroup m2 ) { int result = m1 . compareTo ( m2 ) ; if ( result == 0 ) { return m1 . getShortDescription ( ) . compareToIgnoreCase ( m2 . getShortDescription ( ) ) ; } return result ; }
Sorts bug groups on severity first then on bug pattern name .
68
13
153,218
static int compareMarkers ( IMarker m1 , IMarker m2 ) { if ( m1 == null || m2 == null || ! m1 . exists ( ) || ! m2 . exists ( ) ) { return 0 ; } int rank1 = MarkerUtil . findBugRankForMarker ( m1 ) ; int rank2 = MarkerUtil . findBugRankForMarker ( m2 ) ; int result = rank1 - rank2 ; if ( result != 0 ) { return result ; } int prio1 = MarkerUtil . findConfidenceForMarker ( m1 ) . ordinal ( ) ; int prio2 = MarkerUtil . findConfidenceForMarker ( m2 ) . ordinal ( ) ; result = prio1 - prio2 ; if ( result != 0 ) { return result ; } String a1 = m1 . getAttribute ( IMarker . MESSAGE , "" ) ; String a2 = m2 . getAttribute ( IMarker . MESSAGE , "" ) ; return a1 . compareToIgnoreCase ( a2 ) ; }
Sorts markers on rank then priority and then on name if requested
244
13
153,219
public void setParamsWithProperty ( BitSet nonNullSet ) { for ( int i = 0 ; i < 32 ; ++ i ) { setParamWithProperty ( i , nonNullSet . get ( i ) ) ; } }
Set the non - null param set from given BitSet .
49
12
153,220
public void setParamWithProperty ( int param , boolean hasProperty ) { if ( param < 0 || param > 31 ) { return ; } if ( hasProperty ) { bits |= ( 1 << param ) ; } else { bits &= ~ ( 1 << param ) ; } }
Set whether or not a parameter might be non - null .
59
12
153,221
public BitSet getMatchingParameters ( BitSet nullArgSet ) { BitSet result = new BitSet ( ) ; for ( int i = 0 ; i < 32 ; ++ i ) { result . set ( i , nullArgSet . get ( i ) && hasProperty ( i ) ) ; } return result ; }
Given a bitset of null arguments passed to the method represented by this property return a bitset indicating which null arguments correspond to an non - null param .
67
31
153,222
public static int getNumParametersForInvocation ( InvokeInstruction inv , ConstantPoolGen cpg ) { SignatureParser sigParser = new SignatureParser ( inv . getSignature ( cpg ) ) ; return sigParser . getNumParameters ( ) ; }
Get the number of parameters passed to method invocation .
54
10
153,223
public void build ( ) { int numGood = 0 , numBytecodes = 0 ; if ( DEBUG ) { System . out . println ( "Method: " + methodGen . getName ( ) + " - " + methodGen . getSignature ( ) + "in class " + methodGen . getClassName ( ) ) ; } // Associate line number information with each InstructionHandle LineNumberTable table = methodGen . getLineNumberTable ( methodGen . getConstantPool ( ) ) ; if ( table != null && table . getTableLength ( ) > 0 ) { checkTable ( table ) ; InstructionHandle handle = methodGen . getInstructionList ( ) . getStart ( ) ; while ( handle != null ) { int bytecodeOffset = handle . getPosition ( ) ; if ( bytecodeOffset < 0 ) { throw new IllegalStateException ( "Bad bytecode offset: " + bytecodeOffset ) ; } if ( DEBUG ) { System . out . println ( "Looking for source line for bytecode offset " + bytecodeOffset ) ; } int sourceLine ; try { sourceLine = table . getSourceLine ( bytecodeOffset ) ; } catch ( ArrayIndexOutOfBoundsException e ) { if ( LINE_NUMBER_BUG ) { throw e ; } else { sourceLine = - 1 ; } } if ( sourceLine >= 0 ) { ++ numGood ; } lineNumberMap . put ( handle , new LineNumber ( bytecodeOffset , sourceLine ) ) ; handle = handle . getNext ( ) ; ++ numBytecodes ; } hasLineNumbers = true ; if ( DEBUG ) { System . out . println ( "\t" + numGood + "/" + numBytecodes + " had valid line numbers" ) ; } } }
Build the line number information . Should be called before any other methods .
373
14
153,224
public void setReturnValue ( MethodDescriptor methodDesc , TypeQualifierValue < ? > tqv , TypeQualifierAnnotation tqa ) { Map < TypeQualifierValue < ? > , TypeQualifierAnnotation > map = returnValueMap . get ( methodDesc ) ; if ( map == null ) { map = new HashMap <> ( ) ; returnValueMap . put ( methodDesc , map ) ; } map . put ( tqv , tqa ) ; if ( DEBUG ) { System . out . println ( "tqdb: " + methodDesc + " for " + tqv + " ==> " + tqa ) ; } }
Set a TypeQualifierAnnotation on a method return value .
140
13
153,225
public TypeQualifierAnnotation getReturnValue ( MethodDescriptor methodDesc , TypeQualifierValue < ? > tqv ) { // // TODO: handling of overridden methods? // Map < TypeQualifierValue < ? > , TypeQualifierAnnotation > map = returnValueMap . get ( methodDesc ) ; if ( map == null ) { return null ; } return map . get ( tqv ) ; }
Get the TypeQualifierAnnotation on a method return value .
89
13
153,226
public void setParameter ( MethodDescriptor methodDesc , int param , TypeQualifierValue < ? > tqv , TypeQualifierAnnotation tqa ) { Map < TypeQualifierValue < ? > , TypeQualifierAnnotation > map = parameterMap . get ( methodDesc , param ) ; if ( map == null ) { map = new HashMap <> ( ) ; parameterMap . put ( methodDesc , param , map ) ; } map . put ( tqv , tqa ) ; if ( DEBUG ) { System . out . println ( "tqdb: " + methodDesc + " parameter " + param + " for " + tqv + " ==> " + tqa ) ; } }
Set a TypeQualifierAnnotation on a method parameter .
150
12
153,227
public TypeQualifierAnnotation getParameter ( MethodDescriptor methodDesc , int param , TypeQualifierValue < ? > tqv ) { // // TODO: handling of overridden methods? // Map < TypeQualifierValue < ? > , TypeQualifierAnnotation > map = parameterMap . get ( methodDesc , param ) ; if ( map == null ) { return null ; } return map . get ( tqv ) ; }
Get the TypeQualifierAnnotation on a parameter .
92
11
153,228
protected static boolean isLongOrDouble ( FieldInstruction fieldIns , ConstantPoolGen cpg ) { Type type = fieldIns . getFieldType ( cpg ) ; int code = type . getType ( ) ; return code == Const . T_LONG || code == Const . T_DOUBLE ; }
Return whether the given FieldInstruction accesses a long or double field .
66
15
153,229
protected static Variable snarfFieldValue ( FieldInstruction fieldIns , ConstantPoolGen cpg , ValueNumberFrame frame ) throws DataflowAnalysisException { if ( isLongOrDouble ( fieldIns , cpg ) ) { int numSlots = frame . getNumSlots ( ) ; ValueNumber topValue = frame . getValue ( numSlots - 1 ) ; ValueNumber nextValue = frame . getValue ( numSlots - 2 ) ; return new LongOrDoubleLocalVariable ( topValue , nextValue ) ; } else { return new LocalVariable ( frame . getTopValue ( ) ) ; } }
Get a Variable representing the stack value which will either be stored into or loaded from a field .
128
19
153,230
public static Collection < TypeQualifierValue < ? > > getRelevantTypeQualifiers ( MethodDescriptor methodDescriptor , CFG cfg ) throws CheckedAnalysisException { final HashSet < TypeQualifierValue < ? > > result = new HashSet <> ( ) ; XMethod xmethod = XFactory . createXMethod ( methodDescriptor ) ; if ( FIND_EFFECTIVE_RELEVANT_QUALIFIERS ) { if ( DEBUG_FIND_EFFECTIVE_RELEVANT_QUALIFIERS ) { System . out . println ( "**** Finding effective type qualifiers for " + xmethod ) ; } // // This will take care of methods using fields annotated with // a type qualifier. // getDirectlyRelevantTypeQualifiers ( xmethod , result ) ; // For all known type qualifiers, find the effective (direct, // inherited, // or default) type qualifier annotations // on the method and all methods directly called by the method. // addEffectiveRelevantQualifiers ( result , xmethod ) ; IAnalysisCache analysisCache = Global . getAnalysisCache ( ) ; ConstantPoolGen cpg = analysisCache . getClassAnalysis ( ConstantPoolGen . class , methodDescriptor . getClassDescriptor ( ) ) ; for ( Iterator < Location > i = cfg . locationIterator ( ) ; i . hasNext ( ) ; ) { Location location = i . next ( ) ; Instruction ins = location . getHandle ( ) . getInstruction ( ) ; if ( ins instanceof InvokeInstruction ) { if ( ins instanceof INVOKEDYNAMIC ) { // TODO handle INVOKEDYNAMIC } else { XMethod called = XFactory . createXMethod ( ( InvokeInstruction ) ins , cpg ) ; addEffectiveRelevantQualifiers ( result , called ) ; } } if ( DEBUG_FIND_EFFECTIVE_RELEVANT_QUALIFIERS ) { System . out . println ( "===> result: " + result ) ; } } // // XXX: this code can go away eventually // if ( ! methodDescriptor . isStatic ( ) ) { // Instance method - must consider type qualifiers inherited // from superclasses SupertypeTraversalVisitor visitor = new OverriddenMethodsVisitor ( xmethod ) { /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.ba.ch.OverriddenMethodsVisitor# * visitOverriddenMethod(edu.umd.cs.findbugs.ba.XMethod) */ @ Override protected boolean visitOverriddenMethod ( XMethod xmethod ) { getDirectlyRelevantTypeQualifiers ( xmethod , result ) ; return true ; } } ; try { AnalysisContext . currentAnalysisContext ( ) . getSubtypes2 ( ) . traverseSupertypesDepthFirst ( xmethod . getClassDescriptor ( ) , visitor ) ; } catch ( ClassNotFoundException e ) { AnalysisContext . currentAnalysisContext ( ) . getLookupFailureCallback ( ) . reportMissingClass ( e ) ; return Collections . < TypeQualifierValue < ? > > emptySet ( ) ; } catch ( UncheckedAnalysisException e ) { AnalysisContext . currentAnalysisContext ( ) . getLookupFailureCallback ( ) . logError ( "Error getting relevant type qualifiers for " + xmethod . toString ( ) , e ) ; return Collections . < TypeQualifierValue < ? > > emptySet ( ) ; } } } return result ; }
Find relevant type qualifiers needing to be checked for a given method .
757
13
153,231
public static ClassDescriptor createClassDescriptorFromResourceName ( String resourceName ) { if ( ! isClassResource ( resourceName ) ) { throw new IllegalArgumentException ( "Resource " + resourceName + " is not a class" ) ; } return createClassDescriptor ( resourceName . substring ( 0 , resourceName . length ( ) - 6 ) ) ; }
Create a class descriptor from a resource name .
82
9
153,232
public static @ CheckForNull ClassDescriptor createClassDescriptorFromFieldSignature ( String signature ) { int start = signature . indexOf ( ' ' ) ; if ( start < 0 ) { return null ; } int end = signature . indexOf ( ' ' , start ) ; if ( end < 0 ) { return null ; } return createClassDescriptor ( signature . substring ( start + 1 , end ) ) ; }
Create a class descriptor from a field signature
93
8
153,233
public void setPluginList ( Path src ) { if ( pluginList == null ) { pluginList = src ; } else { pluginList . append ( src ) ; } }
the plugin list to use .
36
6
153,234
public void addAllowedClass ( String className ) { String classRegex = START + dotsToRegex ( className ) + ".class$" ; LOG . debug ( "Class regex: {}" , classRegex ) ; patternList . add ( Pattern . compile ( classRegex ) . matcher ( "" ) ) ; }
Add the name of a class to be matched by the screener .
71
15
153,235
public void addAllowedPackage ( String packageName ) { if ( packageName . endsWith ( "." ) ) { packageName = packageName . substring ( 0 , packageName . length ( ) - 1 ) ; } String packageRegex = START + dotsToRegex ( packageName ) + SEP + JAVA_IDENTIFIER_PART + "+.class$" ; LOG . debug ( "Package regex: {}" , packageRegex ) ; patternList . add ( Pattern . compile ( packageRegex ) . matcher ( "" ) ) ; }
Add the name of a package to be matched by the screener . All class files that appear to be in the package should be matched .
120
29
153,236
public void addAllowedPrefix ( String prefix ) { if ( prefix . endsWith ( "." ) ) { prefix = prefix . substring ( 0 , prefix . length ( ) - 1 ) ; } LOG . debug ( "Allowed prefix: {}" , prefix ) ; String packageRegex = START + dotsToRegex ( prefix ) + SEP ; LOG . debug ( "Prefix regex: {}" , packageRegex ) ; patternList . add ( Pattern . compile ( packageRegex ) . matcher ( "" ) ) ; }
Add the name of a prefix to be matched by the screener . All class files that appear to be in the package specified by the prefix or a more deeply nested package should be matched .
115
39
153,237
@ Deprecated public @ Nonnull String getMessage ( String key ) { BugPattern bugPattern = DetectorFactoryCollection . instance ( ) . lookupBugPattern ( key ) ; if ( bugPattern == null ) { return L10N . getLocalString ( "err.missing_pattern" , "Error: missing bug pattern for key" ) + " " + key ; } return bugPattern . getAbbrev ( ) + ": " + bugPattern . getLongDescription ( ) ; }
Get a message string . This is a format pattern for describing an entire bug instance in a single line .
103
21
153,238
public @ Nonnull String getDetailHTML ( String key ) { BugPattern bugPattern = DetectorFactoryCollection . instance ( ) . lookupBugPattern ( key ) ; if ( bugPattern == null ) { return L10N . getLocalString ( "err.missing_pattern" , "Error: missing bug pattern for key" ) + " " + key ; } return bugPattern . getDetailHTML ( ) ; }
Get an HTML document describing the bug pattern for given key in detail .
89
14
153,239
public String getAnnotationDescription ( String key ) { try { return annotationDescriptionBundle . getString ( key ) ; } catch ( MissingResourceException mre ) { if ( DEBUG ) { return "TRANSLATE(" + key + ") (param={0}}" ; } else { try { return englishAnnotationDescriptionBundle . getString ( key ) ; } catch ( MissingResourceException mre2 ) { return key + " {0}" ; } } } }
Get an annotation description string . This is a format pattern which will describe a BugAnnotation in the context of a particular bug instance . Its single format argument is the BugAnnotation .
101
37
153,240
public String getBugCategoryDescription ( String category ) { BugCategory bc = DetectorFactoryCollection . instance ( ) . getBugCategory ( category ) ; return ( bc != null ? bc . getShortDescription ( ) : category ) ; }
Get the description of a bug category . Returns the category if no description can be found .
49
18
153,241
JPanel createSourceCodePanel ( ) { Font sourceFont = new Font ( "Monospaced" , Font . PLAIN , ( int ) Driver . getFontSize ( ) ) ; mainFrame . getSourceCodeTextPane ( ) . setFont ( sourceFont ) ; mainFrame . getSourceCodeTextPane ( ) . setEditable ( false ) ; mainFrame . getSourceCodeTextPane ( ) . getCaret ( ) . setSelectionVisible ( true ) ; mainFrame . getSourceCodeTextPane ( ) . setDocument ( SourceCodeDisplay . SOURCE_NOT_RELEVANT ) ; JScrollPane sourceCodeScrollPane = new JScrollPane ( mainFrame . getSourceCodeTextPane ( ) ) ; sourceCodeScrollPane . getVerticalScrollBar ( ) . setUnitIncrement ( 20 ) ; JPanel panel = new JPanel ( ) ; panel . setLayout ( new BorderLayout ( ) ) ; panel . add ( sourceCodeScrollPane , BorderLayout . CENTER ) ; panel . revalidate ( ) ; if ( MainFrame . GUI2_DEBUG ) { System . out . println ( "Created source code panel" ) ; } return panel ; }
Creates the source code panel but does not put anything in it .
262
14
153,242
public void scrollLineToVisible ( int line , int margin ) { int maxMargin = ( parentHeight ( ) - 20 ) / 2 ; if ( margin > maxMargin ) { margin = Math . max ( 0 , maxMargin ) ; } scrollLineToVisibleImpl ( line , margin ) ; }
scroll the specified line into view with a margin of margin pixels above and below
67
15
153,243
public void scrollLinesToVisible ( int startLine , int endLine , Collection < Integer > otherLines ) { int startY , endY ; try { startY = lineToY ( startLine ) ; } catch ( BadLocationException ble ) { if ( MainFrame . GUI2_DEBUG ) { ble . printStackTrace ( ) ; } return ; // give up } try { endY = lineToY ( endLine ) ; } catch ( BadLocationException ble ) { endY = startY ; // better than nothing } int max = parentHeight ( ) - 0 ; if ( endY - startY > max ) { endY = startY + max ; } else if ( otherLines != null && otherLines . size ( ) > 0 ) { int origin = startY + endY / 2 ; PriorityQueue < Integer > pq = new PriorityQueue <> ( otherLines . size ( ) , new DistanceComparator ( origin ) ) ; for ( int line : otherLines ) { int otherY ; try { otherY = lineToY ( line ) ; } catch ( BadLocationException ble ) { continue ; // give up on this one } pq . add ( otherY ) ; } while ( ! pq . isEmpty ( ) ) { int y = pq . remove ( ) ; int lo = Math . min ( startY , y ) ; int hi = Math . max ( endY , y ) ; if ( hi - lo > max ) { break ; } else { startY = lo ; endY = hi ; } } } if ( endY - startY > max ) { endY = startY + max ; } scrollYToVisibleImpl ( ( startY + endY ) / 2 , max / 2 ) ; }
scroll the specified primary lines into view along with as many of the other lines as is convenient
379
18
153,244
private void examineBasicBlocks ( ) throws DataflowAnalysisException , CFGBuilderException { // Look for null check blocks where the reference being checked // is definitely null, or null on some path Iterator < BasicBlock > bbIter = invDataflow . getCFG ( ) . blockIterator ( ) ; while ( bbIter . hasNext ( ) ) { BasicBlock basicBlock = bbIter . next ( ) ; if ( basicBlock . isNullCheck ( ) ) { analyzeNullCheck ( invDataflow , basicBlock ) ; } else if ( ! basicBlock . isEmpty ( ) ) { // Look for all reference comparisons where // - both values compared are definitely null, or // - one value is definitely null and one is definitely not null // These cases are not null dereferences, // but they are quite likely to indicate an error, so while // we've got // information about null values, we may as well report them. InstructionHandle lastHandle = basicBlock . getLastInstruction ( ) ; Instruction last = lastHandle . getInstruction ( ) ; switch ( last . getOpcode ( ) ) { case Const . IF_ACMPEQ : case Const . IF_ACMPNE : analyzeRefComparisonBranch ( basicBlock , lastHandle ) ; break ; case Const . IFNULL : case Const . IFNONNULL : analyzeIfNullBranch ( basicBlock , lastHandle ) ; break ; default : break ; } } } }
Examine basic blocks for null checks and potentially - redundant null comparisons .
308
14
153,245
private void examineNullValues ( ) throws CFGBuilderException , DataflowAnalysisException { Set < LocationWhereValueBecomesNull > locationWhereValueBecomesNullSet = invDataflow . getAnalysis ( ) . getLocationWhereValueBecomesNullSet ( ) ; if ( DEBUG_DEREFS ) { System . out . println ( "----------------------- examineNullValues " + locationWhereValueBecomesNullSet . size ( ) ) ; } Map < ValueNumber , SortedSet < Location > > bugStatementLocationMap = new HashMap <> ( ) ; // Inspect the method for locations where a null value is guaranteed to // be dereferenced. Add the dereference locations Map < ValueNumber , NullValueUnconditionalDeref > nullValueGuaranteedDerefMap = new HashMap <> ( ) ; // Check every location CFG cfg = classContext . getCFG ( method ) ; for ( Iterator < Location > i = cfg . locationIterator ( ) ; i . hasNext ( ) ; ) { Location location = i . next ( ) ; if ( DEBUG_DEREFS ) { System . out . println ( "At location " + location ) ; } checkForUnconditionallyDereferencedNullValues ( location , bugStatementLocationMap , nullValueGuaranteedDerefMap , vnaDataflow . getFactAtLocation ( location ) , invDataflow . getFactAtLocation ( location ) , uvdDataflow . getFactAfterLocation ( location ) , false ) ; } HashSet < ValueNumber > npeIfStatementCovered = new HashSet <> ( nullValueGuaranteedDerefMap . keySet ( ) ) ; Map < ValueNumber , SortedSet < Location > > bugEdgeLocationMap = new HashMap <> ( ) ; checkEdges ( cfg , nullValueGuaranteedDerefMap , bugEdgeLocationMap ) ; Map < ValueNumber , SortedSet < Location > > bugLocationMap = bugEdgeLocationMap ; bugLocationMap . putAll ( bugStatementLocationMap ) ; // For each value number that is null somewhere in the // method, collect the set of locations where it becomes null. // FIXME: we may see some locations that are not guaranteed to be // dereferenced (how to fix this?) Map < ValueNumber , Set < Location > > nullValueAssignmentMap = findNullAssignments ( locationWhereValueBecomesNullSet ) ; reportBugs ( nullValueGuaranteedDerefMap , npeIfStatementCovered , bugLocationMap , nullValueAssignmentMap ) ; }
Examine null values . Report any that are guaranteed to be dereferenced on non - implicit - exception paths .
556
24
153,246
private void noteUnconditionallyDereferencedNullValue ( Location thisLocation , Map < ValueNumber , SortedSet < Location > > bugLocations , Map < ValueNumber , NullValueUnconditionalDeref > nullValueGuaranteedDerefMap , UnconditionalValueDerefSet derefSet , IsNullValue isNullValue , ValueNumber valueNumber ) { if ( DEBUG ) { System . out . println ( "%%% HIT for value number " + valueNumber + " @ " + thisLocation ) ; } Set < Location > unconditionalDerefLocationSet = derefSet . getUnconditionalDerefLocationSet ( valueNumber ) ; if ( unconditionalDerefLocationSet . isEmpty ( ) ) { AnalysisContext . logError ( "empty set of unconditionally dereferenced locations at " + thisLocation . getHandle ( ) . getPosition ( ) + " in " + classContext . getClassDescriptor ( ) + "." + method . getName ( ) + method . getSignature ( ) ) ; return ; } // OK, we have a null value that is unconditionally // derferenced. Make a note of the locations where it // will be dereferenced. NullValueUnconditionalDeref thisNullValueDeref = nullValueGuaranteedDerefMap . get ( valueNumber ) ; if ( thisNullValueDeref == null ) { thisNullValueDeref = new NullValueUnconditionalDeref ( ) ; nullValueGuaranteedDerefMap . put ( valueNumber , thisNullValueDeref ) ; } thisNullValueDeref . add ( isNullValue , unconditionalDerefLocationSet ) ; if ( thisLocation != null ) { SortedSet < Location > locationsForThisBug = bugLocations . get ( valueNumber ) ; if ( locationsForThisBug == null ) { locationsForThisBug = new TreeSet <> ( ) ; bugLocations . put ( valueNumber , locationsForThisBug ) ; } locationsForThisBug . add ( thisLocation ) ; } }
Note the locations where a known - null value is unconditionally dereferenced .
451
17
153,247
private void examineRedundantBranches ( ) { for ( RedundantBranch redundantBranch : redundantBranchList ) { if ( DEBUG ) { System . out . println ( "Redundant branch: " + redundantBranch ) ; } int lineNumber = redundantBranch . lineNumber ; // The source to bytecode compiler may sometimes duplicate blocks of // code along different control paths. So, to report the bug, // we check to ensure that the branch is REALLY determined each // place it is duplicated, and that it is determined in the same // way. boolean confused = undeterminedBranchSet . get ( lineNumber ) || ( definitelySameBranchSet . get ( lineNumber ) && definitelyDifferentBranchSet . get ( lineNumber ) ) ; // confused if there is JSR confusion or multiple null checks with // different results on the same line boolean reportIt = true ; if ( lineMentionedMultipleTimes . get ( lineNumber ) && confused ) { reportIt = false ; } else if ( redundantBranch . location . getBasicBlock ( ) . isInJSRSubroutine ( ) /* * occurs * in * a * JSR */ && confused ) { reportIt = false ; } else { int pc = redundantBranch . location . getHandle ( ) . getPosition ( ) ; for ( CodeException e : method . getCode ( ) . getExceptionTable ( ) ) { if ( e . getCatchType ( ) == 0 && e . getStartPC ( ) != e . getHandlerPC ( ) && e . getEndPC ( ) <= pc && pc <= e . getEndPC ( ) + 5 ) { reportIt = false ; } } } if ( reportIt ) { collector . foundRedundantNullCheck ( redundantBranch . location , redundantBranch ) ; } } }
Examine redundant branches .
386
5
153,248
private void analyzeIfNullBranch ( BasicBlock basicBlock , InstructionHandle lastHandle ) throws DataflowAnalysisException { Location location = new Location ( lastHandle , basicBlock ) ; IsNullValueFrame frame = invDataflow . getFactAtLocation ( location ) ; if ( ! frame . isValid ( ) ) { // This is probably dead code due to an infeasible exception edge. return ; } IsNullValue top = frame . getTopValue ( ) ; // Find the line number. int lineNumber = getLineNumber ( method , lastHandle ) ; if ( lineNumber < 0 ) { return ; } if ( ! ( top . isDefinitelyNull ( ) || top . isDefinitelyNotNull ( ) ) ) { if ( DEBUG ) { System . out . println ( "Line " + lineNumber + " undetermined" ) ; } undeterminedBranchSet . set ( lineNumber ) ; return ; } // Figure out if the branch is always taken // or always not taken. short opcode = lastHandle . getInstruction ( ) . getOpcode ( ) ; boolean definitelySame = top . isDefinitelyNull ( ) ; if ( opcode != Const . IFNULL ) { definitelySame = ! definitelySame ; } if ( definitelySame ) { if ( DEBUG ) { System . out . println ( "Line " + lineNumber + " always same" ) ; } definitelySameBranchSet . set ( lineNumber ) ; } else { if ( DEBUG ) { System . out . println ( "Line " + lineNumber + " always different" ) ; } definitelyDifferentBranchSet . set ( lineNumber ) ; } RedundantBranch redundantBranch = new RedundantBranch ( location , lineNumber , top ) ; // Determine which control edge is made infeasible by the redundant // comparison boolean wantNull = ( opcode == Const . IFNULL ) ; int infeasibleEdgeType = ( wantNull == top . isDefinitelyNull ( ) ) ? EdgeTypes . FALL_THROUGH_EDGE : EdgeTypes . IFCMP_EDGE ; Edge infeasibleEdge = invDataflow . getCFG ( ) . getOutgoingEdgeWithType ( basicBlock , infeasibleEdgeType ) ; redundantBranch . setInfeasibleEdge ( infeasibleEdge ) ; if ( DEBUG ) { System . out . println ( "Adding redundant branch: " + redundantBranch ) ; } redundantBranchList . add ( redundantBranch ) ; }
This is called for both IFNULL and IFNONNULL instructions .
528
14
153,249
public @ Nonnull BugPattern getBugPattern ( ) { BugPattern result = DetectorFactoryCollection . instance ( ) . lookupBugPattern ( getType ( ) ) ; if ( result != null ) { return result ; } AnalysisContext . logError ( "Unable to find description of bug pattern " + getType ( ) ) ; result = DetectorFactoryCollection . instance ( ) . lookupBugPattern ( "UNKNOWN" ) ; if ( result != null ) { return result ; } return BugPattern . REALLY_UNKNOWN ; }
Get the BugPattern .
111
5
153,250
@ CheckForNull private < T extends BugAnnotation > T findPrimaryAnnotationOfType ( Class < T > cls ) { T firstMatch = null ; for ( Iterator < BugAnnotation > i = annotationIterator ( ) ; i . hasNext ( ) ; ) { BugAnnotation annotation = i . next ( ) ; if ( cls . isAssignableFrom ( annotation . getClass ( ) ) ) { if ( annotation . getDescription ( ) . endsWith ( "DEFAULT" ) ) { return cls . cast ( annotation ) ; } else if ( firstMatch == null ) { firstMatch = cls . cast ( annotation ) ; } } } return firstMatch ; }
Find the first BugAnnotation in the list of annotations that is the same type or a subtype as the given Class parameter .
147
26
153,251
public @ CheckForNull < A extends BugAnnotation > A getAnnotationWithRole ( Class < A > c , String role ) { for ( BugAnnotation a : annotationList ) { if ( c . isInstance ( a ) && Objects . equals ( role , a . getDescription ( ) ) ) { return c . cast ( a ) ; } } return null ; }
Get the first bug annotation with the specified class and role ; return null if no such annotation exists ;
79
20
153,252
public String getProperty ( String name ) { BugProperty prop = lookupProperty ( name ) ; return prop != null ? prop . getValue ( ) : null ; }
Get value of given property .
34
6
153,253
public String getProperty ( String name , String defaultValue ) { String value = getProperty ( name ) ; return value != null ? value : defaultValue ; }
Get value of given property returning given default value if the property has not been set .
33
17
153,254
@ Nonnull public BugInstance setProperty ( String name , String value ) { BugProperty prop = lookupProperty ( name ) ; if ( prop != null ) { prop . setValue ( value ) ; } else { prop = new BugProperty ( name , value ) ; addProperty ( prop ) ; } return this ; }
Set value of given property .
66
6
153,255
public BugProperty lookupProperty ( String name ) { BugProperty prop = propertyListHead ; while ( prop != null ) { if ( prop . getName ( ) . equals ( name ) ) { break ; } prop = prop . getNext ( ) ; } return prop ; }
Look up a property by name .
57
7
153,256
public boolean deleteProperty ( String name ) { BugProperty prev = null ; BugProperty prop = propertyListHead ; while ( prop != null ) { if ( prop . getName ( ) . equals ( name ) ) { break ; } prev = prop ; prop = prop . getNext ( ) ; } if ( prop != null ) { if ( prev != null ) { // Deleted node in interior or at tail of list prev . setNext ( prop . getNext ( ) ) ; } else { // Deleted node at head of list propertyListHead = prop . getNext ( ) ; } if ( prop . getNext ( ) == null ) { // Deleted node at end of list propertyListTail = prev ; } return true ; } else { // No such property return false ; } }
Delete property with given name .
166
6
153,257
@ Nonnull public BugInstance addAnnotations ( Collection < ? extends BugAnnotation > annotationCollection ) { for ( BugAnnotation annotation : annotationCollection ) { add ( annotation ) ; } return this ; }
Add a Collection of BugAnnotations .
43
8
153,258
@ Nonnull public BugInstance addClassAndMethod ( PreorderVisitor visitor ) { addClass ( visitor ) ; XMethod m = visitor . getXMethod ( ) ; addMethod ( visitor ) ; if ( ! MemberUtils . isUserGenerated ( m ) ) { foundInAutogeneratedMethod ( ) ; } return this ; }
Add a class annotation and a method annotation for the class and method which the given visitor is currently visiting .
73
21
153,259
@ Nonnull public BugInstance addClassAndMethod ( JavaClass javaClass , Method method ) { addClass ( javaClass . getClassName ( ) ) ; addMethod ( javaClass , method ) ; if ( ! MemberUtils . isUserGenerated ( method ) ) { foundInAutogeneratedMethod ( ) ; } return this ; }
Add class and method annotations for given class and method .
73
11
153,260
@ Nonnull public BugInstance addClass ( ClassNode classNode ) { String dottedClassName = ClassName . toDottedClassName ( classNode . name ) ; ClassAnnotation classAnnotation = new ClassAnnotation ( dottedClassName ) ; add ( classAnnotation ) ; return this ; }
Add a class annotation for the classNode .
63
9
153,261
@ Nonnull public BugInstance addClass ( PreorderVisitor visitor ) { String className = visitor . getDottedClassName ( ) ; addClass ( className ) ; return this ; }
Add a class annotation for the class that the visitor is currently visiting .
41
14
153,262
@ Nonnull public BugInstance addSuperclass ( PreorderVisitor visitor ) { String className = ClassName . toDottedClassName ( visitor . getSuperclassName ( ) ) ; addClass ( className ) ; return this ; }
Add a class annotation for the superclass of the class the visitor is currently visiting .
51
17
153,263
@ Nonnull public BugInstance addType ( String typeDescriptor ) { TypeAnnotation typeAnnotation = new TypeAnnotation ( typeDescriptor ) ; add ( typeAnnotation ) ; return this ; }
Add a type annotation . Handy for referring to array types .
45
13
153,264
@ Nonnull public BugInstance addField ( String className , String fieldName , String fieldSig , boolean isStatic ) { addField ( new FieldAnnotation ( className , fieldName , fieldSig , isStatic ) ) ; return this ; }
Add a field annotation .
54
5
153,265
@ Nonnull public BugInstance addField ( FieldVariable field ) { return addField ( field . getClassName ( ) , field . getFieldName ( ) , field . getFieldSig ( ) , field . isStatic ( ) ) ; }
Add a field annotation for a FieldVariable matched in a ByteCodePattern .
52
15
153,266
@ Nonnull public BugInstance addField ( FieldDescriptor fieldDescriptor ) { FieldAnnotation fieldAnnotation = FieldAnnotation . fromFieldDescriptor ( fieldDescriptor ) ; add ( fieldAnnotation ) ; return this ; }
Add a field annotation for a FieldDescriptor .
53
11
153,267
@ Nonnull public BugInstance addVisitedField ( PreorderVisitor visitor ) { FieldAnnotation f = FieldAnnotation . fromVisitedField ( visitor ) ; addField ( f ) ; return this ; }
Add a field annotation for the field which is being visited by given visitor .
45
15
153,268
@ Nonnull public BugInstance addOptionalLocalVariable ( DismantleBytecode dbc , OpcodeStack . Item item ) { int register = item . getRegisterNumber ( ) ; if ( register >= 0 ) { this . add ( LocalVariableAnnotation . getLocalVariableAnnotation ( dbc . getMethod ( ) , register , dbc . getPC ( ) - 1 , dbc . getPC ( ) ) ) ; } return this ; }
Local variable adders
94
4
153,269
@ Nonnull public BugInstance addMethod ( PreorderVisitor visitor ) { MethodAnnotation methodAnnotation = MethodAnnotation . fromVisitedMethod ( visitor ) ; addMethod ( methodAnnotation ) ; addSourceLinesForMethod ( methodAnnotation , SourceLineAnnotation . fromVisitedMethod ( visitor ) ) ; return this ; }
Add a method annotation for the method which the given visitor is currently visiting . If the method has source line information then a SourceLineAnnotation is added to the method .
72
34
153,270
@ Nonnull public BugInstance addCalledMethod ( DismantleBytecode visitor ) { return addMethod ( MethodAnnotation . fromCalledMethod ( visitor ) ) . describe ( MethodAnnotation . METHOD_CALLED ) ; }
Add a method annotation for the method which has been called by the method currently being visited by given visitor . Assumes that the visitor has just looked at an invoke instruction of some kind .
50
37
153,271
@ Nonnull public BugInstance addCalledMethod ( String className , String methodName , String methodSig , boolean isStatic ) { return addMethod ( MethodAnnotation . fromCalledMethod ( className , methodName , methodSig , isStatic ) ) . describe ( MethodAnnotation . METHOD_CALLED ) ; }
Add a method annotation .
72
5
153,272
@ Nonnull public BugInstance addParameterAnnotation ( int index , String role ) { return addInt ( index + 1 ) . describe ( role ) ; }
Add an annotation about a parameter
33
6
153,273
@ Nonnull public BugInstance addString ( char c ) { add ( StringAnnotation . fromRawString ( Character . toString ( c ) ) ) ; return this ; }
Add a String annotation .
37
5
153,274
@ Nonnull public BugInstance addSourceLine ( ClassContext classContext , MethodGen methodGen , String sourceFile , InstructionHandle start , InstructionHandle end ) { // Make sure start and end are really in the right order. if ( start . getPosition ( ) > end . getPosition ( ) ) { InstructionHandle tmp = start ; start = end ; end = tmp ; } SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation . fromVisitedInstructionRange ( classContext , methodGen , sourceFile , start , end ) ; if ( sourceLineAnnotation != null ) { add ( sourceLineAnnotation ) ; } return this ; }
Add a source line annotation describing a range of instructions .
136
11
153,275
@ Nonnull public BugInstance addUnknownSourceLine ( String className , String sourceFile ) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation . createUnknown ( className , sourceFile ) ; if ( sourceLineAnnotation != null ) { add ( sourceLineAnnotation ) ; } return this ; }
Add a non - specific source line annotation . This will result in the entire source file being displayed .
67
20
153,276
@ Nonnull public BugInstance describe ( String description ) { annotationList . get ( annotationList . size ( ) - 1 ) . setDescription ( description ) ; return this ; }
Add a description to the most recently added bug annotation .
37
11
153,277
public ExceptionSet getEdgeExceptionSet ( Edge edge ) { CachedExceptionSet cachedExceptionSet = thrownExceptionSetMap . get ( edge . getSource ( ) ) ; return cachedExceptionSet . getEdgeExceptionSet ( edge ) ; }
Get the set of exceptions that can be thrown on given edge . This should only be called after the analysis completes .
49
23
153,278
private CachedExceptionSet getCachedExceptionSet ( BasicBlock basicBlock ) { CachedExceptionSet cachedExceptionSet = thrownExceptionSetMap . get ( basicBlock ) ; if ( cachedExceptionSet == null ) { // When creating the cached exception type set for the first time: // - the block result is set to TOP, so it won't match // any block result that has actually been computed // using the analysis transfer function // - the exception set is created as empty (which makes it // return TOP as its common superclass) TypeFrame top = createFact ( ) ; makeFactTop ( top ) ; cachedExceptionSet = new CachedExceptionSet ( top , exceptionSetFactory . createExceptionSet ( ) ) ; thrownExceptionSetMap . put ( basicBlock , cachedExceptionSet ) ; } return cachedExceptionSet ; }
Get the cached set of exceptions that can be thrown from given basic block . If this information hasn t been computed yet then an empty exception set is returned .
171
31
153,279
private CachedExceptionSet computeBlockExceptionSet ( BasicBlock basicBlock , TypeFrame result ) throws DataflowAnalysisException { ExceptionSet exceptionSet = computeThrownExceptionTypes ( basicBlock ) ; TypeFrame copyOfResult = createFact ( ) ; copy ( result , copyOfResult ) ; CachedExceptionSet cachedExceptionSet = new CachedExceptionSet ( copyOfResult , exceptionSet ) ; thrownExceptionSetMap . put ( basicBlock , cachedExceptionSet ) ; return cachedExceptionSet ; }
Compute the set of exceptions that can be thrown from the given basic block . This should only be called if the existing cached exception set is out of date .
103
32
153,280
private ExceptionSet computeEdgeExceptionSet ( Edge edge , ExceptionSet thrownExceptionSet ) { if ( thrownExceptionSet . isEmpty ( ) ) { return thrownExceptionSet ; } ExceptionSet result = exceptionSetFactory . createExceptionSet ( ) ; if ( edge . getType ( ) == UNHANDLED_EXCEPTION_EDGE ) { // The unhandled exception edge always comes // after all of the handled exception edges. result . addAll ( thrownExceptionSet ) ; thrownExceptionSet . clear ( ) ; return result ; } BasicBlock handlerBlock = edge . getTarget ( ) ; CodeExceptionGen handler = handlerBlock . getExceptionGen ( ) ; ObjectType catchType = handler . getCatchType ( ) ; if ( Hierarchy . isUniversalExceptionHandler ( catchType ) ) { result . addAll ( thrownExceptionSet ) ; thrownExceptionSet . clear ( ) ; } else { // Go through the set of thrown exceptions. // Any that will DEFINITELY be caught be this handler, remove. // Any that MIGHT be caught, but won't definitely be caught, // remain. for ( ExceptionSet . ThrownExceptionIterator i = thrownExceptionSet . iterator ( ) ; i . hasNext ( ) ; ) { // ThrownException thrownException = i.next(); ObjectType thrownType = i . next ( ) ; boolean explicit = i . isExplicit ( ) ; if ( DEBUG ) { System . out . println ( "\texception type " + thrownType + ", catch type " + catchType ) ; } try { if ( Hierarchy . isSubtype ( thrownType , catchType ) ) { // Exception can be thrown along this edge result . add ( thrownType , explicit ) ; // And it will definitely be caught i . remove ( ) ; if ( DEBUG ) { System . out . println ( "\tException is subtype of catch type: " + "will definitely catch" ) ; } } else if ( Hierarchy . isSubtype ( catchType , thrownType ) ) { // Exception possibly thrown along this edge result . add ( thrownType , explicit ) ; if ( DEBUG ) { System . out . println ( "\tException is supertype of catch type: " + "might catch" ) ; } } } catch ( ClassNotFoundException e ) { // As a special case, if a class hierarchy lookup // fails, then we will conservatively assume that the // exception in question CAN, but WON'T NECESSARILY // be caught by the handler. AnalysisContext . reportMissingClass ( e ) ; result . add ( thrownType , explicit ) ; } } } return result ; }
Based on the set of exceptions that can be thrown from the source basic block compute the set of exceptions that can propagate along given exception edge . This method should be called for each outgoing exception edge in sequence so the caught exceptions can be removed from the thrown exception set as needed .
550
55
153,281
@ CheckForNull public static JavaClass getOuterClass ( JavaClass obj ) throws ClassNotFoundException { for ( Attribute a : obj . getAttributes ( ) ) { if ( a instanceof InnerClasses ) { for ( InnerClass ic : ( ( InnerClasses ) a ) . getInnerClasses ( ) ) { if ( obj . getClassNameIndex ( ) == ic . getInnerClassIndex ( ) ) { // System.out.println("Outer class is " + // ic.getOuterClassIndex()); ConstantClass oc = ( ConstantClass ) obj . getConstantPool ( ) . getConstant ( ic . getOuterClassIndex ( ) ) ; String ocName = oc . getBytes ( obj . getConstantPool ( ) ) ; return Repository . lookupClass ( ocName ) ; } } } } return null ; }
Determine the outer class of obj .
189
9
153,282
public void addVerticesToSet ( Set < VertexType > set ) { // Add the vertex for this object set . add ( this . m_vertex ) ; // Add vertices for all children Iterator < SearchTree < VertexType > > i = childIterator ( ) ; while ( i . hasNext ( ) ) { SearchTree < VertexType > child = i . next ( ) ; child . addVerticesToSet ( set ) ; } }
Add all vertices contained in this search tree to the given set .
99
14
153,283
private void checkQualifier ( XMethod xmethod , CFG cfg , TypeQualifierValue < ? > typeQualifierValue , ForwardTypeQualifierDataflowFactory forwardDataflowFactory , BackwardTypeQualifierDataflowFactory backwardDataflowFactory , ValueNumberDataflow vnaDataflow ) throws CheckedAnalysisException { if ( DEBUG ) { System . out . println ( "----------------------------------------------------------------------" ) ; System . out . println ( "Checking type qualifier " + typeQualifierValue . toString ( ) + " on method " + xmethod . toString ( ) ) ; if ( typeQualifierValue . isStrictQualifier ( ) ) { System . out . println ( " Strict type qualifier" ) ; } System . out . println ( "----------------------------------------------------------------------" ) ; } if ( DEBUG_DATAFLOW ) { System . out . println ( "********* Valuenumber analysis *********" ) ; DataflowCFGPrinter < ValueNumberFrame , ValueNumberAnalysis > p = new DataflowCFGPrinter <> ( vnaDataflow ) ; p . print ( System . out ) ; } ForwardTypeQualifierDataflow forwardDataflow = forwardDataflowFactory . getDataflow ( typeQualifierValue ) ; if ( DEBUG_DATAFLOW && ( DEBUG_DATAFLOW_MODE . startsWith ( "forward" ) || "both" . equals ( DEBUG_DATAFLOW_MODE ) ) ) { System . out . println ( "********* Forwards analysis *********" ) ; DataflowCFGPrinter < TypeQualifierValueSet , ForwardTypeQualifierDataflowAnalysis > p = new DataflowCFGPrinter <> ( forwardDataflow ) ; p . print ( System . out ) ; } BackwardTypeQualifierDataflow backwardDataflow = backwardDataflowFactory . getDataflow ( typeQualifierValue ) ; if ( DEBUG_DATAFLOW && ( DEBUG_DATAFLOW_MODE . startsWith ( "backward" ) || "both" . equals ( DEBUG_DATAFLOW_MODE ) ) ) { System . out . println ( "********* Backwards analysis *********" ) ; DataflowCFGPrinter < TypeQualifierValueSet , BackwardTypeQualifierDataflowAnalysis > p = new DataflowCFGPrinter <> ( backwardDataflow ) ; p . print ( System . out ) ; } checkDataflow ( xmethod , cfg , typeQualifierValue , vnaDataflow , forwardDataflow , backwardDataflow ) ; checkValueSources ( xmethod , cfg , typeQualifierValue , vnaDataflow , forwardDataflow , backwardDataflow ) ; }
Check a specific TypeQualifierValue on a method .
566
11
153,284
public void setMethodHash ( XMethod method , byte [ ] methodHash ) { methodHashMap . put ( method , new MethodHash ( method . getName ( ) , method . getSignature ( ) , method . isStatic ( ) , methodHash ) ) ; }
Set method hash for given method .
57
7
153,285
public void setClassHash ( byte [ ] classHash ) { this . classHash = new byte [ classHash . length ] ; System . arraycopy ( classHash , 0 , this . classHash , 0 , classHash . length ) ; }
Set class hash .
51
4
153,286
public ClassHash computeHash ( JavaClass javaClass ) { this . className = javaClass . getClassName ( ) ; Method [ ] methodList = new Method [ javaClass . getMethods ( ) . length ] ; // Sort methods System . arraycopy ( javaClass . getMethods ( ) , 0 , methodList , 0 , javaClass . getMethods ( ) . length ) ; Arrays . sort ( methodList , ( o1 , o2 ) -> { // sort by name, then signature int cmp = o1 . getName ( ) . compareTo ( o2 . getName ( ) ) ; if ( cmp != 0 ) { return cmp ; } return o1 . getSignature ( ) . compareTo ( o2 . getSignature ( ) ) ; } ) ; Field [ ] fieldList = new Field [ javaClass . getFields ( ) . length ] ; // Sort fields System . arraycopy ( javaClass . getFields ( ) , 0 , fieldList , 0 , javaClass . getFields ( ) . length ) ; Arrays . sort ( fieldList , ( o1 , o2 ) -> { int cmp = o1 . getName ( ) . compareTo ( o2 . getName ( ) ) ; if ( cmp != 0 ) { return cmp ; } return o1 . getSignature ( ) . compareTo ( o2 . getSignature ( ) ) ; } ) ; MessageDigest digest = Util . getMD5Digest ( ) ; // Compute digest of method names and signatures, in order. // Also, compute method hashes. CharsetEncoder encoder = Charset . forName ( "UTF-8" ) . newEncoder ( ) ; for ( Method method : methodList ) { work ( digest , method . getName ( ) , encoder ) ; work ( digest , method . getSignature ( ) , encoder ) ; MethodHash methodHash = new MethodHash ( ) . computeHash ( method ) ; methodHashMap . put ( XFactory . createXMethod ( javaClass , method ) , methodHash ) ; } // Compute digest of field names and signatures. for ( Field field : fieldList ) { work ( digest , field . getName ( ) , encoder ) ; work ( digest , field . getSignature ( ) , encoder ) ; } classHash = digest . digest ( ) ; return this ; }
Compute hash for given class and all of its methods .
513
12
153,287
public static String hashToString ( byte [ ] hash ) { StringBuilder buf = new StringBuilder ( ) ; for ( byte b : hash ) { buf . append ( HEX_CHARS [ ( b >> 4 ) & 0xF ] ) ; buf . append ( HEX_CHARS [ b & 0xF ] ) ; } return buf . toString ( ) ; }
Convert a hash to a string of hex digits .
81
11
153,288
public static byte [ ] stringToHash ( String s ) { if ( s . length ( ) % 2 != 0 ) { throw new IllegalArgumentException ( "Invalid hash string: " + s ) ; } byte [ ] hash = new byte [ s . length ( ) / 2 ] ; for ( int i = 0 ; i < s . length ( ) ; i += 2 ) { byte b = ( byte ) ( ( hexDigitValue ( s . charAt ( i ) ) << 4 ) + hexDigitValue ( s . charAt ( i + 1 ) ) ) ; hash [ i / 2 ] = b ; } return hash ; }
Convert a string of hex digits to a hash .
137
11
153,289
public static Variable lookup ( String varName , BindingSet bindingSet ) { if ( bindingSet == null ) { return null ; } Binding binding = bindingSet . lookup ( varName ) ; return ( binding != null ) ? binding . getVariable ( ) : null ; }
Look up a variable definition in given BindingSet .
56
10
153,290
public WarningPropertySet < T > addProperty ( T prop ) { map . put ( prop , Boolean . TRUE ) ; return this ; }
Add a warning property to the set . The warning implicitly has the boolean value true as its attribute .
29
20
153,291
public WarningPropertySet < T > setProperty ( T prop , String value ) { map . put ( prop , value ) ; return this ; }
Add a warning property and its attribute value .
30
9
153,292
public boolean checkProperty ( T prop , Object value ) { Object attribute = getProperty ( prop ) ; return ( attribute != null && attribute . equals ( value ) ) ; }
Check whether or not the given WarningProperty has the given attribute value .
36
14
153,293
public int computePriority ( int basePriority ) { boolean relaxedReporting = FindBugsAnalysisFeatures . isRelaxedMode ( ) ; boolean atLeastMedium = false ; boolean falsePositive = false ; boolean atMostLow = false ; boolean atMostMedium = false ; boolean peggedHigh = false ; int aLittleBitLower = 0 ; int priority = basePriority ; if ( ! relaxedReporting ) { for ( T warningProperty : map . keySet ( ) ) { PriorityAdjustment adj = warningProperty . getPriorityAdjustment ( ) ; if ( adj == PriorityAdjustment . PEGGED_HIGH ) { peggedHigh = true ; priority -- ; } else if ( adj == PriorityAdjustment . FALSE_POSITIVE ) { falsePositive = true ; atMostLow = true ; } else if ( adj == PriorityAdjustment . A_LITTLE_BIT_LOWER_PRIORITY ) { aLittleBitLower ++ ; } else if ( adj == PriorityAdjustment . A_LITTLE_BIT_HIGHER_PRIORITY ) { aLittleBitLower -- ; } else if ( adj == PriorityAdjustment . RAISE_PRIORITY ) { -- priority ; } else if ( adj == PriorityAdjustment . RAISE_PRIORITY_TO_AT_LEAST_NORMAL ) { -- priority ; atLeastMedium = true ; } else if ( adj == PriorityAdjustment . LOWER_PRIORITY_TO_AT_MOST_NORMAL ) { ++ priority ; atMostMedium = true ; } else if ( adj == PriorityAdjustment . RAISE_PRIORITY_TO_HIGH ) { return Priorities . HIGH_PRIORITY ; } else if ( adj == PriorityAdjustment . LOWER_PRIORITY ) { ++ priority ; } else if ( adj == PriorityAdjustment . AT_MOST_LOW ) { priority ++ ; atMostLow = true ; } else if ( adj == PriorityAdjustment . AT_MOST_MEDIUM ) { atMostMedium = true ; } else if ( adj == PriorityAdjustment . NO_ADJUSTMENT ) { assert true ; // do nothing } else { throw new IllegalStateException ( "Unknown priority " + adj ) ; } } if ( peggedHigh && ! falsePositive ) { return Priorities . HIGH_PRIORITY ; } if ( aLittleBitLower >= 3 || priority == 1 && aLittleBitLower == 2 ) { priority ++ ; } else if ( aLittleBitLower <= - 2 ) { priority -- ; } if ( atMostMedium ) { priority = Math . max ( Priorities . NORMAL_PRIORITY , priority ) ; } if ( falsePositive && ! atLeastMedium ) { return Priorities . EXP_PRIORITY + 1 ; } else if ( atMostLow ) { return Math . min ( Math . max ( Priorities . LOW_PRIORITY , priority ) , Priorities . EXP_PRIORITY ) ; } if ( atLeastMedium && priority > Priorities . NORMAL_PRIORITY ) { priority = Priorities . NORMAL_PRIORITY ; } if ( priority < Priorities . HIGH_PRIORITY ) { priority = Priorities . HIGH_PRIORITY ; } else if ( priority > Priorities . EXP_PRIORITY ) { priority = Priorities . EXP_PRIORITY ; } } return priority ; }
Use the PriorityAdjustments specified by the set s WarningProperty elements to compute a warning priority from the given base priority .
728
24
153,294
public void decorateBugInstance ( BugInstance bugInstance ) { int priority = computePriority ( bugInstance . getPriority ( ) ) ; bugInstance . setPriority ( priority ) ; for ( Map . Entry < T , Object > entry : map . entrySet ( ) ) { WarningProperty prop = entry . getKey ( ) ; Object attribute = entry . getValue ( ) ; if ( attribute == null ) { attribute = "" ; } bugInstance . setProperty ( prop . getName ( ) , attribute . toString ( ) ) ; } }
Decorate given BugInstance with properties .
116
8
153,295
public ValueNumber getEntryValueForParameter ( int param ) { SignatureParser sigParser = new SignatureParser ( methodGen . getSignature ( ) ) ; int p = 0 ; int slotOffset = methodGen . isStatic ( ) ? 0 : 1 ; for ( String paramSig : sigParser . parameterSignatures ( ) ) { if ( p == param ) { return getEntryValue ( slotOffset ) ; } p ++ ; slotOffset += SignatureParser . getNumSlotsForType ( paramSig ) ; } throw new IllegalStateException ( ) ; }
Get the value number assigned to the given parameter upon entry to the method .
118
15
153,296
public static void writeCollection ( XMLOutput xmlOutput , Collection < ? extends XMLWriteable > collection ) throws IOException { for ( XMLWriteable obj : collection ) { obj . writeXML ( xmlOutput ) ; } }
Write a Collection of XMLWriteable objects .
47
9
153,297
@ Override public void addParameterAnnotation ( int param , AnnotationValue annotationValue ) { HashMap < Integer , Map < ClassDescriptor , AnnotationValue > > updatedAnnotations = new HashMap <> ( methodParameterAnnotations ) ; Map < ClassDescriptor , AnnotationValue > paramMap = updatedAnnotations . get ( param ) ; if ( paramMap == null ) { paramMap = new HashMap <> ( ) ; updatedAnnotations . put ( param , paramMap ) ; } paramMap . put ( annotationValue . getAnnotationClass ( ) , annotationValue ) ; methodParameterAnnotations = updatedAnnotations ; TypeQualifierApplications . updateAnnotations ( this ) ; }
Destructively add a parameter annotation .
149
8
153,298
String getResourceName ( ) { if ( ! resourceNameKnown ) { // The resource name of a classfile can only be determined by // reading // the file and parsing the constant pool. // If we can't do this for some reason, then we just // make the resource name equal to the filename. try { resourceName = getClassDescriptor ( ) . toResourceName ( ) ; } catch ( Exception e ) { resourceName = fileName ; } resourceNameKnown = true ; } return resourceName ; }
Get the resource name of the single file . We have to open the file and parse the constant pool in order to find this out .
108
27
153,299
public InputStream getInputStreamFromOffset ( int offset ) throws IOException { loadFileData ( ) ; return new ByteArrayInputStream ( data , offset , data . length - offset ) ; }
Get an InputStream on data starting at given offset .
41
11