idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
2,900
|
private static Process startProcess ( String [ ] exec ) throws IOException { Process process = Runtime . getRuntime ( ) . exec ( exec ) ; return process ; }
|
Starts a OS level process .
|
2,901
|
private static BufferedReader createReader ( Process process ) { InputStream inputStream = process . getInputStream ( ) ; InputStreamReader in = new InputStreamReader ( inputStream ) ; BufferedReader reader = new BufferedReader ( in ) ; return reader ; }
|
Creates a Reader instance for the process output .
|
2,902
|
private static int readEnvironment ( String cmdExec , Properties properties ) { BufferedReader reader = null ; Process process = null ; int exitValue = 99 ; try { String [ ] args = new String [ ] { cmdExec } ; process = startProcess ( args ) ; reader = createReader ( process ) ; processLinesOfEnvironmentVariables ( reader , properties ) ; process . waitFor ( ) ; reader . close ( ) ; } catch ( InterruptedException t ) { throw new EnvironmentException ( "NA" , t ) ; } catch ( IOException t ) { throw new EnvironmentException ( "NA" , t ) ; } finally { if ( process != null ) { process . destroy ( ) ; exitValue = process . exitValue ( ) ; } close ( reader ) ; } return exitValue ; }
|
Reads the environment variables and stores them in a Properties object .
|
2,903
|
public PropertiesWriter append ( final String key , final String value ) { NullArgumentException . validateNotEmpty ( key , "Key" ) ; String valueToAdd = value ; if ( value == null ) { valueToAdd = "" ; } Integer position = m_positions . get ( key ) ; List < String > values = m_values . get ( key ) ; if ( values == null ) { values = new ArrayList < String > ( ) ; m_values . put ( key , values ) ; } values . add ( valueToAdd ) ; StringBuilder builder = new StringBuilder ( ) . append ( key ) . append ( "=" ) ; if ( values . size ( ) == 1 ) { builder . append ( valueToAdd ) ; } else { builder . append ( "\\\n" ) ; String trail = null ; for ( String storedValue : values ) { if ( trail != null ) { builder . append ( trail ) ; } builder . append ( storedValue ) ; trail = m_separator + "\\\n" ; } } if ( position == null ) { m_content . add ( builder . toString ( ) ) ; m_positions . put ( key , m_content . size ( ) - 1 ) ; } else { m_content . set ( position , builder . toString ( ) ) ; } return this ; }
|
Appends a property to be written .
|
2,904
|
public PropertiesWriter append ( final String comment ) { String commentToAdd = "#" + comment ; if ( comment == null ) { commentToAdd = "#" ; } m_content . add ( commentToAdd ) ; return this ; }
|
Appends a comment to be written .
|
2,905
|
public void write ( ) throws IOException { BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( m_outputStream ) ) ; for ( String line : m_content ) { writer . write ( line ) ; writer . newLine ( ) ; } writer . flush ( ) ; writer . close ( ) ; }
|
Write properties to output stream .
|
2,906
|
public void exception ( ExceptionSource source , Throwable exception ) { synchronized ( m_monitors ) { for ( ExceptionMonitor monitor : m_monitors ) { monitor . exception ( source , exception ) ; } } }
|
This method is called when an Exception or Throwable occurs .
|
2,907
|
private boolean matchesIncludes ( final String fileName ) { if ( m_includes . length == 0 ) { return true ; } for ( Pattern include : m_includes ) { if ( include . matcher ( fileName ) . matches ( ) ) { return true ; } } return false ; }
|
Checks if the file name matches inclusion patterns .
|
2,908
|
private boolean matchesExcludes ( final String fileName ) { for ( Pattern include : m_excludes ) { if ( include . matcher ( fileName ) . matches ( ) ) { return true ; } } return false ; }
|
Checks if the file name matches exclusion patterns .
|
2,909
|
private List < String > listFiles ( final File dir , final String parentName ) { final List < String > fileNames = new ArrayList < String > ( ) ; File [ ] files = null ; if ( dir . canRead ( ) ) { files = dir . listFiles ( ) ; } if ( files != null ) { for ( File file : files ) { if ( file . isDirectory ( ) ) { fileNames . addAll ( listFiles ( file , parentName + file . getName ( ) + "/" ) ) ; } else { fileNames . add ( parentName + file . getName ( ) ) ; } } } return fileNames ; }
|
Lists recursively files form a directory
|
2,910
|
public String getString ( String key ) throws MissingResourceException { ResourceBundle bundle = getBundle ( ) ; return bundle . getString ( key ) ; }
|
Retrieve a raw string from bundle .
|
2,911
|
public ResourceBundle getBundle ( ) throws MissingResourceException { if ( null == m_bundle ) { ClassLoader classLoader = m_classLoader ; if ( null == classLoader ) { classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; } if ( null != classLoader ) { m_bundle = ResourceBundle . getBundle ( m_baseName , m_locale , classLoader ) ; } else { m_bundle = ResourceBundle . getBundle ( m_baseName , m_locale ) ; } } return m_bundle ; }
|
Retrieve underlying ResourceBundle . If bundle has not been loaded it will be loaded by this method . Access is given in case other resources need to be extracted that this Manager does not provide simplified access to .
|
2,912
|
private String getPatternString ( String key ) throws MissingResourceException { ResourceBundle bundle = getBundle ( ) ; Object object = bundle . getObject ( key ) ; if ( object instanceof String ) { return ( String ) object ; } else if ( object instanceof String [ ] ) { String [ ] strings = ( String [ ] ) object ; return strings [ RANDOM . nextInt ( strings . length ) ] ; } else { throw new MissingResourceException ( "Unable to find resource of appropriate type." , "java.lang.String" , key ) ; } }
|
Utility method to retrieve a string from ResourceBundle . If the key is a single string then that will be returned . If key refers to string array then a random string will be chosen . Other types cause an exception .
|
2,913
|
public static Store < InputStream > anonymousStore ( ) throws IOException { File temp = File . createTempFile ( "ops4j-store-anonymous-" , "" ) ; temp . delete ( ) ; temp . mkdir ( ) ; return new TemporaryStore ( temp , true ) ; }
|
If the store must be unique here is it .
|
2,914
|
@ SuppressWarnings ( "unchecked" ) private < T > Class < T > loadClassIfVisible ( String className , ClassLoader classLoader ) { try { Class < T > klass = ( Class < T > ) classLoader . loadClass ( className ) ; return klass ; } catch ( ClassNotFoundException e ) { return null ; } }
|
Loads a class with the given name from the given class loader .
|
2,915
|
public static InputStream prepareInputStream ( final URL url , final boolean acceptAnyCertificate ) throws IOException { final URLConnection conn = url . openConnection ( ) ; prepareForAuthentication ( conn ) ; prepareHttpHeaders ( conn ) ; if ( acceptAnyCertificate ) { prepareForSSL ( conn ) ; } return conn . getInputStream ( ) ; }
|
Prepare url for authentication and ssl if necessary and returns the input stream from the url .
|
2,916
|
public static void validateNotEmpty ( String stringToCheck , String argumentName ) throws NullArgumentException { validateNotEmpty ( stringToCheck , false , argumentName ) ; }
|
Validates that the string is not null and not an empty string without trimming the string .
|
2,917
|
public static void validateNotEmpty ( String stringToCheck , boolean trim , String argumentName ) throws NullArgumentException { validateNotNull ( stringToCheck , argumentName ) ; if ( stringToCheck . length ( ) == 0 || ( trim && stringToCheck . trim ( ) . length ( ) == 0 ) ) { throw new NullArgumentException ( argumentName + IS_EMPTY ) ; } }
|
Validates that the string is not null and not an empty string .
|
2,918
|
public static void validateNotEmpty ( Properties propertiesToCheck , String argumentName ) throws NullArgumentException { validateNotNull ( propertiesToCheck , argumentName ) ; if ( propertiesToCheck . isEmpty ( ) ) { throw new NullArgumentException ( argumentName + IS_EMPTY ) ; } }
|
Validates that the Properties instance is not null and that it has entries .
|
2,919
|
public static void validateNotEmpty ( Object [ ] arrayToCheck , String argumentName ) throws NullArgumentException { validateNotNull ( arrayToCheck , argumentName ) ; if ( arrayToCheck . length == 0 ) { throw new NullArgumentException ( argumentName + IS_EMPTY ) ; } }
|
Validates that the array instance is not null and that it has entries .
|
2,920
|
public static void validateNotEmptyContent ( String [ ] arrayToCheck , String argumentName ) throws NullArgumentException { validateNotEmptyContent ( arrayToCheck , false , argumentName ) ; }
|
Validates that the string array instance is not null and that it has entries that are not null or empty eithout trimming the string .
|
2,921
|
public static void validateNotEmptyContent ( String [ ] arrayToCheck , boolean trim , String argumentName ) throws NullArgumentException { validateNotEmpty ( arrayToCheck , argumentName ) ; for ( int i = 0 ; i < arrayToCheck . length ; i ++ ) { validateNotEmpty ( arrayToCheck [ i ] , arrayToCheck [ i ] + "[" + i + "]" ) ; if ( trim ) { validateNotEmpty ( arrayToCheck [ i ] . trim ( ) , arrayToCheck [ i ] + "[" + i + "]" ) ; } } }
|
Validates that the string array instance is not null and that it has entries that are not null or empty .
|
2,922
|
@ SuppressWarnings ( "unchecked" ) public < T > T get ( final String propertyName ) { return ( T ) m_properties . get ( propertyName ) ; }
|
Returns the property by name .
|
2,923
|
protected Map < String , ZipEntry > getEntries ( ZipFile zf ) { Enumeration < ? > e = zf . entries ( ) ; Map < String , ZipEntry > m = new HashMap < String , ZipEntry > ( ) ; while ( e . hasMoreElements ( ) ) { ZipEntry ze = ( ZipEntry ) e . nextElement ( ) ; m . put ( ze . getName ( ) , ze ) ; } return m ; }
|
Get all the entries in a ZIP file .
|
2,924
|
protected static void printHelp ( ) { System . out . println ( ) ; System . out . println ( "Usage: java " + ZipExploder . class . getName ( ) + " (-jar jarFilename... | -zip zipFilename...)... -dir destDir {-verbose}" ) ; System . out . println ( "Where:" ) ; System . out . println ( " jarFilename path to source jar, may repeat" ) ; System . out . println ( " zipFilename path to source zip, may repeat" ) ; System . out . println ( " destDir path to target directory; should exist" ) ; System . out . println ( "Note: one -jar or -zip is required; switch case or order is not important" ) ; }
|
Print command help text .
|
2,925
|
public static void main ( final String [ ] args ) { if ( args . length == 0 ) { printHelp ( ) ; System . exit ( 0 ) ; } List < String > zipNames = new ArrayList < String > ( ) ; List < String > jarNames = new ArrayList < String > ( ) ; String destDir = null ; boolean jarActive = false , zipActive = false , destDirActive = false ; boolean verbose = false ; for ( int i = 0 ; i < args . length ; i ++ ) { String arg = args [ i ] ; if ( arg . charAt ( 0 ) == '-' ) { arg = arg . substring ( 1 ) ; if ( arg . equalsIgnoreCase ( "jar" ) ) { jarActive = true ; zipActive = false ; destDirActive = false ; } else if ( arg . equalsIgnoreCase ( "zip" ) ) { zipActive = true ; jarActive = false ; destDirActive = false ; } else if ( arg . equalsIgnoreCase ( "dir" ) ) { jarActive = false ; zipActive = false ; destDirActive = true ; } else if ( arg . equalsIgnoreCase ( "verbose" ) ) { verbose = true ; } else { reportError ( "Invalid switch - " + arg ) ; } } else { if ( jarActive ) { jarNames . add ( arg ) ; } else if ( zipActive ) { zipNames . add ( arg ) ; } else if ( destDirActive ) { if ( destDir != null ) { reportError ( "duplicate argument - " + "-destDir" ) ; } destDir = arg ; } else { reportError ( "Too many parameters - " + arg ) ; } } } if ( destDir == null || ( zipNames . size ( ) + jarNames . size ( ) ) == 0 ) { reportError ( "Missing parameters" ) ; } if ( verbose ) { System . out . println ( "Effective command: " + ZipExploder . class . getName ( ) + " " + ( jarNames . size ( ) > 0 ? "-jars " + jarNames + " " : "" ) + ( zipNames . size ( ) > 0 ? "-zips " + zipNames + " " : "" ) + "-dir " + destDir ) ; } try { ZipExploder ze = new ZipExploder ( verbose ) ; ze . process ( FileUtils . pathNamesToFiles ( zipNames . toArray ( new String [ zipNames . size ( ) ] ) ) , FileUtils . pathNamesToFiles ( jarNames . toArray ( new String [ jarNames . size ( ) ] ) ) , new File ( destDir ) ) ; } catch ( IOException ioe ) { System . err . println ( "Exception - " + ioe . getMessage ( ) ) ; ioe . printStackTrace ( ) ; System . exit ( 2 ) ; } }
|
Main command line entry point .
|
2,926
|
public String getMessage ( ) { String base = super . getMessage ( ) ; if ( null == base ) { return "Failed to access " + m_variable + " environment variable" ; } return "Failed to access " + m_variable + " environment variable - " + base ; }
|
Prepends variable name to the base message .
|
2,927
|
public void notifyUpdate ( URL resource , int expected , int count ) { if ( m_first ) { m_expected = expected ; m_start = System . currentTimeMillis ( ) ; m_first = false ; } int completed = ( count * 100 ) / expected ; m_out . print ( resource . toExternalForm ( ) + " : " + completed + "% \r" ) ; }
|
Notify the monitor of the update in the download status .
|
2,928
|
public void notifyCompletion ( URL resource ) { long now = System . currentTimeMillis ( ) ; long time = now - m_start ; int kBps = ( int ) ( m_expected / time ) ; m_out . println ( resource . toExternalForm ( ) + " : " + kBps + " kBps. " ) ; }
|
Notify the monitor of the successful completion of a download process .
|
2,929
|
private static void processToken ( String token , Stack < String > stack , Properties props ) { if ( "}" . equals ( token ) ) { String name = stack . pop ( ) ; String open = stack . pop ( ) ; if ( "${" . equals ( open ) ) { startProperty ( name , props , stack ) ; } else { push ( stack , "${" + name + "}" ) ; } } else { if ( "$" . equals ( token ) ) { stack . push ( "$" ) ; } else { push ( stack , token ) ; } } }
|
Process one token .
|
2,930
|
private static void startProperty ( String name , Properties props , Stack < String > stack ) { String propValue = System . getProperty ( name ) ; if ( propValue == null ) { propValue = props . getProperty ( name ) ; } if ( propValue == null ) { push ( stack , "${" + name + "}" ) ; } else { push ( stack , propValue ) ; } }
|
Starts a new property .
|
2,931
|
private static void push ( Stack < String > stack , String value ) { if ( stack . size ( ) > 0 ) { String data = stack . pop ( ) ; if ( "${" . equals ( data ) ) { stack . push ( data ) ; stack . push ( value ) ; } else { stack . push ( data + value ) ; } } else { stack . push ( value ) ; } }
|
Pushes a value on a stack
|
2,932
|
public void notifyUpdate ( URL resource , int expected , int count ) { synchronized ( m_Monitors ) { for ( StreamMonitor monitor : m_Monitors ) { monitor . notifyUpdate ( resource , expected , count ) ; } } }
|
Notify all subscribing monitors of a updated event .
|
2,933
|
public void notifyCompletion ( URL resource ) { synchronized ( m_Monitors ) { for ( StreamMonitor monitor : m_Monitors ) { monitor . notifyCompletion ( resource ) ; } } }
|
Notify all subscribing monitors of a download completion event .
|
2,934
|
private static void closeStreams ( InputStream src , OutputStream dest ) { try { src . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } try { dest . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }
|
Closes the streams and reports Exceptions to System . err
|
2,935
|
public static boolean compareStreams ( InputStream in1 , InputStream in2 ) throws IOException { boolean moreOnIn1 ; do { int v1 = in1 . read ( ) ; int v2 = in2 . read ( ) ; if ( v1 != v2 ) { return false ; } moreOnIn1 = v1 != - 1 ; } while ( moreOnIn1 ) ; boolean noMoreOnIn2Either = in2 . read ( ) == - 1 ; return noMoreOnIn2Either ; }
|
Compares if two streams are identical in their contents .
|
2,936
|
public static void copyReaderToWriter ( Reader input , Writer output , boolean close ) throws IOException { try { BufferedReader in = bufferInput ( input ) ; BufferedWriter out = bufferOutput ( output ) ; int ch = in . read ( ) ; while ( ch != - 1 ) { out . write ( ch ) ; ch = in . read ( ) ; } out . flush ( ) ; out . close ( ) ; } finally { if ( close ) { input . close ( ) ; output . close ( ) ; } } }
|
Copies the Reader to the Writer .
|
2,937
|
private static BufferedWriter bufferOutput ( Writer writer ) { BufferedWriter out ; if ( writer instanceof BufferedWriter ) { out = ( BufferedWriter ) writer ; } else { out = new BufferedWriter ( writer ) ; } return out ; }
|
Wraps the Writer in a BufferedWriter unless it already is a BufferedWriter .
|
2,938
|
private static BufferedReader bufferInput ( Reader reader ) { BufferedReader in ; if ( reader instanceof BufferedReader ) { in = ( BufferedReader ) reader ; } else { in = new BufferedReader ( reader ) ; } return in ; }
|
Wraps the Reader in a BufferedReaderm unless it already is a BufferedReader .
|
2,939
|
public static void copyStreamToWriter ( InputStream in , Writer out , String encoding , boolean close ) throws IOException { InputStreamReader reader = new InputStreamReader ( in , encoding ) ; copyReaderToWriter ( reader , out , close ) ; }
|
Copies an InputStream to a Writer .
|
2,940
|
public static void copyReaderToStream ( Reader in , OutputStream out , String encoding , boolean close ) throws IOException { OutputStreamWriter writer = new OutputStreamWriter ( out , encoding ) ; copyReaderToWriter ( in , writer , close ) ; }
|
Copies the content of the Reader to the provided OutputStream using the provided encoding .
|
2,941
|
public PKSigningInformation loadSigningInformationFromPKCS12AndIntermediateCertificate ( InputStream keyStoreInputStream , String keyStorePassword , InputStream appleWWDRCAFileInputStream ) throws IOException , CertificateException { KeyStore pkcs12KeyStore = loadPKCS12File ( keyStoreInputStream , keyStorePassword ) ; X509Certificate appleWWDRCACert = loadDERCertificate ( appleWWDRCAFileInputStream ) ; return loadSigningInformation ( pkcs12KeyStore , keyStorePassword , appleWWDRCACert ) ; }
|
Load all signing information necessary for pass generation using two input streams for the key store and the Apple WWDRCA certificate .
|
2,942
|
public KeyStore loadPKCS12File ( InputStream inputStreamOfP12 , String password ) throws CertificateException , IOException { try { return CertUtils . toKeyStore ( inputStreamOfP12 , password . toCharArray ( ) ) ; } catch ( IllegalStateException ex ) { throw new IOException ( "Key from the input stream could not be decrypted" , ex ) ; } }
|
Load the keystore from an already opened input stream .
|
2,943
|
public X509Certificate loadDERCertificate ( String filePath ) throws IOException , CertificateException { try ( InputStream certificateInputStream = CertUtils . toInputStream ( filePath ) ) { return loadDERCertificate ( certificateInputStream ) ; } }
|
Load certificate file in DER format from the filesystem or the classpath
|
2,944
|
public void visitClassContext ( ClassContext classContext ) { try { stack = new OpcodeStack ( ) ; suspectLocals = new HashMap < > ( ) ; classVersion = classContext . getJavaClass ( ) . getMajor ( ) ; super . visitClassContext ( classContext ) ; } finally { stack = null ; suspectLocals = null ; } }
|
implements the visitor to create and clear the stack and suspectLocals
|
2,945
|
public void visitMethod ( Method obj ) { suspectLocals . clear ( ) ; int [ ] parmRegs = RegisterUtils . getParameterRegisters ( obj ) ; for ( int pr : parmRegs ) { suspectLocals . put ( Integer . valueOf ( pr ) , new RegisterInfo ( RegisterUtils . getLocalVariableEndRange ( obj . getLocalVariableTable ( ) , pr , 0 ) ) ) ; } }
|
implements the visitor to collect parameter registers
|
2,946
|
public void visitCode ( Code obj ) { forLoops = new HashSet < > ( ) ; super . visitCode ( obj ) ; forLoops = null ; }
|
implements the visitor to clear the forLoops set
|
2,947
|
public void sawOpcode ( int seen ) { if ( ! forLoops . isEmpty ( ) ) { Iterator < FloatForLoop > ffl = forLoops . iterator ( ) ; while ( ffl . hasNext ( ) ) { if ( ! ffl . next ( ) . sawOpcode ( seen ) ) { ffl . remove ( ) ; } } } if ( OpcodeUtils . isFLoad ( seen ) || OpcodeUtils . isDLoad ( seen ) ) { forLoops . add ( new FloatForLoop ( RegisterUtils . getLoadReg ( this , seen ) , getPC ( ) ) ) ; } }
|
implements the visitor to find for loops using floating point indexes
|
2,948
|
public void visitField ( Field obj ) { String fieldSig = obj . getSignature ( ) ; if ( "Ljavax/swing/JLabel;" . equals ( fieldSig ) ) { FieldAnnotation fa = FieldAnnotation . fromVisitedField ( this ) ; fieldLabels . add ( XFactory . createXField ( fa ) ) ; } }
|
looks for fields that are JLabels and stores them in a set
|
2,949
|
private void processFaultyGuiStrings ( ) { FQMethod methodInfo = new FQMethod ( getClassConstantOperand ( ) , getNameConstantOperand ( ) , getSigConstantOperand ( ) ) ; Integer parmIndex = displayTextMethods . get ( methodInfo ) ; if ( ( parmIndex != null ) && ( stack . getStackDepth ( ) > parmIndex . intValue ( ) ) ) { OpcodeStack . Item item = stack . getStackItem ( parmIndex . intValue ( ) ) ; if ( item . getConstant ( ) != null ) { bugReporter . reportBug ( new BugInstance ( this , BugType . S508C_NON_TRANSLATABLE_STRING . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } else if ( S508UserValue . APPENDED_STRING == item . getUserValue ( ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . S508C_APPENDED_STRING . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } } }
|
looks for calls to set a readable string that is generated from a static constant as these strings are not translatable . also looks for setting readable strings that are appended together . This is likely not to be internationalizable .
|
2,950
|
private void processNullLayouts ( String className , String methodName ) { if ( "java/awt/Container" . equals ( className ) && "setLayout" . equals ( methodName ) && ( stack . getStackDepth ( ) > 0 ) && stack . getStackItem ( 0 ) . isNull ( ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . S508C_NULL_LAYOUT . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } }
|
looks for containers where a null layout is installed
|
2,951
|
private void processSetColorOps ( String methodName ) throws ClassNotFoundException { if ( "setBackground" . equals ( methodName ) || "setForeground" . equals ( methodName ) ) { int argCount = SignatureUtils . getNumParameters ( getSigConstantOperand ( ) ) ; if ( stack . getStackDepth ( ) > argCount ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; if ( S508UserValue . FROM_UIMANAGER != item . getUserValue ( ) ) { item = stack . getStackItem ( argCount ) ; JavaClass cls = item . getJavaClass ( ) ; if ( ( ( jcomponentClass != null ) && cls . instanceOf ( jcomponentClass ) ) || ( ( componentClass != null ) && cls . instanceOf ( componentClass ) ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . S508C_SET_COMP_COLOR . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } } } } }
|
looks for calls to set the color of components where the color isn t from UIManager
|
2,952
|
private void processSetSizeOps ( String methodName ) throws ClassNotFoundException { if ( "setSize" . equals ( methodName ) ) { int argCount = SignatureUtils . getNumParameters ( getSigConstantOperand ( ) ) ; if ( ( windowClass != null ) && ( stack . getStackDepth ( ) > argCount ) ) { OpcodeStack . Item item = stack . getStackItem ( argCount ) ; JavaClass cls = item . getJavaClass ( ) ; if ( ( cls != null ) && cls . instanceOf ( windowClass ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . S508C_NO_SETSIZE . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } } } }
|
looks for calls to setSize on components rather than letting the layout manager set them
|
2,953
|
public static int getAStoreReg ( final DismantleBytecode dbc , final int seen ) { if ( seen == Const . ASTORE ) { return dbc . getRegisterOperand ( ) ; } if ( OpcodeUtils . isAStore ( seen ) ) { return seen - Const . ASTORE_0 ; } return - 1 ; }
|
returns the register used to store a reference
|
2,954
|
public static int getALoadReg ( DismantleBytecode dbc , int seen ) { if ( seen == Const . ALOAD ) { return dbc . getRegisterOperand ( ) ; } if ( OpcodeUtils . isALoad ( seen ) ) { return seen - Const . ALOAD_0 ; } return - 1 ; }
|
returns the register used to load a reference
|
2,955
|
public static int getStoreReg ( DismantleBytecode dbc , int seen ) { if ( ( seen == Const . ASTORE ) || ( seen == Const . ISTORE ) || ( seen == Const . LSTORE ) || ( seen == Const . FSTORE ) || ( seen == Const . DSTORE ) ) { return dbc . getRegisterOperand ( ) ; } if ( OpcodeUtils . isIStore ( seen ) ) { return seen - Const . ISTORE_0 ; } else if ( OpcodeUtils . isLStore ( seen ) ) { return seen - Const . LSTORE_0 ; } else if ( OpcodeUtils . isFStore ( seen ) ) { return seen - Const . FSTORE_0 ; } else if ( OpcodeUtils . isDStore ( seen ) ) { return seen - Const . DSTORE_0 ; } else if ( OpcodeUtils . isAStore ( seen ) ) { return seen - Const . ASTORE_0 ; } return - 1 ; }
|
returns the register used in a store operation
|
2,956
|
public static int getLoadReg ( DismantleBytecode dbc , int seen ) { if ( ( seen == Const . ALOAD ) || ( seen == Const . ILOAD ) || ( seen == Const . LLOAD ) || ( seen == Const . FLOAD ) || ( seen == Const . DLOAD ) ) { return dbc . getRegisterOperand ( ) ; } if ( OpcodeUtils . isILoad ( seen ) ) { return seen - Const . ILOAD_0 ; } else if ( OpcodeUtils . isLLoad ( seen ) ) { return seen - Const . LLOAD_0 ; } else if ( OpcodeUtils . isFLoad ( seen ) ) { return seen - Const . FLOAD_0 ; } else if ( OpcodeUtils . isDLoad ( seen ) ) { return seen - Const . DLOAD_0 ; } else if ( OpcodeUtils . isALoad ( seen ) ) { return seen - Const . ALOAD_0 ; } return - 1 ; }
|
returns the register used in a load operation
|
2,957
|
public static int getLocalVariableEndRange ( LocalVariableTable lvt , int reg , int curPC ) { int endRange = Integer . MAX_VALUE ; if ( lvt != null ) { LocalVariable lv = lvt . getLocalVariable ( reg , curPC ) ; if ( lv != null ) { endRange = lv . getStartPC ( ) + lv . getLength ( ) ; } } return endRange ; }
|
returns the end pc of the visible range of this register at this pc
|
2,958
|
public static int [ ] getParameterRegisters ( Method obj ) { Type [ ] argTypes = obj . getArgumentTypes ( ) ; int [ ] regs = new int [ argTypes . length ] ; int curReg = obj . isStatic ( ) ? 0 : 1 ; for ( int t = 0 ; t < argTypes . length ; t ++ ) { String sig = argTypes [ t ] . getSignature ( ) ; regs [ t ] = curReg ; curReg += SignatureUtils . getSignatureSize ( sig ) ; } return regs ; }
|
gets the set of registers used for parameters
|
2,959
|
public void visitCode ( Code obj ) { if ( ! Values . STATIC_INITIALIZER . equals ( getMethodName ( ) ) ) { state = State . SEEN_NOTHING ; super . visitCode ( obj ) ; } }
|
implements the visitor by forwarding calls for methods that are the static initializer
|
2,960
|
public void sawOpcode ( int seen ) { int index ; switch ( state ) { case SEEN_NOTHING : if ( seen == Const . BIPUSH ) { arraySize = getIntConstant ( ) ; if ( arraySize > 0 ) { state = State . SEEN_ARRAY_SIZE ; } } else if ( ( seen >= Const . ICONST_M1 ) && ( seen <= Const . ICONST_5 ) ) { arraySize = seen - Const . ICONST_M1 - 1 ; if ( arraySize > 0 ) { state = State . SEEN_ARRAY_SIZE ; } } break ; case SEEN_ARRAY_SIZE : if ( ( seen == Const . ANEWARRAY ) || ( seen == Const . NEWARRAY ) ) { state = State . SEEN_NEWARRAY ; storeCount = 0 ; } else { state = State . SEEN_NOTHING ; } break ; case SEEN_NEWARRAY : if ( seen == Const . DUP ) { state = State . SEEN_DUP ; } else { state = State . SEEN_NOTHING ; } break ; case SEEN_DUP : if ( seen == Const . BIPUSH ) { index = getIntConstant ( ) ; } else if ( ( seen >= Const . ICONST_M1 ) && ( seen <= Const . ICONST_5 ) ) { index = seen - Const . ICONST_M1 - 1 ; } else { state = State . SEEN_NOTHING ; return ; } if ( index != storeCount ) { state = State . SEEN_NOTHING ; } else { state = State . SEEN_INDEX ; } break ; case SEEN_INDEX : if ( ( seen == Const . LDC ) || ( seen == Const . LDC_W ) ) { state = State . SEEN_LDC ; } else { state = State . SEEN_NOTHING ; } break ; case SEEN_LDC : if ( ( seen >= Const . IASTORE ) && ( seen <= Const . SASTORE ) ) { if ( ( ++ storeCount ) == arraySize ) { state = State . SEEN_INDEX_STORE ; } else { state = State . SEEN_NEWARRAY ; } } break ; case SEEN_INDEX_STORE : if ( OpcodeUtils . isAStore ( seen ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . SACM_STATIC_ARRAY_CREATED_IN_METHOD . name ( ) , ( arraySize < 3 ) ? LOW_PRIORITY : ( ( arraySize < 10 ) ? NORMAL_PRIORITY : HIGH_PRIORITY ) ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this , getPC ( ) ) ) ; } state = State . SEEN_NOTHING ; break ; } }
|
implements the visitor to look for creation of local arrays using constant values
|
2,961
|
public void visitClassContext ( ClassContext classContext ) { try { JavaClass cls = classContext . getJavaClass ( ) ; if ( ( serializableClass != null ) && ( cls . implementationOf ( serializableClass ) ) ) { Field [ ] fields = cls . getFields ( ) ; setupVisitorForClass ( cls ) ; for ( Field f : fields ) { if ( ! f . isStatic ( ) && f . isFinal ( ) && f . isTransient ( ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . NFF_NON_FUNCTIONAL_FIELD . name ( ) , Priorities . NORMAL_PRIORITY ) . addClass ( this ) . addField ( cls . getClassName ( ) , f . getName ( ) , f . getSignature ( ) , f . getAccessFlags ( ) ) ) ; } } } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } }
|
checks to see if the class is Serializable then looks for fields that are both final and transient
|
2,962
|
public void visitCode ( Code obj ) { Method m = getMethod ( ) ; stack . resetForMethodEntry ( this ) ; initializedRegs . clear ( ) ; modifyRegs . clear ( ) ; Type [ ] argTypes = m . getArgumentTypes ( ) ; int arg = m . isStatic ( ) ? 0 : 1 ; for ( Type argType : argTypes ) { String argSig = argType . getSignature ( ) ; initializedRegs . set ( arg ) ; arg += SignatureUtils . getSignatureSize ( argSig ) ; } nullStoreToLocation . clear ( ) ; super . visitCode ( obj ) ; for ( Integer pc : nullStoreToLocation . values ( ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . AIOB_ARRAY_STORE_TO_NULL_REFERENCE . name ( ) , HIGH_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this , pc . intValue ( ) ) ) ; } }
|
overrides the visitor to collect parameter registers
|
2,963
|
public void visitClassContext ( ClassContext classContext ) { try { int majorVersion = classContext . getJavaClass ( ) . getMajor ( ) ; if ( majorVersion >= Const . MAJOR_1_4 ) { fbInfo = new ArrayList < > ( ) ; super . visitClassContext ( classContext ) ; } } finally { fbInfo = null ; } }
|
overrides the visitor to check for java class version being as good or better than 1 . 4
|
2,964
|
public void visitCode ( Code obj ) { fbInfo . clear ( ) ; loadedReg = - 1 ; CodeException [ ] exc = obj . getExceptionTable ( ) ; if ( exc != null ) { for ( CodeException ce : exc ) { if ( ( ce . getCatchType ( ) == 0 ) && ( ce . getStartPC ( ) == ce . getHandlerPC ( ) ) ) { fbInfo . add ( new FinallyBlockInfo ( ce . getStartPC ( ) ) ) ; } } } if ( ! fbInfo . isEmpty ( ) ) { try { super . visitCode ( obj ) ; } catch ( StopOpcodeParsingException e ) { } } }
|
overrides the visitor to collect finally block info .
|
2,965
|
private static Method findMethod ( JavaClass cls , String name , String sig ) { Method [ ] methods = cls . getMethods ( ) ; for ( Method m : methods ) { if ( m . getName ( ) . equals ( name ) && m . getSignature ( ) . equals ( sig ) ) { return m ; } } return null ; }
|
finds the method in specified class by name and signature
|
2,966
|
public boolean prescreen ( Method method ) { if ( Values . STATIC_INITIALIZER . equals ( method . getName ( ) ) ) { return false ; } BitSet bytecodeSet = getClassContext ( ) . getBytecodeSet ( method ) ; return ( bytecodeSet != null ) && ( bytecodeSet . get ( Const . ATHROW ) ) ; }
|
looks for methods that contain a ATHROW opcodes ignoring static initializers
|
2,967
|
public void visitCode ( Code obj ) { Method method = getMethod ( ) ; if ( ! method . isSynthetic ( ) && prescreen ( method ) ) { stack . resetForMethodEntry ( this ) ; super . visitCode ( obj ) ; } }
|
overrides the visitor to prescreen the method to look for throws calls and only forward onto bytecode scanning if there
|
2,968
|
public void sawOpcode ( int seen ) { boolean allConstantStrings = false ; boolean sawConstant = false ; try { stack . precomputation ( this ) ; if ( seen == Const . ATHROW ) { checkForWEM ( ) ; } else if ( ( seen == Const . LDC ) || ( seen == Const . LDC_W ) ) { if ( getConstantRefOperand ( ) instanceof ConstantString ) { sawConstant = true ; } } else if ( ( seen == Const . INVOKESPECIAL ) && Values . CONSTRUCTOR . equals ( getNameConstantOperand ( ) ) ) { String clsName = getClassConstantOperand ( ) ; if ( clsName . indexOf ( "Exception" ) < 0 ) { return ; } JavaClass exCls = Repository . lookupClass ( clsName ) ; if ( ! exCls . instanceOf ( exceptionClass ) ) { return ; } String sig = getSigConstantOperand ( ) ; List < String > argTypes = SignatureUtils . getParameterSignatures ( sig ) ; int stringParms = 0 ; for ( int t = 0 ; t < argTypes . size ( ) ; t ++ ) { if ( ! Values . SIG_JAVA_LANG_STRING . equals ( argTypes . get ( t ) ) ) { continue ; } stringParms ++ ; int stackOffset = argTypes . size ( ) - t - 1 ; if ( ( stack . getStackDepth ( ) > stackOffset ) && ( stack . getStackItem ( stackOffset ) . getUserValue ( ) == null ) ) { return ; } } if ( Values . SLASHED_JAVA_LANG_EXCEPTION . equals ( clsName ) && SignatureBuilder . SIG_THROWABLE_TO_VOID . equals ( getSigConstantOperand ( ) ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . WEM_OBSCURING_EXCEPTION . name ( ) , LOW_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) ) ; } allConstantStrings = stringParms > 0 ; } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } finally { TernaryPatcher . pre ( stack , seen ) ; stack . sawOpcode ( this , seen ) ; TernaryPatcher . post ( stack , seen ) ; if ( ( sawConstant || allConstantStrings ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; item . setUserValue ( Boolean . TRUE ) ; } } }
|
overrides the visitor to look for throws instructions using exceptions with static messages
|
2,969
|
public static void main ( final String [ ] args ) { JOptionPane . showMessageDialog ( null , "To use fb-contrib, copy this jar file into your local SpotBugs plugin directory, and use SpotBugs as usual.\n\nfb-contrib is a trademark of MeBigFatGuy.com" , "fb-contrib: copyright 2005-2019" , JOptionPane . INFORMATION_MESSAGE ) ; System . exit ( 0 ) ; }
|
shows the simple help
|
2,970
|
public void visitClassContext ( ClassContext classContext ) { try { JavaClass cls = classContext . getJavaClass ( ) ; for ( CompareSpec entry : compareClasses ) { if ( cls . implementationOf ( entry . getCompareClass ( ) ) ) { methodInfo = entry . getMethodInfo ( ) ; stack = new OpcodeStack ( ) ; super . visitClassContext ( classContext ) ; break ; } } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } finally { methodInfo = null ; stack = null ; } }
|
implements the visitor to actually iterate twice over this class once for compareTo and once for compare .
|
2,971
|
public void visitCode ( Code obj ) { if ( getMethod ( ) . isSynthetic ( ) ) { return ; } String methodName = getMethodName ( ) ; String methodSig = getMethodSig ( ) ; if ( methodName . equals ( methodInfo . methodName ) && methodSig . endsWith ( methodInfo . signatureEnding ) && ( SignatureUtils . getNumParameters ( methodSig ) == methodInfo . argumentCount ) ) { stack . resetForMethodEntry ( this ) ; seenNegative = false ; seenPositive = false ; seenZero = false ; seenUnconditionalNonZero = false ; furthestBranchTarget = - 1 ; sawConstant = null ; try { super . visitCode ( obj ) ; if ( ! seenZero || seenUnconditionalNonZero || ( obj . getCode ( ) . length > 2 ) ) { boolean seenAll = seenNegative & seenPositive & seenZero ; if ( ! seenAll || seenUnconditionalNonZero ) { bugReporter . reportBug ( new BugInstance ( this , BugType . SCRV_SUSPICIOUS_COMPARATOR_RETURN_VALUES . name ( ) , seenAll ? LOW_PRIORITY : NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this , 0 ) ) ; } } } catch ( StopOpcodeParsingException e ) { } } }
|
implements the visitor to check to see what Const were returned from a comparator . If no Const were returned it can t determine anything however if only Const were returned it looks to see if negative positive and zero was returned . It also looks to see if a non zero value is returned unconditionally . While it is possible that later check is ok it usually means something is wrong .
|
2,972
|
public void sawOpcode ( int seen ) { try { stack . precomputation ( this ) ; switch ( seen ) { case Const . IRETURN : { processIntegerReturn ( ) ; } break ; case Const . GOTO : case Const . GOTO_W : { if ( stack . getStackDepth ( ) > 0 ) { throw new StopOpcodeParsingException ( ) ; } if ( furthestBranchTarget < getBranchTarget ( ) ) { furthestBranchTarget = getBranchTarget ( ) ; } } break ; case Const . IFEQ : case Const . IFNE : case Const . IFLT : case Const . IFGE : case Const . IFGT : case Const . IFLE : case Const . IF_ICMPEQ : case Const . IF_ICMPNE : case Const . IF_ICMPLT : case Const . IF_ICMPGE : case Const . IF_ICMPGT : case Const . IF_ICMPLE : case Const . IF_ACMPEQ : case Const . IF_ACMPNE : case Const . IFNULL : case Const . IFNONNULL : { if ( furthestBranchTarget < getBranchTarget ( ) ) { furthestBranchTarget = getBranchTarget ( ) ; } } break ; case Const . LOOKUPSWITCH : case Const . TABLESWITCH : { int defTarget = getDefaultSwitchOffset ( ) + getPC ( ) ; if ( furthestBranchTarget > defTarget ) { furthestBranchTarget = defTarget ; } } break ; case Const . ATHROW : { if ( stack . getStackDepth ( ) > 0 ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; String exSig = item . getSignature ( ) ; if ( "Ljava/lang/UnsupportedOperationException;" . equals ( exSig ) ) { throw new StopOpcodeParsingException ( ) ; } } } break ; case Const . ICONST_0 : if ( getNextOpcode ( ) == Const . IRETURN ) { sawConstant = Integer . valueOf ( 0 ) ; } break ; case Const . ICONST_M1 : if ( getNextOpcode ( ) == Const . IRETURN ) { sawConstant = Integer . valueOf ( - 1 ) ; } break ; case Const . ICONST_1 : if ( getNextOpcode ( ) == Const . IRETURN ) { sawConstant = Integer . valueOf ( 1 ) ; } break ; default : break ; } } finally { stack . sawOpcode ( this , seen ) ; } }
|
implements the visitor to look for returns of constant values and records them for being negative zero or positive . It also records unconditional returns of non zero values
|
2,973
|
public void visitCode ( final Code obj ) { stack . resetForMethodEntry ( this ) ; indexToFieldMap . clear ( ) ; super . visitCode ( obj ) ; }
|
implements the visitor to reset the opcode stack and the file maps
|
2,974
|
private int getIntOpRegister ( final int seen ) { if ( ( seen == Const . ISTORE ) || ( seen == Const . IINC ) ) { return getRegisterOperand ( ) ; } return seen - Const . ISTORE_0 ; }
|
fetch the register from a integer op code
|
2,975
|
public void visitClassContext ( ClassContext classContext ) { try { JavaClass cls = classContext . getJavaClass ( ) ; if ( cls . getMajor ( ) >= Const . MAJOR_1_5 ) { stack = new OpcodeStack ( ) ; checkedFields = new HashSet < > ( ) ; enumRegs = new HashMap < > ( ) ; enumFields = new HashMap < > ( ) ; super . visitClassContext ( classContext ) ; } } finally { stack = null ; checkedFields = null ; enumRegs = null ; enumFields = null ; } }
|
implements the visitor to check that the class is greater or equal than 1 . 5 and set and clear the stack
|
2,976
|
private boolean isEnum ( int stackPos ) throws ClassNotFoundException { if ( stack . getStackDepth ( ) <= stackPos ) { return false ; } OpcodeStack . Item item = stack . getStackItem ( stackPos ) ; if ( ! item . getSignature ( ) . startsWith ( Values . SIG_QUALIFIED_CLASS_PREFIX ) ) { return false ; } JavaClass cls = item . getJavaClass ( ) ; if ( ( cls == null ) || ! cls . isEnum ( ) ) { return false ; } return cls . getInterfaces ( ) . length == 0 ; }
|
returns whether the item at the stackPos location on the stack is an enum and doesn t implement any interfaces
|
2,977
|
private boolean couldBeEnumCollection ( int stackPos ) { if ( stack . getStackDepth ( ) <= stackPos ) { return false ; } OpcodeStack . Item item = stack . getStackItem ( stackPos ) ; CollectionType userValue = ( CollectionType ) item . getUserValue ( ) ; if ( userValue != null ) { return userValue == CollectionType . REGULAR ; } String realClass = item . getSignature ( ) ; return "Ljava/util/HashSet;" . equals ( realClass ) || "Ljava/util/HashMap;" . equals ( realClass ) ; }
|
returns whether the item at the stackpos location isn t an enum collection but could be
|
2,978
|
private boolean alreadyReported ( int stackPos ) { if ( stack . getStackDepth ( ) <= stackPos ) { return false ; } OpcodeStack . Item item = stack . getStackItem ( stackPos ) ; XField field = item . getXField ( ) ; if ( field == null ) { return false ; } String fieldName = field . getName ( ) ; return ! checkedFields . add ( fieldName ) ; }
|
returns whether the collection has already been reported on
|
2,979
|
public void visitCode ( Code obj ) { try { XMethod xMethod = getXMethod ( ) ; if ( xMethod != null ) { String [ ] tes = xMethod . getThrownExceptions ( ) ; Set < String > thrownExceptions = new HashSet < > ( Arrays . < String > asList ( ( tes == null ) ? new String [ 0 ] : tes ) ) ; blocks = new ArrayList < > ( ) ; inBlocks = new ArrayList < > ( ) ; transitionPoints = new BitSet ( ) ; CodeException [ ] ces = obj . getExceptionTable ( ) ; for ( CodeException ce : ces ) { TryBlock tb = new TryBlock ( ce ) ; int existingBlock = blocks . indexOf ( tb ) ; if ( existingBlock >= 0 ) { tb = blocks . get ( existingBlock ) ; tb . addCatchType ( ce ) ; } else { blocks . add ( tb ) ; } } Iterator < TryBlock > it = blocks . iterator ( ) ; while ( it . hasNext ( ) ) { TryBlock block = it . next ( ) ; if ( block . hasMultipleHandlers ( ) || block . isFinally ( ) || block . catchIsThrown ( getConstantPool ( ) , thrownExceptions ) ) { it . remove ( ) ; } } if ( blocks . size ( ) > 1 ) { stack . resetForMethodEntry ( this ) ; super . visitCode ( obj ) ; if ( blocks . size ( ) > 1 ) { TryBlock firstBlock = blocks . get ( 0 ) ; for ( int i = 1 ; i < blocks . size ( ) ; i ++ ) { TryBlock secondBlock = blocks . get ( i ) ; if ( ! blocksSplitAcrossTransitions ( firstBlock , secondBlock ) && ( firstBlock . getCatchType ( ) == secondBlock . getCatchType ( ) ) && firstBlock . getThrowSignature ( ) . equals ( secondBlock . getThrowSignature ( ) ) && firstBlock . getMessage ( ) . equals ( secondBlock . getMessage ( ) ) && firstBlock . getExceptionSignature ( ) . equals ( secondBlock . getExceptionSignature ( ) ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . STB_STACKED_TRY_BLOCKS . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLineRange ( this , firstBlock . getStartPC ( ) , firstBlock . getEndHandlerPC ( ) ) . addSourceLineRange ( this , secondBlock . getStartPC ( ) , secondBlock . getEndHandlerPC ( ) ) ) ; } firstBlock = secondBlock ; } } } } } finally { blocks = null ; inBlocks = null ; transitionPoints = null ; } }
|
overrides the visitor to look for idea try catch blocks to find issues specifically method needs two or more try catch blocks that only catch one exception type .
|
2,980
|
private TryBlock findBlockWithStart ( int pc ) { for ( TryBlock block : blocks ) { if ( block . atStartPC ( pc ) ) { return block ; } } return null ; }
|
looks for an existing try block that has this pc as a start of the try
|
2,981
|
public void visit ( Method obj ) { state = State . SAW_NOTHING ; register1_1 = - 1 ; register1_2 = - 1 ; register2_1 = - 1 ; register2_2 = - 1 ; super . visit ( obj ) ; }
|
overrides the visitor to reset the registers
|
2,982
|
public void sawOpcode ( int seen ) { switch ( state ) { case SAW_NOTHING : if ( OpcodeUtils . isALoad ( seen ) ) { register1_1 = RegisterUtils . getALoadReg ( this , seen ) ; state = State . SAW_LOAD1_1 ; } break ; case SAW_LOAD1_1 : if ( OpcodeUtils . isALoad ( seen ) ) { register1_2 = RegisterUtils . getALoadReg ( this , seen ) ; } if ( register1_2 > - 1 ) { state = State . SAW_LOAD1_2 ; } else { state = State . SAW_NOTHING ; } break ; case SAW_LOAD1_2 : if ( seen == Const . INVOKEVIRTUAL ) { String cls = getDottedClassConstantOperand ( ) ; if ( dateClasses . contains ( cls ) ) { String methodName = getNameConstantOperand ( ) ; if ( "equals" . equals ( methodName ) || "after" . equals ( methodName ) || "before" . equals ( methodName ) ) { state = State . SAW_CMP1 ; } } } if ( state != State . SAW_CMP1 ) { state = State . SAW_NOTHING ; } break ; case SAW_CMP1 : if ( seen == Const . IFNE ) { state = State . SAW_IFNE ; } else { state = State . SAW_NOTHING ; } break ; case SAW_IFNE : if ( OpcodeUtils . isALoad ( seen ) ) { register2_1 = RegisterUtils . getALoadReg ( this , seen ) ; } if ( register2_1 > - 1 ) { state = State . SAW_LOAD2_1 ; } else { state = State . SAW_NOTHING ; } break ; case SAW_LOAD2_1 : if ( OpcodeUtils . isALoad ( seen ) ) { register2_2 = RegisterUtils . getALoadReg ( this , seen ) ; } if ( ( register2_2 > - 1 ) && ( ( ( register1_1 == register2_1 ) && ( register1_2 == register2_2 ) ) || ( ( register1_1 == register2_2 ) && ( register1_2 == register2_1 ) ) ) ) { state = State . SAW_LOAD2_2 ; } else { state = State . SAW_NOTHING ; } break ; case SAW_LOAD2_2 : if ( seen == Const . INVOKEVIRTUAL ) { String cls = getDottedClassConstantOperand ( ) ; if ( dateClasses . contains ( cls ) ) { String methodName = getNameConstantOperand ( ) ; if ( "equals" . equals ( methodName ) || "after" . equals ( methodName ) || "before" . equals ( methodName ) ) { state = State . SAW_CMP2 ; } } } if ( state != State . SAW_CMP2 ) { state = State . SAW_NOTHING ; } break ; case SAW_CMP2 : if ( seen == Const . IFEQ ) { bugReporter . reportBug ( new BugInstance ( "DDC_DOUBLE_DATE_COMPARISON" , NORMAL_PRIORITY ) . addClassAndMethod ( this ) . addSourceLine ( this ) ) ; } state = State . SAW_NOTHING ; break ; default : break ; } }
|
overrides the visitor to look for double date compares using the same registers
|
2,983
|
protected final int isLocalCollection ( OpcodeStack . Item item ) throws ClassNotFoundException { Comparable < ? > aliasReg = ( Comparable < ? > ) item . getUserValue ( ) ; if ( aliasReg instanceof Integer ) { return ( ( Integer ) aliasReg ) . intValue ( ) ; } int reg = item . getRegisterNumber ( ) ; if ( reg < 0 ) { return - 1 ; } JavaClass cls = item . getJavaClass ( ) ; if ( ( cls != null ) && cls . implementationOf ( collectionClass ) ) { return reg ; } return - 1 ; }
|
determines if the stack item refers to a collection that is stored in a local variable
|
2,984
|
public void visitClassContext ( ClassContext classContext ) { try { localizableFields = new HashMap < > ( ) ; visitedBlocks = new BitSet ( ) ; clsContext = classContext ; clsName = clsContext . getJavaClass ( ) . getClassName ( ) ; clsSig = SignatureUtils . classToSignature ( clsName ) ; JavaClass cls = classContext . getJavaClass ( ) ; Field [ ] fields = cls . getFields ( ) ; ConstantPool cp = classContext . getConstantPoolGen ( ) . getConstantPool ( ) ; for ( Field f : fields ) { if ( ! f . isStatic ( ) && ! f . isVolatile ( ) && ( f . getName ( ) . indexOf ( Values . SYNTHETIC_MEMBER_CHAR ) < 0 ) && f . isPrivate ( ) ) { FieldAnnotation fa = new FieldAnnotation ( cls . getClassName ( ) , f . getName ( ) , f . getSignature ( ) , false ) ; boolean hasExternalAnnotation = false ; for ( AnnotationEntry entry : f . getAnnotationEntries ( ) ) { ConstantUtf8 cutf = ( ConstantUtf8 ) cp . getConstant ( entry . getTypeIndex ( ) ) ; if ( ! cutf . getBytes ( ) . startsWith ( Values . JAVA ) ) { hasExternalAnnotation = true ; break ; } } localizableFields . put ( f . getName ( ) , new FieldInfo ( fa , hasExternalAnnotation ) ) ; } } if ( ! localizableFields . isEmpty ( ) ) { buildMethodFieldModifiers ( classContext ) ; super . visitClassContext ( classContext ) ; for ( FieldInfo fi : localizableFields . values ( ) ) { FieldAnnotation fa = fi . getFieldAnnotation ( ) ; SourceLineAnnotation sla = fi . getSrcLineAnnotation ( ) ; BugInstance bug = new BugInstance ( this , BugType . FCBL_FIELD_COULD_BE_LOCAL . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addField ( fa ) ; if ( sla != null ) { bug . addSourceLine ( sla ) ; } bugReporter . reportBug ( bug ) ; } } } finally { localizableFields = null ; visitedBlocks = null ; clsContext = null ; methodFieldModifiers = null ; } }
|
overrides the visitor to collect localizable fields and then report those that survive all method checks .
|
2,985
|
public void visitMethod ( Method obj ) { if ( localizableFields . isEmpty ( ) ) { return ; } try { cfg = clsContext . getCFG ( obj ) ; cpg = cfg . getMethodGen ( ) . getConstantPool ( ) ; BasicBlock bb = cfg . getEntry ( ) ; Set < String > uncheckedFields = new HashSet < > ( localizableFields . keySet ( ) ) ; visitedBlocks . clear ( ) ; checkBlock ( bb , uncheckedFields ) ; } catch ( CFGBuilderException cbe ) { localizableFields . clear ( ) ; } finally { cfg = null ; cpg = null ; } }
|
overrides the visitor to navigate basic blocks looking for all first usages of fields removing those that are read from first .
|
2,986
|
private boolean prescreen ( Method method ) { BitSet bytecodeSet = getClassContext ( ) . getBytecodeSet ( method ) ; return ( bytecodeSet != null ) && ( bytecodeSet . get ( Const . PUTFIELD ) || bytecodeSet . get ( Const . GETFIELD ) ) ; }
|
looks for methods that contain a GETFIELD or PUTFIELD opcodes
|
2,987
|
public void sawOpcode ( int seen ) { if ( ( seen == Const . GETFIELD ) || ( seen == Const . PUTFIELD ) ) { String fieldName = getNameConstantOperand ( ) ; FieldInfo fi = localizableFields . get ( fieldName ) ; if ( fi != null ) { SourceLineAnnotation sla = SourceLineAnnotation . fromVisitedInstruction ( this ) ; fi . setSrcLineAnnotation ( sla ) ; } } }
|
implements the visitor to add SourceLineAnnotations for fields in constructors and static initializers .
|
2,988
|
private void buildMethodFieldModifiers ( ClassContext classContext ) { FieldModifier fm = new FieldModifier ( ) ; fm . visitClassContext ( classContext ) ; methodFieldModifiers = fm . getMethodFieldModifiers ( ) ; }
|
builds up the method to field map of what method write to which fields this is one recursively so that if method A calls method B and method B writes to field C then A modifies F .
|
2,989
|
public void visitClassContext ( ClassContext classContext ) { if ( mapInterface != null ) { this . clsContext = classContext ; classContext . getJavaClass ( ) . accept ( this ) ; } }
|
overrides the visitor to make sure that the static initializer was able to load the map class
|
2,990
|
public void visitField ( Field obj ) { if ( checkConfusedName ( obj . getName ( ) , obj . getSignature ( ) ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . CNC_COLLECTION_NAMING_CONFUSION . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addField ( this ) . addString ( obj . getName ( ) ) ) ; } }
|
overrides the visitor to look for fields where the name has Map Set List in it but the type of that field isn t that .
|
2,991
|
public void visitMethod ( Method obj ) { LocalVariableTable lvt = obj . getLocalVariableTable ( ) ; if ( lvt != null ) { LocalVariable [ ] lvs = lvt . getLocalVariableTable ( ) ; for ( LocalVariable lv : lvs ) { if ( checkConfusedName ( lv . getName ( ) , lv . getSignature ( ) ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . CNC_COLLECTION_NAMING_CONFUSION . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addString ( lv . getName ( ) ) . addSourceLine ( this . clsContext , this , lv . getStartPC ( ) ) ) ; } } } }
|
overrides the visitor to look for local variables where the name has Map Set List in it but the type of that field isn t that . note that this only is useful if compiled with debug labels .
|
2,992
|
@ edu . umd . cs . findbugs . annotations . SuppressFBWarnings ( value = "EXS_EXCEPTION_SOFTENING_RETURN_FALSE" , justification = "No other simple way to determine whether class exists" ) private boolean checkConfusedName ( String methodOrVariableName , String signature ) { try { String name = methodOrVariableName . toLowerCase ( Locale . ENGLISH ) ; if ( ( name . endsWith ( "map" ) || ( name . endsWith ( "set" ) && ! name . endsWith ( "toset" ) ) || name . endsWith ( "list" ) || name . endsWith ( "queue" ) ) && signature . startsWith ( "Ljava/util/" ) ) { String clsName = SignatureUtils . stripSignature ( signature ) ; JavaClass cls = Repository . lookupClass ( clsName ) ; if ( ( cls . implementationOf ( mapInterface ) && ! name . endsWith ( "map" ) ) || ( cls . implementationOf ( setInterface ) && ! name . endsWith ( "set" ) ) || ( ( cls . implementationOf ( listInterface ) || cls . implementationOf ( queueInterface ) ) && ! name . endsWith ( "list" ) && ! name . endsWith ( "queue" ) ) ) { return true ; } } } catch ( ClassNotFoundException cnfe ) { bugReporter . reportMissingClass ( cnfe ) ; } return false ; }
|
looks for a name that mentions a collection type but the wrong type for the variable
|
2,993
|
public void sawOpcode ( int seen ) { Units unit = null ; try { stack . precomputation ( this ) ; switch ( seen ) { case Const . INVOKEVIRTUAL : case Const . INVOKEINTERFACE : case Const . INVOKESTATIC : unit = processInvoke ( ) ; break ; case Const . GETSTATIC : String clsName = getClassConstantOperand ( ) ; if ( "java/util/concurrent/TimeUnit" . equals ( clsName ) || "edu/emory/matchcs/backport/java/util/concurrent/TimeUnit" . equals ( clsName ) ) { unit = TIMEUNIT_TO_UNITS . get ( getNameConstantOperand ( ) ) ; } break ; case Const . L2I : case Const . I2L : if ( stack . getStackDepth ( ) > 0 ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; unit = ( Units ) item . getUserValue ( ) ; } break ; case Const . IADD : case Const . ISUB : case Const . IMUL : case Const . IDIV : case Const . IREM : case Const . LADD : case Const . LSUB : case Const . LMUL : case Const . LDIV : case Const . LREM : processArithmetic ( ) ; break ; default : break ; } } finally { stack . sawOpcode ( this , seen ) ; if ( ( unit != null ) && ( stack . getStackDepth ( ) > 0 ) ) { OpcodeStack . Item item = stack . getStackItem ( 0 ) ; item . setUserValue ( unit ) ; } } }
|
overrides the visitor to look for operations on two time unit values that are conflicting
|
2,994
|
@ SuppressWarnings ( "PMD.CompareObjectsWithEquals" ) private void processArithmetic ( ) { if ( stack . getStackDepth ( ) > 1 ) { OpcodeStack . Item arg1 = stack . getStackItem ( 0 ) ; OpcodeStack . Item arg2 = stack . getStackItem ( 1 ) ; Units u1 = ( Units ) arg1 . getUserValue ( ) ; Units u2 = ( Units ) arg2 . getUserValue ( ) ; if ( ( u1 != null ) && ( u2 != null ) && ( u1 != u2 ) ) { bugReporter . reportBug ( new BugInstance ( this , BugType . CTU_CONFLICTING_TIME_UNITS . name ( ) , NORMAL_PRIORITY ) . addClass ( this ) . addMethod ( this ) . addSourceLine ( this ) . addString ( u1 . toString ( ) ) . addString ( u2 . toString ( ) ) ) ; } } }
|
false positive ; we re comparing enums
|
2,995
|
public void visitClassContext ( ClassContext classContext ) { try { if ( ( throwableClass != null ) && ! isPre14Class ( classContext . getJavaClass ( ) ) ) { stack = new OpcodeStack ( ) ; catchInfos = new HashSet < > ( ) ; exReg = new HashMap < > ( ) ; super . visitClassContext ( classContext ) ; } } finally { stack = null ; catchInfos = null ; exceptions = null ; exReg = null ; } }
|
implements the visitor to make sure the jdk is 1 . 4 or better
|
2,996
|
public boolean prescreen ( Code code , Method method ) { if ( method . isSynthetic ( ) ) { return false ; } CodeException [ ] ce = code . getExceptionTable ( ) ; if ( CollectionUtils . isEmpty ( ce ) ) { return false ; } BitSet bytecodeSet = getClassContext ( ) . getBytecodeSet ( method ) ; return ( bytecodeSet != null ) && bytecodeSet . get ( Const . ATHROW ) ; }
|
looks for methods that contain a catch block and an ATHROW opcode
|
2,997
|
public void visitCode ( Code obj ) { if ( prescreen ( obj , getMethod ( ) ) ) { stack . resetForMethodEntry ( this ) ; catchInfos . clear ( ) ; exceptions = collectExceptions ( obj . getExceptionTable ( ) ) ; exReg . clear ( ) ; lastWasExitPoint = false ; super . visitCode ( obj ) ; } }
|
implements the visitor to filter out methods that don t throw exceptions
|
2,998
|
public CodeException [ ] collectExceptions ( CodeException ... exs ) { List < CodeException > filteredEx = new ArrayList < > ( ) ; for ( CodeException ce : exs ) { if ( ( ce . getCatchType ( ) != 0 ) && ( ce . getStartPC ( ) < ce . getEndPC ( ) ) && ( ce . getEndPC ( ) <= ce . getHandlerPC ( ) ) ) { filteredEx . add ( ce ) ; } } return filteredEx . toArray ( new CodeException [ 0 ] ) ; }
|
collects all the valid exception objects ( ones where start and finish are before the target
|
2,999
|
public boolean isPossibleExBuilder ( int excReg ) throws ClassNotFoundException { String sig = getSigConstantOperand ( ) ; String returnSig = SignatureUtils . getReturnSignature ( sig ) ; if ( returnSig . startsWith ( Values . SIG_QUALIFIED_CLASS_PREFIX ) ) { returnSig = SignatureUtils . trimSignature ( returnSig ) ; JavaClass retCls = Repository . lookupClass ( returnSig ) ; if ( retCls . instanceOf ( throwableClass ) ) { int numParms = SignatureUtils . getNumParameters ( sig ) ; if ( stack . getStackDepth ( ) >= numParms ) { for ( int p = 0 ; p < numParms ; p ++ ) { OpcodeStack . Item item = stack . getStackItem ( p ) ; if ( item . getRegisterNumber ( ) == excReg ) { return true ; } } } } } return false ; }
|
returns whether the method called might be a method that builds an exception using the original exception . It does so by looking to see if the method returns an exception and if one of the parameters is the original exception
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.