instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void shouldBeAbleToOpenTxAfterPreviousIsClosed() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( true );
sess.beginTransaction().close();
// When
Transaction tx = sess.beginTransaction();
// Then we should've gotten a transaction object back
assertNotNull( tx );
} | #vulnerable code
@Test
public void shouldBeAbleToOpenTxAfterPreviousIsClosed() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( true );
InternalSession sess = new InternalSession( mock );
sess.beginTransaction().close();
// When
Transaction tx = sess.beginTransaction();
// Then we should've gotten a transaction object back
assertNotNull( tx );
}
#location 11
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
void assertExpectedReadQueryDistribution( Context context )
{
Map<String,Long> readQueriesByServer = context.getReadQueriesByServer();
ClusterAddresses clusterAddresses = fetchClusterAddresses( driver );
// expect all followers to serve more than zero read queries
assertAllAddressesServedReadQueries( "Follower", clusterAddresses.followers, readQueriesByServer );
// expect all read replicas to serve more than zero read queries
assertAllAddressesServedReadQueries( "Read replica", clusterAddresses.readReplicas, readQueriesByServer );
// expect all followers to serve same order of magnitude read queries
assertAllAddressesServedSimilarAmountOfReadQueries( "Followers", clusterAddresses.followers,
readQueriesByServer, clusterAddresses );
// expect all read replicas to serve same order of magnitude read queries
assertAllAddressesServedSimilarAmountOfReadQueries( "Read replicas", clusterAddresses.readReplicas,
readQueriesByServer, clusterAddresses );
} | #vulnerable code
@Override
void assertExpectedReadQueryDistribution( Context context )
{
Map<String,Long> readQueriesByServer = context.getReadQueriesByServer();
ClusterAddresses clusterAddresses = fetchClusterAddresses( driver );
// before 3.2.0 only read replicas serve reads
ServerVersion version = ServerVersion.version( driver );
boolean readsOnFollowersEnabled = READ_ON_FOLLOWERS_BY_DEFAULT.availableIn( version );
if ( readsOnFollowersEnabled )
{
// expect all followers to serve more than zero read queries
assertAllAddressesServedReadQueries( "Follower", clusterAddresses.followers, readQueriesByServer );
}
// expect all read replicas to serve more than zero read queries
assertAllAddressesServedReadQueries( "Read replica", clusterAddresses.readReplicas, readQueriesByServer );
if ( readsOnFollowersEnabled )
{
// expect all followers to serve same order of magnitude read queries
assertAllAddressesServedSimilarAmountOfReadQueries( "Followers", clusterAddresses.followers,
readQueriesByServer, clusterAddresses );
}
// expect all read replicas to serve same order of magnitude read queries
assertAllAddressesServedSimilarAmountOfReadQueries( "Read replicas", clusterAddresses.readReplicas,
readQueriesByServer, clusterAddresses );
}
#location 9
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void shouldNotPutBackPurgedConnection() throws IOException, InterruptedException, StubServer.ForceKilled
{
// Given
StubServer server = StubServer.start( resource( "not_reuse_connection.script" ), 9001 );
//START servers
StubServer readServer = StubServer.start( resource( "empty.script" ), 9002 );
StubServer writeServer1 = StubServer.start( resource( "dead_server.script" ), 9003 );
StubServer writeServer2 = StubServer.start( resource( "empty.script" ), 9006 );
URI uri = URI.create( "bolt+routing://127.0.0.1:9001" );
RoutingDriver driver = (RoutingDriver) GraphDatabase.driver( uri, config );
//Open both a read and a write session
Session readSession = driver.session( AccessMode.READ );
Session writeSession = driver.session( AccessMode.WRITE );
try
{
writeSession.run( "MATCH (n) RETURN n.name" );
writeSession.close();
fail();
}
catch (SessionExpiredException e)
{
//ignore
}
//We now lost all write servers
assertThat(driver.writeServers(), hasSize( 0 ));
//reacquiring will trow out the current read server at 9002
writeSession = driver.session( AccessMode.WRITE );
assertThat(driver.routingServers(), contains(address( 9004 )));
assertThat(driver.readServers(), contains(address( 9005 )));
assertThat(driver.writeServers(), contains(address( 9006 )));
assertFalse(driver.connectionPool().hasAddress(address( 9002 ) ));
// now we close the read session and the connection should not be put
// back to the pool
Connection connection = ((RoutingNetworkSession) readSession).connection;
assertTrue( connection.isOpen() );
readSession.close();
assertFalse( connection.isOpen() );
assertFalse(driver.connectionPool().hasAddress(address( 9002 ) ));
writeSession.close();
driver.close();
// Finally
assertThat( server.exitStatus(), equalTo( 0 ) );
assertThat( readServer.exitStatus(), equalTo( 0 ) );
assertThat( writeServer1.exitStatus(), equalTo( 0 ) );
assertThat( writeServer2.exitStatus(), equalTo( 0 ) );
} | #vulnerable code
@Test
public void shouldNotPutBackPurgedConnection() throws IOException, InterruptedException, StubServer.ForceKilled
{
// Given
StubServer server = StubServer.start( resource( "not_reuse_connection.script" ), 9001 );
//START servers
StubServer readServer = StubServer.start( resource( "empty.script" ), 9002 );
StubServer writeServer1 = StubServer.start( resource( "dead_server.script" ), 9003 );
StubServer writeServer2 = StubServer.start( resource( "empty.script" ), 9006 );
URI uri = URI.create( "bolt+routing://127.0.0.1:9001" );
RoutingDriver driver = (RoutingDriver) GraphDatabase.driver( uri, config );
//Open both a read and a write session
Session readSession = driver.session( AccessMode.READ );
Session writeSession = driver.session( AccessMode.WRITE );
try
{
writeSession.run( "MATCH (n) RETURN n.name" );
writeSession.close();
fail();
}
catch (SessionExpiredException e)
{
//ignore
}
//We now lost all write servers
assertThat(driver.writeServers(), hasSize( 0 ));
//reacquiring will trow out the current read server at 9002
writeSession = driver.session( AccessMode.WRITE );
assertThat(driver.routingServers(), contains(address( 9004 )));
assertThat(driver.readServers(), contains(address( 9005 )));
assertThat(driver.writeServers(), contains(address( 9006 )));
assertFalse(driver.connectionPool().hasAddress(address( 9002 ) ));
// now we close the read session and the connection should not be put
// back to the pool
Connection connection = ((ClusteredNetworkSession) readSession).connection;
assertTrue( connection.isOpen() );
readSession.close();
assertFalse( connection.isOpen() );
assertFalse(driver.connectionPool().hasAddress(address( 9002 ) ));
writeSession.close();
driver.close();
// Finally
assertThat( server.exitStatus(), equalTo( 0 ) );
assertThat( readServer.exitStatus(), equalTo( 0 ) );
assertThat( writeServer1.exitStatus(), equalTo( 0 ) );
assertThat( writeServer2.exitStatus(), equalTo( 0 ) );
}
#location 26
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static Driver driver( URI uri, AuthToken authToken, Config config )
{
// Make sure we have some configuration to play with
config = config == null ? Config.defaultConfig() : config;
return new DriverFactory().newInstance( uri, authToken, config.routingSettings(), config );
} | #vulnerable code
public static Driver driver( URI uri, AuthToken authToken, Config config )
{
// Break down the URI into its constituent parts
String scheme = uri.getScheme();
BoltServerAddress address = BoltServerAddress.from( uri );
// Make sure we have some configuration to play with
if ( config == null )
{
config = Config.defaultConfig();
}
// Construct security plan
SecurityPlan securityPlan;
try
{
securityPlan = createSecurityPlan( address, config );
}
catch ( GeneralSecurityException | IOException ex )
{
throw new ClientException( "Unable to establish SSL parameters", ex );
}
ConnectionPool connectionPool = createConnectionPool( authToken, securityPlan, config );
switch ( scheme.toLowerCase() )
{
case "bolt":
return new DirectDriver( address, connectionPool, securityPlan, config.logging() );
case "bolt+routing":
return new RoutingDriver(
config.routingSettings(),
address,
connectionPool,
securityPlan,
Clock.SYSTEM,
config.logging() );
default:
throw new ClientException( format( "Unsupported URI scheme: %s", scheme ) );
}
}
#location 37
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void shouldNotAllowNewTxWhileOneIsRunning() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( true );
sess.beginTransaction();
// Expect
exception.expect( ClientException.class );
// When
sess.beginTransaction();
} | #vulnerable code
@Test
public void shouldNotAllowNewTxWhileOneIsRunning() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( true );
InternalSession sess = new InternalSession( mock );
sess.beginTransaction();
// Expect
exception.expect( ClientException.class );
// When
sess.beginTransaction();
}
#location 15
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void loadX509Cert( File certFile, KeyStore keyStore ) throws GeneralSecurityException, IOException
{
try ( BufferedInputStream inputStream = new BufferedInputStream( new FileInputStream( certFile ) ) )
{
CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" );
int certCount = 0; // The file might contain multiple certs
while ( inputStream.available() > 0 )
{
try
{
Certificate cert = certFactory.generateCertificate( inputStream );
certCount++;
loadX509Cert( cert, "neo4j.javadriver.trustedcert." + certCount, keyStore );
}
catch ( CertificateException e )
{
if ( e.getCause() != null && e.getCause().getMessage().equals( "Empty input" ) )
{
// This happens if there is whitespace at the end of the certificate - we load one cert, and then try and load a
// second cert, at which point we fail
return;
}
throw new IOException( "Failed to load certificate from `" + certFile.getAbsolutePath() + "`: " + certCount + " : " + e.getMessage(), e );
}
}
}
} | #vulnerable code
public static void loadX509Cert( File certFile, KeyStore keyStore ) throws GeneralSecurityException, IOException
{
BufferedInputStream inputStream = new BufferedInputStream( new FileInputStream( certFile ) );
CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" );
int certCount = 0; // The file might contain multiple certs
while ( inputStream.available() > 0 )
{
try
{
Certificate cert = certFactory.generateCertificate( inputStream );
certCount++;
loadX509Cert( cert, "neo4j.javadriver.trustedcert." + certCount, keyStore );
}
catch ( CertificateException e )
{
if ( e.getCause() != null && e.getCause().getMessage().equals( "Empty input" ) )
{
// This happens if there is whitespace at the end of the certificate - we load one cert, and then try and load a
// second cert, at which point we fail
return;
}
throw new IOException( "Failed to load certificate from `" + certFile.getAbsolutePath() + "`: " + certCount + " : " + e.getMessage(), e );
}
}
}
#location 14
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void loadX509Cert( File certFile, KeyStore keyStore ) throws GeneralSecurityException, IOException
{
try ( BufferedInputStream inputStream = new BufferedInputStream( new FileInputStream( certFile ) ) )
{
CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" );
int certCount = 0; // The file might contain multiple certs
while ( inputStream.available() > 0 )
{
try
{
Certificate cert = certFactory.generateCertificate( inputStream );
certCount++;
loadX509Cert( cert, "neo4j.javadriver.trustedcert." + certCount, keyStore );
}
catch ( CertificateException e )
{
if ( e.getCause() != null && e.getCause().getMessage().equals( "Empty input" ) )
{
// This happens if there is whitespace at the end of the certificate - we load one cert, and then try and load a
// second cert, at which point we fail
return;
}
throw new IOException( "Failed to load certificate from `" + certFile.getAbsolutePath() + "`: " + certCount + " : " + e.getMessage(), e );
}
}
}
} | #vulnerable code
public static void loadX509Cert( File certFile, KeyStore keyStore ) throws GeneralSecurityException, IOException
{
BufferedInputStream inputStream = new BufferedInputStream( new FileInputStream( certFile ) );
CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" );
int certCount = 0; // The file might contain multiple certs
while ( inputStream.available() > 0 )
{
try
{
Certificate cert = certFactory.generateCertificate( inputStream );
certCount++;
loadX509Cert( cert, "neo4j.javadriver.trustedcert." + certCount, keyStore );
}
catch ( CertificateException e )
{
if ( e.getCause() != null && e.getCause().getMessage().equals( "Empty input" ) )
{
// This happens if there is whitespace at the end of the certificate - we load one cert, and then try and load a
// second cert, at which point we fail
return;
}
throw new IOException( "Failed to load certificate from `" + certFile.getAbsolutePath() + "`: " + certCount + " : " + e.getMessage(), e );
}
}
}
#location 14
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
@SuppressWarnings( "unchecked" )
public void connectSendsInit()
{
String userAgent = "agentSmith";
ConnectionSettings settings = new ConnectionSettings( basicAuthToken(), userAgent );
RecordingSocketConnector connector = new RecordingSocketConnector( settings );
connector.connect( LOCAL_DEFAULT );
assertEquals( 1, connector.createConnections.size() );
Connection connection = connector.createConnections.get( 0 );
verify( connection ).init( eq( userAgent ), any( Map.class ) );
} | #vulnerable code
@Test
@SuppressWarnings( "unchecked" )
public void connectSendsInit()
{
String userAgent = "agentSmith";
ConnectionSettings settings = new ConnectionSettings( basicAuthToken(), userAgent );
TestSocketConnector connector = new TestSocketConnector( settings, insecure(), loggingMock() );
connector.connect( LOCAL_DEFAULT );
assertEquals( 1, connector.createConnections.size() );
Connection connection = connector.createConnections.get( 0 );
verify( connection ).init( eq( userAgent ), any( Map.class ) );
}
#location 9
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void saveX509Cert( String certStr, File certFile ) throws IOException
{
try ( BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) ) )
{
writer.write( BEGIN_CERT );
writer.newLine();
writer.write( certStr );
writer.newLine();
writer.write( END_CERT );
writer.newLine();
}
} | #vulnerable code
public static void saveX509Cert( String certStr, File certFile ) throws IOException
{
BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) );
writer.write( BEGIN_CERT );
writer.newLine();
writer.write( certStr );
writer.newLine();
writer.write( END_CERT );
writer.newLine();
writer.close();
}
#location 15
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static String read(File file) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String ret = new String(new byte[0], "UTF-8");
String line;
while ((line = in.readLine()) != null) {
ret += line;
}
in.close();
return ret;
} | #vulnerable code
public static String read(File file) throws IOException {
// BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
InputStream inStream = new FileInputStream(file);
BufferedReader in = new BufferedReader(inputStreamToReader(inStream));
StringBuilder ret = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
ret.append(line);
}
in.close();
return ret.toString();
}
#location 4
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static String read(File file) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String ret = new String(new byte[0], "UTF-8");
String line;
while ((line = in.readLine()) != null) {
ret += line;
}
in.close();
return ret;
} | #vulnerable code
public static String read(File file) throws IOException {
// BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
InputStream inStream = new FileInputStream(file);
BufferedReader in = new BufferedReader(inputStreamToReader(inStream));
StringBuilder ret = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
ret.append(line);
}
in.close();
return ret.toString();
}
#location 13
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String[] args) {
System.out.println("********** Running Sikulix.main");
int dl = RunTime.checkArgs(args);
if (dl > -1) {
testNumber = dl;
}
if (RunTime.testing) {
rt = RunTime.get();
testNumber = rt.getOptionNumber("testing.test", -1);
}
if (testNumber > -1) {
rt = RunTime.get();
if (!rt.testing) {
rt.show();
rt.testing = true;
Debug.on(3);
}
Tests.runTest(testNumber);
System.exit(1);
} else {
rt = RunTime.get();
Debug.on(3);
File workDir = new File(rt.fSxProject, "Setup/target/Setup");
boolean success = addFromProject("Setup", "Setup/sikulixapi.jar");
rt.extractResourcesToFolderFromJar("sikulixapi.jar", "META-INF/libs/tessdata", new File(workDir,"stuff"), null);
rt.terminate(1,"");
if (rt.runningWinApp) {
popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName());
try {
Screen scr = new Screen();
scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3);
} catch (Exception ex) {
popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName());
}
popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName());
}
System.out.println("nothing to do (yet)");
}
} | #vulnerable code
public static void main(String[] args) {
System.out.println("********** Running Sikulix.main");
int dl = RunTime.checkArgs(args);
if (dl > -1) {
testNumber = dl;
}
if (RunTime.testing) {
rt = RunTime.get();
testNumber = rt.getOptionNumber("testing.test", -1);
}
if (testNumber > -1) {
rt = RunTime.get();
if (!rt.testing) {
rt.show();
rt.testing = true;
Debug.on(3);
}
Tests.runTest(testNumber);
System.exit(1);
} else {
rt = RunTime.get();
if (rt.runningWinApp) {
popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName());
try {
Screen scr = new Screen();
scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3);
} catch (Exception ex) {
popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName());
}
popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName());
}
System.out.println("nothing to do (yet)");
}
}
#location 30
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String[] args) {
String[] splashArgs = new String[]{
"splash", "#", "#" + Settings.SikuliVersionIDE, "", "#", "#... starting - please wait ..."};
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log(lvl, "final cleanup");
if (isRunning != null) {
try {
isRunningFile.close();
} catch (IOException ex) {
}
isRunning.delete();
}
FileManager.cleanTemp();
}
});
if (System.getProperty("sikuli.FromCommandLine") == null) {
String[] userOptions = collectOptions("IDE", args);
if (userOptions == null) {
System.exit(0);
}
if (userOptions.length > 0) {
for (String e : userOptions) {
log(lvl, "arg: " + e);
}
args = userOptions;
}
}
start = (new Date()).getTime();
ScriptRunner.initScriptingSupport();
IDESupport.initIDESupport();
CommandArgs cmdArgs = new CommandArgs("IDE");
cmdLine = cmdArgs.getCommandLine(CommandArgs.scanArgs(args));
if (cmdLine == null) {
Debug.error("Did not find any valid option on command line!");
System.exit(1);
}
if (cmdLine.hasOption("h")) {
cmdArgs.printHelp();
System.exit(0);
}
if (cmdLine.hasOption("c")) {
System.setProperty("sikuli.console", "false");
}
if (cmdLine.hasOption(CommandArgsEnum.LOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.LOGFILE.longname());
if (!Debug.setLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.USERLOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.USERLOGFILE.longname());
if (!Debug.setUserLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.DEBUG.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.DEBUG.longname());
if (cmdValue == null) {
Debug.setDebugLevel(3);
Debug.setLogFile("");
Settings.LogTime = true;
} else {
Debug.setDebugLevel(cmdValue);
}
}
if (cmdLine.hasOption(CommandArgsEnum.LOAD.shortname())) {
loadScripts = cmdLine.getOptionValues(CommandArgsEnum.LOAD.longname());
log(lvl, "requested to load: " + loadScripts);
if (loadScripts[0].endsWith(".skl")) {
log(lvl, "Switching to ScriptRunner to run " + loadScripts[0]);
ScriptRunner.runscript(args);
}
}
if (cmdLine.hasOption(CommandArgsEnum.RUN.shortname())
|| cmdLine.hasOption(CommandArgsEnum.TEST.shortname())
|| cmdLine.hasOption(CommandArgsEnum.INTERACTIVE.shortname())) {
log(lvl, "Switching to ScriptRunner with option -r, -t or -i");
ScriptRunner.runscript(args);
}
new File(Settings.BaseTempPath).mkdirs();
isRunning = new File(Settings.BaseTempPath, "sikuli-ide-isrunning");
try {
isRunning.createNewFile();
isRunningFile = new FileOutputStream(isRunning);
if (null == isRunningFile.getChannel().tryLock()) {
splashArgs[5] = "Terminating on FatalError: IDE already running";
splash = new SplashFrame(splashArgs);
log(-1, splashArgs[5]);
Sikulix.pause(3);
System.exit(1);
}
} catch (Exception ex) {
splashArgs[5] = "Terminating on FatalError: cannot access IDE lock ";
splash = new SplashFrame(splashArgs);
log(-1, splashArgs[5] + "\n" + isRunning.getAbsolutePath());
Sikulix.pause(3);
System.exit(1);
}
Settings.setArgs(cmdArgs.getUserArgs(), cmdArgs.getSikuliArgs());
Settings.showJavaInfo();
Settings.printArgs();
if (Settings.isMac()) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "SikuliX-u8zIDE");
}
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//TODO UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
log(-1, "Problem loading UIManager!\nError: %s", e.getMessage());
}
SikuliIDE.getInstance().initNativeSupport();
SikuliIDE.getInstance().initSikuliIDE(args);
} | #vulnerable code
public static void main(String[] args) {
String[] splashArgs = new String[]{
"splash", "#", "#" + Settings.SikuliVersionIDE, "", "#", "#... starting - please wait ..."};
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log(lvl, "final cleanup");
if (isRunning != null) {
try {
isRunningFile.close();
} catch (IOException ex) {
}
isRunning.delete();
}
FileManager.cleanTemp();
}
});
if (System.getProperty("sikuli.FromCommandLine") == null) {
String[] userOptions = collectOptions("IDE", args);
if (userOptions == null) {
System.exit(0);
}
if (userOptions.length > 0) {
for (String e : userOptions) {
log(lvl, "arg: " + e);
}
args = userOptions;
}
}
start = (new Date()).getTime();
ScriptRunner.initScriptingSupport();
IDESupport.initIDESupport();
CommandArgs cmdArgs = new CommandArgs("IDE");
cmdLine = cmdArgs.getCommandLine(CommandArgs.scanArgs(args));
if (cmdLine == null) {
Debug.error("Did not find any valid option on command line!");
System.exit(1);
}
if (cmdLine.hasOption("h")) {
cmdArgs.printHelp();
System.exit(0);
}
if (cmdLine.hasOption("c")) {
System.setProperty("sikuli.console", "false");
}
if (cmdLine.hasOption(CommandArgsEnum.LOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.LOGFILE.longname());
if (!Debug.setLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.USERLOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.USERLOGFILE.longname());
if (!Debug.setUserLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.DEBUG.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.DEBUG.longname());
if (cmdValue == null) {
Debug.setDebugLevel(3);
Debug.setLogFile("");
Settings.LogTime = true;
} else {
Debug.setDebugLevel(cmdValue);
}
}
if (cmdLine.hasOption(CommandArgsEnum.LOAD.shortname())) {
loadScripts = cmdLine.getOptionValues(CommandArgsEnum.LOAD.longname());
log(lvl, "requested to load: " + loadScripts);
if (loadScripts[0].endsWith(".skl")) {
log(lvl, "Switching to ScriptRunner to run " + loadScripts[0]);
ScriptRunner.runscript(args);
}
}
if (cmdLine.hasOption(CommandArgsEnum.RUN.shortname())
|| cmdLine.hasOption(CommandArgsEnum.TEST.shortname())
|| cmdLine.hasOption(CommandArgsEnum.INTERACTIVE.shortname())) {
log(lvl, "Switching to ScriptRunner with option -r, -t or -i");
ScriptRunner.runscript(args);
}
new File(Settings.BaseTempPath).mkdirs();
isRunning = new File(Settings.BaseTempPath, "sikuli-ide-isrunning");
try {
isRunning.createNewFile();
isRunningFile = new FileOutputStream(isRunning);
if (null == isRunningFile.getChannel().tryLock()) {
splashArgs[5] = "Terminating on FatalError: IDE already running";
splash = new SplashFrame(splashArgs);
log(-1, splashArgs[5]);
Sikulix.pause(3);
System.exit(1);
}
} catch (Exception ex) {
splashArgs[5] = "Terminating on FatalError: cannot access IDE lock ";
splash = new SplashFrame(splashArgs);
log(-1, splashArgs[5] + "\n" + isRunning.getAbsolutePath());
Sikulix.pause(3);
System.exit(1);
}
Settings.setArgs(cmdArgs.getUserArgs(), cmdArgs.getSikuliArgs());
Settings.showJavaInfo();
Settings.printArgs();
initNativeSupport();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
log(-1, "Problem loading UIManager!\nError: %s", e.getMessage());
}
if (nativeSupport != null) {
nativeSupport.initApp(Debug.getDebugLevel() > 2 ? true : false);
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
SikuliIDE.getInstance(args);
}
#location 85
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public <PSI> Iterator<Match> findAll(PSI target) throws FindFailed {
lastMatches = null;
Image img = null;
String targetStr = target.toString();
if (target instanceof String) {
targetStr = targetStr.trim();
}
while (true) {
try {
if (autoWaitTimeout > 0) {
RepeatableFindAll rf = new RepeatableFindAll(target);
rf.repeat(autoWaitTimeout);
lastMatches = rf.getMatches();
} else {
lastMatches = doFindAll(target, null);
}
} catch (Exception ex) {
if (ex instanceof IOException) {
if (handleImageMissing(img, false)) {
continue;
}
}
throw new FindFailed(ex.getMessage());
}
if (lastMatches != null) {
return lastMatches;
}
if (!handleFindFailed(img)) {
return null;
}
}
} | #vulnerable code
public <PSI> Iterator<Match> findAll(PSI target) throws FindFailed {
lastMatches = null;
Image img = null;
String targetStr = target.toString();
if (target instanceof String) {
targetStr = targetStr.trim();
}
while (true) {
try {
if (autoWaitTimeout > 0) {
RepeatableFindAll rf = new RepeatableFindAll(target);
rf.repeat(autoWaitTimeout);
lastMatches = rf.getMatches();
} else {
lastMatches = doFindAll(target, null);
}
} catch (Exception ex) {
if (ex instanceof IOException) {
if (handleImageMissing(img)) {
continue;
}
}
throw new FindFailed(ex.getMessage());
}
if (lastMatches != null) {
return lastMatches;
}
if (!handleFindFailed(img)) {
return null;
}
}
}
#location 28
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static boolean unpackJar(String jarName, String folderName, boolean del) {
jarName = FileManager.slashify(jarName, false);
if (!jarName.endsWith(".jar")) {
jarName += ".jar";
}
if (!new File(jarName).isAbsolute()) {
log(-1, "unpackJar: jar path not absolute");
return false;
}
if (folderName == null) {
folderName = jarName.substring(0, jarName.length() - 4);
} else if (!new File(folderName).isAbsolute()) {
log(-1, "unpackJar: folder path not absolute");
return false;
}
folderName = FileManager.slashify(folderName, true);
ZipInputStream in;
BufferedOutputStream out;
try {
if (del) {
FileManager.deleteFileOrFolder(folderName);
}
in = new ZipInputStream(new BufferedInputStream(new FileInputStream(jarName)));
log0(lvl, "unpackJar: %s to %s", jarName, folderName);
boolean isExecutable;
int n;
File f;
for (ZipEntry z = in.getNextEntry(); z != null; z = in.getNextEntry()) {
if (z.isDirectory()) {
(new File(folderName, z.getName())).mkdirs();
} else {
n = z.getName().lastIndexOf(EXECUTABLE);
if (n >= 0) {
f = new File(folderName, z.getName().substring(0, n));
isExecutable = true;
} else {
f = new File(folderName, z.getName());
isExecutable = false;
}
f.getParentFile().mkdirs();
out = new BufferedOutputStream(new FileOutputStream(f));
bufferedWrite(in, out);
out.close();
if (isExecutable) {
f.setExecutable(true, false);
}
}
}
in.close();
} catch (Exception ex) {
log0(-1, "unpackJar: " + ex.getMessage());
return false;
}
log0(lvl, "unpackJar: completed");
return true;
} | #vulnerable code
public static boolean unpackJar(String jarName, String folderName, boolean del) {
ZipInputStream in = null;
BufferedOutputStream out = null;
try {
if (del) {
FileManager.deleteFileOrFolder(folderName);
}
in = new ZipInputStream(new BufferedInputStream(new FileInputStream(jarName)));
log0(lvl, "unpackJar: %s to %s", jarName, folderName);
boolean isExecutable;
int n;
File f;
for (ZipEntry z = in.getNextEntry(); z != null; z = in.getNextEntry()) {
if (z.isDirectory()) {
(new File(folderName, z.getName())).mkdirs();
} else {
n = z.getName().lastIndexOf(EXECUTABLE);
if (n >= 0) {
f = new File(folderName, z.getName().substring(0, n));
isExecutable = true;
} else {
f = new File(folderName, z.getName());
isExecutable = false;
}
f.getParentFile().mkdirs();
out = new BufferedOutputStream(new FileOutputStream(f));
bufferedWrite(in, out);
out.close();
if (isExecutable) {
f.setExecutable(true, false);
}
}
}
in.close();
} catch (Exception ex) {
log0(-1, "unpackJar: " + ex.getMessage());
return false;
}
log0(lvl, "unpackJar: completed");
return true;
}
#location 35
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private boolean checkPatterns(ScreenImage simg) {
log(lvl + 1, "update: checking patterns");
if (!observedRegion.isObserving()) {
return false;
}
Finder finder = null;
for (String name : eventStates.keySet()) {
if (!patternsToCheck()) {
continue;
}
if (eventStates.get(name) == State.REPEAT) {
if ((new Date()).getTime() < eventRepeatWaitTimes.get(name)) {
continue;
} else {
eventStates.put(name, State.UNKNOWN);
}
}
Object ptn = eventNames.get(name);
Image img = Image.getImageFromTarget(ptn);
if (img == null || !img.isUseable()) {
Debug.error("EventMgr: checkPatterns: Image not valid", ptn);
eventStates.put(name, State.MISSING);
continue;
}
Match match = null;
boolean hasMatch = false;
long lastSearchTime;
long now = 0;
if (!Settings.UseImageFinder && Settings.CheckLastSeen && null != img.getLastSeen()) {
Region r = Region.create(img.getLastSeen());
if (observedRegion.contains(r)) {
lastSearchTime = (new Date()).getTime();
Finder f = new Finder(new Screen().capture(r), r);
f.find(new Pattern(img).similar(Settings.CheckLastSeenSimilar));
if (f.hasNext()) {
log(lvl + 1, "checkLastSeen: still there");
match = new Match(new Region(img.getLastSeen()), img.getLastSeenScore());
match.setTimes(0, (new Date()).getTime() - lastSearchTime);
hasMatch = true;
} else {
log(lvl + 1, "checkLastSeen: not there");
}
}
}
if (match == null) {
if (finder == null) {
if (Settings.UseImageFinder) {
finder = new ImageFinder(observedRegion);
((ImageFinder) finder).setIsMultiFinder();
} else {
finder = new Finder(simg, observedRegion);
}
}
lastSearchTime = (new Date()).getTime();
now = (new Date()).getTime();
finder.find(img);
if (finder.hasNext()) {
match = finder.next();
match.setTimes(0, now - lastSearchTime);
if (match.getScore() >= getSimiliarity(ptn)) {
hasMatch = true;
img.setLastSeen(match.getRect(), match.getScore());
}
}
}
if (hasMatch) {
eventMatches.put(name, match);
log(lvl + 1, "(%s): %s match: %s in:%s", eventTypes.get(name), ptn.toString(),
match.toStringShort(), observedRegion.toStringShort());
} else if (eventStates.get(ptn) == State.FIRST) {
log(lvl + 1, "(%s): %s match: %s in:%s", eventTypes.get(name), ptn.toString(),
match.toStringShort(), observedRegion.toStringShort());
eventStates.put(name, State.UNKNOWN);
}
if (eventStates.get(name) != State.HAPPENED) {
if (hasMatch && eventTypes.get(name) == ObserveEvent.Type.VANISH) {
eventMatches.put(name, match);
}
if ((hasMatch && eventTypes.get(name) == ObserveEvent.Type.APPEAR)
|| (!hasMatch && eventTypes.get(name) == ObserveEvent.Type.VANISH)) {
eventStates.put(name, State.HAPPENED);
eventCounts.put(name, eventCounts.get(name) + 1);
callEventObserver(name, eventMatches.get(name), now);
if (shouldStopOnFirstEvent) {
observedRegion.stopObserver();
}
}
}
if (!observedRegion.isObserving()) {
return false;
}
}
return patternsToCheck();
} | #vulnerable code
private boolean checkPatterns(ScreenImage simg) {
log(lvl + 1, "update: checking patterns");
if (!observedRegion.isObserving()) {
return false;
}
Finder finder = null;
for (String name : eventStates.keySet()) {
if (!patternsToCheck()) {
continue;
}
if (eventStates.get(name) == State.REPEAT) {
if ((new Date()).getTime() < eventRepeatWaitTimes.get(name)) {
continue;
} else {
eventStates.put(name, State.UNKNOWN);
}
}
Object ptn = eventNames.get(name);
Image img = Image.createFromObject(ptn);
if (!img.isUseable()) {
Debug.error("EventMgr: checkPatterns: Image not valid", ptn);
eventStates.put(name, State.MISSING);
continue;
}
Match match = null;
boolean hasMatch = false;
long lastSearchTime;
long now = 0;
if (!Settings.UseImageFinder && Settings.CheckLastSeen && null != img.getLastSeen()) {
Region r = Region.create(img.getLastSeen());
if (observedRegion.contains(r)) {
lastSearchTime = (new Date()).getTime();
Finder f = new Finder(new Screen().capture(r), r);
f.find(new Pattern(img).similar(Settings.CheckLastSeenSimilar));
if (f.hasNext()) {
log(lvl + 1, "checkLastSeen: still there");
match = new Match(new Region(img.getLastSeen()), img.getLastSeenScore());
match.setTimes(0, (new Date()).getTime() - lastSearchTime);
hasMatch = true;
} else {
log(lvl + 1, "checkLastSeen: not there");
}
}
}
if (match == null) {
if (finder == null) {
if (Settings.UseImageFinder) {
finder = new ImageFinder(observedRegion);
((ImageFinder) finder).setIsMultiFinder();
} else {
finder = new Finder(simg, observedRegion);
}
}
lastSearchTime = (new Date()).getTime();
now = (new Date()).getTime();
finder.find(img);
if (finder.hasNext()) {
match = finder.next();
match.setTimes(0, now - lastSearchTime);
if (match.getScore() >= getSimiliarity(ptn)) {
hasMatch = true;
img.setLastSeen(match.getRect(), match.getScore());
}
}
}
if (hasMatch) {
eventMatches.put(name, match);
log(lvl + 1, "(%s): %s match: %s in:%s", eventTypes.get(name), ptn.toString(),
match.toStringShort(), observedRegion.toStringShort());
} else if (eventStates.get(ptn) == State.FIRST) {
log(lvl + 1, "(%s): %s match: %s in:%s", eventTypes.get(name), ptn.toString(),
match.toStringShort(), observedRegion.toStringShort());
eventStates.put(name, State.UNKNOWN);
}
if (eventStates.get(name) != State.HAPPENED) {
if (hasMatch && eventTypes.get(name) == ObserveEvent.Type.VANISH) {
eventMatches.put(name, match);
}
if ((hasMatch && eventTypes.get(name) == ObserveEvent.Type.APPEAR)
|| (!hasMatch && eventTypes.get(name) == ObserveEvent.Type.VANISH)) {
eventStates.put(name, State.HAPPENED);
eventCounts.put(name, eventCounts.get(name) + 1);
callEventObserver(name, eventMatches.get(name), now);
if (shouldStopOnFirstEvent) {
observedRegion.stopObserver();
}
}
}
if (!observedRegion.isObserving()) {
return false;
}
}
return patternsToCheck();
}
#location 20
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String[] args) throws FindFailed {
System.out.println("********** Running Sikulix.main");
int dl = RunTime.checkArgs(args, RunTime.Type.API);
if (dl > -1 && dl < 999) {
testNumber = dl;
Debug.on(3);
} else {
testNumber = -1;
}
rt = RunTime.get();
testNumber = rt.getOptionNumber("testing.test", -1);
if (testNumber > -1) {
rt = RunTime.get();
if (!rt.testing) {
rt.show();
rt.testing = true;
}
Tests.runTest(testNumber);
System.exit(1);
} else {
rt = RunTime.get();
Debug.on(3);
Settings.InfoLogs = false;
Settings.ActionLogs = false;
URL uTest = null;
try {
imgLink = "http://download.sikuli.de/images";
String imgFolder = "download.sikuli.de/images";
imgHttp = "SikuliLogo.png";
ImagePath.addHTTP(imgFolder);
Image img = Image.create(imgHttp);
Screen scr = new Screen();
scr.find(img).highlight(2);
scr.find(img).highlight(2);
Image.dump();
} catch (Exception ex) {
log(-1, "%s", ex);
}
if (rt.runningWinApp) {
popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName());
try {
Screen scr = new Screen();
scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3);
} catch (Exception ex) {
popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName());
}
popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName());
System.exit(1);
}
rt.terminate(1,"Sikulix::main: nothing to test");
}
} | #vulnerable code
public static void main(String[] args) throws FindFailed {
System.out.println("********** Running Sikulix.main");
int dl = RunTime.checkArgs(args, RunTime.Type.API);
if (dl > -1 && dl < 999) {
testNumber = dl;
Debug.on(3);
} else {
testNumber = -1;
}
rt = RunTime.get();
testNumber = rt.getOptionNumber("testing.test", -1);
if (testNumber > -1) {
rt = RunTime.get();
if (!rt.testing) {
rt.show();
rt.testing = true;
}
Tests.runTest(testNumber);
System.exit(1);
} else {
rt = RunTime.get();
Debug.on(3);
Settings.InfoLogs = false;
Settings.ActionLogs = false;
URL uTest = null;
try {
imgLink = "http://download.sikuli.de/images";
imgHttp = "SikuliLogo.png";
uTest = new URL(imgLink);
URL uImage = FileManager.getURLForContentFromURL(uTest, imgHttp);
int retval;
boolean ok = false;
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) uImage.openConnection();
con.setInstanceFollowRedirects(false);
con.setRequestMethod("HEAD");
retval = con.getResponseCode();
ok = (retval == HttpURLConnection.HTTP_OK);
log(0, "URL: %s (%d)", uImage, retval);
} catch (Exception e) {
log(-1, "%s", e);
ok = false;
}
if (!ok) {
System.exit(1);
}
BufferedImage bImg = ImageIO.read(uImage);
if (bImg != null) {
Image img = new Image(bImg);
Screen scr = new Screen();
scr.find(img).highlight(2);
scr.find(img).highlight(2);
Image.dump();
}
} catch (Exception ex) {
log(-1, "%s", ex);
}
if (rt.runningWinApp) {
popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName());
try {
Screen scr = new Screen();
scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3);
} catch (Exception ex) {
popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName());
}
popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName());
System.exit(1);
}
rt.terminate(1,"Sikulix::main: nothing to test");
}
}
#location 43
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private <PSI> Match doFind(PSI ptn, RepeatableFind repeating) throws IOException {
Finder f = null;
Match m = null;
boolean findingText = false;
lastFindTime = (new Date()).getTime();
ScreenImage simg;
if (repeating != null && repeating._finder != null) {
simg = getScreen().capture(this);
f = repeating._finder;
f.setScreenImage(simg);
f.setRepeating();
lastSearchTime = (new Date()).getTime();
f.findRepeat();
} else {
Image img = null;
if (ptn instanceof String) {
if (((String) ptn).startsWith("\t") && ((String) ptn).endsWith("\t")) {
findingText = true;
} else {
img = Image.create((String) ptn);
if (img.isValid()) {
lastSearchTime = (new Date()).getTime();
f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), null);
if (!f.hasNext()) {
f.find(img);
}
} else if (img.isText()) {
findingText = true;
} else {
throw new IOException("Region: doFind: Image not loadable: " + ptn.toString());
}
}
if (findingText) {
if (TextRecognizer.getInstance() != null) {
log(lvl, "doFind: Switching to TextSearch");
f = new Finder(getScreen().capture(x, y, w, h), this);
lastSearchTime = (new Date()).getTime();
f.findText((String) ptn);
}
}
} else if (ptn instanceof Pattern) {
if (((Pattern) ptn).isValid()) {
img = ((Pattern) ptn).getImage();
lastSearchTime = (new Date()).getTime();
f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), (Pattern) ptn);
if (!f.hasNext()) {
f.find((Pattern) ptn);
}
} else {
throw new IOException("Region: doFind: Image not loadable: " + ptn.toString());
}
} else if (ptn instanceof Image) {
if (((Image) ptn).isValid()) {
img = ((Image) ptn);
lastSearchTime = (new Date()).getTime();
f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), null);
if (!f.hasNext()) {
f.find(img);
}
} else {
throw new IOException("Region: doFind: Image not loadable: " + ptn.toString());
}
} else {
log(-1, "doFind: invalid parameter: %s", ptn);
Sikulix.terminate(999);
}
if (repeating != null) {
repeating._finder = f;
repeating._image = img;
}
}
lastSearchTime = (new Date()).getTime() - lastSearchTime;
lastFindTime = (new Date()).getTime() - lastFindTime;
if (f.hasNext()) {
m = f.next();
m.setTimes(lastFindTime, lastSearchTime);
}
return m;
} | #vulnerable code
private <PSI> Match doFind(PSI ptn, RepeatableFind repeating) throws IOException {
Finder f = null;
Match m = null;
boolean findingText = false;
lastFindTime = (new Date()).getTime();
ScreenImage simg;
if (repeating != null && repeating._finder != null) {
simg = getScreen().capture(this);
f = repeating._finder;
f.setScreenImage(simg);
f.setRepeating();
lastSearchTime = (new Date()).getTime();
f.findRepeat();
} else {
Image img = null;
if (ptn instanceof String) {
if (((String) ptn).startsWith("\t") && ((String) ptn).endsWith("\t")) {
findingText = true;
} else {
img = Image.create((String) ptn);
if (img.isValid()) {
lastSearchTime = (new Date()).getTime();
f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), null);
if (!f.hasNext()) {
f.find(img);
}
} else if (img.isText()) {
findingText = true;
} else {
throw new IOException("Region: doFind: Image not loadable: " + (String) ptn);
}
}
if (findingText) {
if (TextRecognizer.getInstance() != null) {
log(lvl, "doFind: Switching to TextSearch");
f = new Finder(getScreen().capture(x, y, w, h), this);
lastSearchTime = (new Date()).getTime();
f.findText((String) ptn);
}
}
} else if (ptn instanceof Pattern) {
if (((Pattern) ptn).isValid()) {
img = ((Pattern) ptn).getImage();
lastSearchTime = (new Date()).getTime();
f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), (Pattern) ptn);
if (!f.hasNext()) {
f.find((Pattern) ptn);
}
} else {
throw new IOException("Region: doFind: Image not loadable: " + (String) ptn);
}
} else if (ptn instanceof Image) {
if (((Image) ptn).isValid()) {
img = ((Image) ptn);
lastSearchTime = (new Date()).getTime();
f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), null);
if (!f.hasNext()) {
f.find(img);
}
} else {
throw new IOException("Region: doFind: Image not loadable: " + (String) ptn);
}
} else {
log(-1, "doFind: invalid parameter: %s", ptn);
Sikulix.terminate(999);
}
if (repeating != null) {
repeating._finder = f;
repeating._image = img;
}
}
lastSearchTime = (new Date()).getTime() - lastSearchTime;
lastFindTime = (new Date()).getTime() - lastFindTime;
if (f.hasNext()) {
m = f.next();
m.setTimes(lastFindTime, lastSearchTime);
}
return m;
}
#location 74
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public void cleanup() {
} | #vulnerable code
@Override
public void cleanup() {
HotkeyManager.getInstance().cleanUp();
keyUp();
mouseUp(0);
}
#location 3
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Boolean handleImageMissing(Image img, boolean recap) {
log(lvl, "handleImageMissing: %s (%s)", img.getName(), (recap?"recapture ":"capture missing "));
ObserveEvent evt = null;
FindFailedResponse response = findFailedResponse;
if (FindFailedResponse.HANDLE.equals(response)) {
ObserveEvent.Type type = ObserveEvent.Type.MISSING;
if (imageMissingHandler != null && ((ObserverCallBack) imageMissingHandler).getType().equals(type)) {
log(lvl, "handleImageMissing: Response.HANDLE: calling handler");
evt = new ObserveEvent("", type, null, img, this, 0);
((ObserverCallBack) imageMissingHandler).missing(evt);
response = evt.getResponse();
} else {
response = FindFailedResponse.PROMPT;
}
}
if (FindFailedResponse.PROMPT.equals(response)) {
response = handleFindFailedShowDialog(img, true);
}
if (findFailedResponse.RETRY.equals(response)) {
getRobotForRegion().delay(500);
ScreenImage simg = getScreen().userCapture(
(recap?"recapture ":"capture missing ") + img.getName());
if (simg != null) {
String path = ImagePath.getBundlePath();
if (path == null) {
log(-1, "handleImageMissing: no bundle path - aborting");
return null;
}
simg.getFile(path, img.getImageName());
Image.set(img);
if (img.isValid()) {
log(lvl, "handleImageMissing: %scaptured: %s", (recap?"re":""), img);
Image.setIDEshouldReload();
return true;
}
}
return null;
} else if (findFailedResponse.ABORT.equals(response)) {
return null;
}
log(lvl, "handleImageMissing: skip requested on %s", (recap?"recapture ":"capture missing "));
return false;
} | #vulnerable code
private Boolean handleImageMissing(Image img, boolean recap) {
log(lvl, "handleImageMissing: %s (%s)", img.getName(), (recap?"recapture ":"capture missing "));
FindFailedResponse response = handleFindFailedShowDialog(img, true);
if (findFailedResponse.RETRY.equals(response)) {
getRobotForRegion().delay(500);
ScreenImage simg = getScreen().userCapture(
(recap?"recapture ":"capture missing ") + img.getName());
if (simg != null) {
String path = ImagePath.getBundlePath();
if (path == null) {
log(-1, "handleImageMissing: no bundle path - aborting");
return null;
}
simg.getFile(path, img.getImageName());
Image.set(img);
if (img.isValid()) {
log(lvl, "handleImageMissing: %scaptured: %s", (recap?"re":""), img);
Image.setIDEshouldReload();
return true;
}
}
return null;
} else if (findFailedResponse.HANDLE.equals(response)) {
log(-1, "handleImageMissing: HANDLE: not implemented");
return null;
} else if (findFailedResponse.ABORT.equals(response)) {
return null;
}
log(lvl, "handleImageMissing: skip requested on %s", (recap?"recapture ":"capture missing "));
return false;
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public <PSI> Iterator<Match> findAll(PSI target) throws FindFailed {
lastMatches = null;
Image img = null;
String targetStr = target.toString();
if (target instanceof String) {
targetStr = targetStr.trim();
}
while (true) {
try {
if (autoWaitTimeout > 0) {
RepeatableFindAll rf = new RepeatableFindAll(target);
rf.repeat(autoWaitTimeout);
lastMatches = rf.getMatches();
} else {
lastMatches = doFindAll(target, null);
}
} catch (Exception ex) {
if (ex instanceof IOException) {
if (handleImageMissing(img, false)) {
continue;
}
}
throw new FindFailed(ex.getMessage());
}
if (lastMatches != null) {
return lastMatches;
}
if (!handleFindFailed(target, img)) {
return null;
}
}
} | #vulnerable code
public <PSI> Iterator<Match> findAll(PSI target) throws FindFailed {
lastMatches = null;
Image img = null;
String targetStr = target.toString();
if (target instanceof String) {
targetStr = targetStr.trim();
}
while (true) {
try {
if (autoWaitTimeout > 0) {
RepeatableFindAll rf = new RepeatableFindAll(target);
rf.repeat(autoWaitTimeout);
lastMatches = rf.getMatches();
} else {
lastMatches = doFindAll(target, null);
}
} catch (Exception ex) {
if (ex instanceof IOException) {
if (handleImageMissing(img, false)) {
continue;
}
}
throw new FindFailed(ex.getMessage());
}
if (lastMatches != null) {
return lastMatches;
}
if (!handleFindFailed(img)) {
return null;
}
}
}
#location 28
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String mName = method.getName();
if ("handleAbout".equals(mName)) {
sikulixIDE.doAbout();
} else if ("handlePreferences".equals(mName)) {
sikulixIDE.showPreferencesWindow();
} else if ("handleQuitRequestWith".equals(mName)) {
try {
Class sysclass = URLClassLoader.class;
Class comAppleEawtQuitResponse = sysclass.forName("com.apple.eawt.QuitResponse");
Method mCancelQuit = comAppleEawtQuitResponse.getMethod("cancelQuit", null);
Method mPerformQuit = comAppleEawtQuitResponse.getMethod("performQuit", null);
Object resp = args[1];
if (!sikulixIDE.quit()) {
mCancelQuit.invoke(resp, null);
} else {
mPerformQuit.invoke(resp, null);
}
} catch (Exception ex) {
log(lvl, "NativeSupport: Quit: error: %s", ex.getMessage());
System.exit(1);
}
}
return new Object();
} | #vulnerable code
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String mName = method.getName();
if ("handleAbout".equals(mName)) {
SikuliIDE.getInstance().doAbout();
} else if ("handlePreferences".equals(mName)) {
SikuliIDE.getInstance().showPreferencesWindow();
} else if ("handleQuitRequestWith".equals(mName)) {
try {
Class sysclass = URLClassLoader.class;
Class comAppleEawtQuitResponse = sysclass.forName("com.apple.eawt.QuitResponse");
Method mCancelQuit = comAppleEawtQuitResponse.getMethod("cancelQuit", null);
Method mPerformQuit = comAppleEawtQuitResponse.getMethod("performQuit", null);
Object resp = args[1];
if (!SikuliIDE.getInstance().quit()) {
mCancelQuit.invoke(resp, null);
} else {
mPerformQuit.invoke(resp, null);
}
} catch (Exception ex) {
log(lvl, "NativeSupport: Quit: error: %s", ex.getMessage());
System.exit(1);
}
}
return new Object();
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static boolean unzip(File fZip, File fTarget) {
String fpZip = null;
String fpTarget = null;
log(lvl, "unzip: from: %s\nto: %s", fZip, fTarget);
try {
fpZip = fZip.getCanonicalPath();
if (!new File(fpZip).exists()) {
throw new IOException();
}
} catch (IOException ex) {
log(-1, "unzip: source not found:\n%s\n%s", fpZip, ex);
return false;
}
try {
fpTarget = fTarget.getCanonicalPath();
deleteFileOrFolder(fpTarget);
new File(fpTarget).mkdirs();
if (!new File(fpTarget).exists()) {
throw new IOException();
}
} catch (IOException ex) {
log(-1, "unzip: target cannot be created:\n%s\n%s", fpTarget, ex);
return false;
}
ZipInputStream inpZip = null;
ZipEntry entry = null;
try {
final int BUF_SIZE = 2048;
inpZip = new ZipInputStream(new BufferedInputStream(new FileInputStream(fZip)));
while ((entry = inpZip.getNextEntry()) != null) {
if (entry.getName().endsWith("/") || entry.getName().endsWith("\\")) {
new File(fpTarget, entry.getName()).mkdir();
continue;
}
int count;
byte data[] = new byte[BUF_SIZE];
File outFile = new File(fpTarget, entry.getName());
File outFileParent = outFile.getParentFile();
if (! outFileParent.exists()) {
outFileParent.mkdirs();
}
FileOutputStream fos = new FileOutputStream(outFile);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUF_SIZE);
while ((count = inpZip.read(data, 0, BUF_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.close();
}
} catch (Exception ex) {
log(-1, "unzip: not possible: source:\n%s\ntarget:\n%s\n(%s)%s",
fpZip, fpTarget, entry.getName(), ex);
return false;
} finally {
try {
inpZip.close();
} catch (IOException ex) {
log(-1, "unzip: closing source:\n%s\n%s", fpZip, ex);
}
}
return true;
} | #vulnerable code
public static boolean unzip(File fZip, File fTarget) {
String fpZip = null;
String fpTarget = null;
try {
fpZip = fZip.getCanonicalPath();
if (!fZip.exists()) {
log(-1, "unzip: source not found:\n%s", fpZip);
return false;
}
fTarget.mkdirs();
fpTarget = fTarget.getCanonicalPath();
if (!fZip.exists()) {
log(-1, "unzip: target not found:\n%s", fTarget);
return false;
}
final int BUF_SIZE = 2048;
ZipInputStream isZip = new ZipInputStream(new BufferedInputStream(new FileInputStream(fZip)));
ZipEntry entry;
while ((entry = isZip.getNextEntry()) != null) {
int count;
byte data[] = new byte[BUF_SIZE];
FileOutputStream fos = new FileOutputStream(new File(fTarget, entry.getName()));
BufferedOutputStream dest = new BufferedOutputStream(fos, BUF_SIZE);
while ((count = isZip.read(data, 0, BUF_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.close();
}
isZip.close();
} catch (Exception ex) {
log(-1, "unzip: not possible: source:\n%s\ntarget:\n%s\n%s", fpZip, fpTarget, ex);
}
return true;
}
#location 30
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public <PSI> Match wait(PSI target, double timeout) throws FindFailed {
lastMatch = null;
FindFailed shouldAbort = null;
RepeatableFind rf = new RepeatableFind(target, null);
Image img = rf._image;
String targetStr = img.getName();
Boolean response = true;
if (!img.isValid() && img.hasIOException()) {
response = handleImageMissing(img, false);
}
while (null != response && response) {
log(lvl, "find: waiting %.1f secs for %s to appear in %s", timeout, targetStr, this.toStringShort());
if (rf.repeat(timeout)) {
lastMatch = rf.getMatch();
lastMatch.setImage(img);
if (img != null) {
img.setLastSeen(lastMatch.getRect(), lastMatch.getScore());
}
log(lvl, "find: %s has appeared \nat %s", targetStr, lastMatch);
return lastMatch;
} else {
response = handleFindFailed(target, img, false);
if (null == response) {
shouldAbort = FindFailed.createdefault(this, img);
break;
} else if (response) {
if (img.isRecaptured()) {
rf = new RepeatableFind(target, img);
}
continue;
}
break;
}
}
log(lvl, "find: %s has not appeared [%d msec]", targetStr, lastFindTime);
if (shouldAbort != null) {
throw shouldAbort;
}
return lastMatch;
} | #vulnerable code
public <PSI> Match wait(PSI target, double timeout) throws FindFailed {
RepeatableFind rf;
lastMatch = null;
//Image img = null;
String targetStr = target.toString();
if (target instanceof String) {
targetStr = targetStr.trim();
}
while (true) {
try {
log(lvl, "find: waiting %.1f secs for %s to appear in %s", timeout, targetStr, this.toStringShort());
rf = new RepeatableFind(target, null);
rf.repeat(timeout);
lastMatch = rf.getMatch();
} catch (Exception ex) {
if (ex instanceof IOException) {
}
throw new FindFailed(ex.getMessage());
}
if (lastMatch != null) {
lastMatch.setImage(rf._image);
if (rf._image != null) {
rf._image.setLastSeen(lastMatch.getRect(), lastMatch.getScore());
}
log(lvl, "find: %s has appeared \nat %s", targetStr, lastMatch);
break;
}
Image img = rf._image;
if (handleImageMissing(img, false)) {
continue;
}
log(lvl, "find: %s has not appeared [%d msec]", targetStr, lastFindTime);
if (!handleFindFailed(target, img)) {
return null;
}
}
return lastMatch;
}
#location 14
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String[] args) {
String[] splashArgs = new String[]{
"splash", "#", "#" + Settings.SikuliVersionIDE, "", "#", "#... starting - please wait ..."};
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log(lvl, "final cleanup");
if (isRunning != null) {
try {
isRunningFile.close();
} catch (IOException ex) {
}
isRunning.delete();
}
FileManager.cleanTemp();
}
});
if (System.getProperty("sikuli.FromCommandLine") == null) {
String[] userOptions = collectOptions("IDE", args);
if (userOptions == null) {
System.exit(0);
}
if (userOptions.length > 0) {
for (String e : userOptions) {
log(lvl, "arg: " + e);
}
args = userOptions;
}
}
start = (new Date()).getTime();
ScriptRunner.initScriptingSupport();
IDESupport.initIDESupport();
CommandArgs cmdArgs = new CommandArgs("IDE");
cmdLine = cmdArgs.getCommandLine(CommandArgs.scanArgs(args));
if (cmdLine == null) {
Debug.error("Did not find any valid option on command line!");
System.exit(1);
}
if (cmdLine.hasOption("h")) {
cmdArgs.printHelp();
System.exit(0);
}
if (cmdLine.hasOption("c")) {
System.setProperty("sikuli.console", "false");
}
if (cmdLine.hasOption(CommandArgsEnum.LOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.LOGFILE.longname());
if (!Debug.setLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.USERLOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.USERLOGFILE.longname());
if (!Debug.setUserLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.DEBUG.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.DEBUG.longname());
if (cmdValue == null) {
Debug.setDebugLevel(3);
Debug.setLogFile("");
Settings.LogTime = true;
} else {
Debug.setDebugLevel(cmdValue);
}
}
if (cmdLine.hasOption(CommandArgsEnum.LOAD.shortname())) {
loadScripts = cmdLine.getOptionValues(CommandArgsEnum.LOAD.longname());
log(lvl, "requested to load: " + loadScripts);
if (loadScripts[0].endsWith(".skl")) {
log(lvl, "Switching to ScriptRunner to run " + loadScripts[0]);
ScriptRunner.runscript(args);
}
}
if (cmdLine.hasOption(CommandArgsEnum.RUN.shortname())
|| cmdLine.hasOption(CommandArgsEnum.TEST.shortname())
|| cmdLine.hasOption(CommandArgsEnum.INTERACTIVE.shortname())) {
log(lvl, "Switching to ScriptRunner with option -r, -t or -i");
ScriptRunner.runscript(args);
}
new File(Settings.BaseTempPath).mkdirs();
isRunning = new File(Settings.BaseTempPath, "sikuli-ide-isrunning");
try {
isRunning.createNewFile();
isRunningFile = new FileOutputStream(isRunning);
if (null == isRunningFile.getChannel().tryLock()) {
splashArgs[5] = "Terminating on FatalError: IDE already running";
splash = new SplashFrame(splashArgs);
log(-1, splashArgs[5]);
Sikulix.pause(3);
System.exit(1);
}
} catch (Exception ex) {
splashArgs[5] = "Terminating on FatalError: cannot access IDE lock ";
splash = new SplashFrame(splashArgs);
log(-1, splashArgs[5] + "\n" + isRunning.getAbsolutePath());
Sikulix.pause(3);
System.exit(1);
}
Settings.setArgs(cmdArgs.getUserArgs(), cmdArgs.getSikuliArgs());
Settings.showJavaInfo();
Settings.printArgs();
if (Settings.isMac()) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "SikuliX-u8zIDE");
}
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//TODO UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
log(-1, "Problem loading UIManager!\nError: %s", e.getMessage());
}
SikuliIDE.getInstance().initNativeSupport();
SikuliIDE.getInstance().initSikuliIDE(args);
} | #vulnerable code
public static void main(String[] args) {
String[] splashArgs = new String[]{
"splash", "#", "#" + Settings.SikuliVersionIDE, "", "#", "#... starting - please wait ..."};
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log(lvl, "final cleanup");
if (isRunning != null) {
try {
isRunningFile.close();
} catch (IOException ex) {
}
isRunning.delete();
}
FileManager.cleanTemp();
}
});
if (System.getProperty("sikuli.FromCommandLine") == null) {
String[] userOptions = collectOptions("IDE", args);
if (userOptions == null) {
System.exit(0);
}
if (userOptions.length > 0) {
for (String e : userOptions) {
log(lvl, "arg: " + e);
}
args = userOptions;
}
}
start = (new Date()).getTime();
ScriptRunner.initScriptingSupport();
IDESupport.initIDESupport();
CommandArgs cmdArgs = new CommandArgs("IDE");
cmdLine = cmdArgs.getCommandLine(CommandArgs.scanArgs(args));
if (cmdLine == null) {
Debug.error("Did not find any valid option on command line!");
System.exit(1);
}
if (cmdLine.hasOption("h")) {
cmdArgs.printHelp();
System.exit(0);
}
if (cmdLine.hasOption("c")) {
System.setProperty("sikuli.console", "false");
}
if (cmdLine.hasOption(CommandArgsEnum.LOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.LOGFILE.longname());
if (!Debug.setLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.USERLOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.USERLOGFILE.longname());
if (!Debug.setUserLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.DEBUG.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.DEBUG.longname());
if (cmdValue == null) {
Debug.setDebugLevel(3);
Debug.setLogFile("");
Settings.LogTime = true;
} else {
Debug.setDebugLevel(cmdValue);
}
}
if (cmdLine.hasOption(CommandArgsEnum.LOAD.shortname())) {
loadScripts = cmdLine.getOptionValues(CommandArgsEnum.LOAD.longname());
log(lvl, "requested to load: " + loadScripts);
if (loadScripts[0].endsWith(".skl")) {
log(lvl, "Switching to ScriptRunner to run " + loadScripts[0]);
ScriptRunner.runscript(args);
}
}
if (cmdLine.hasOption(CommandArgsEnum.RUN.shortname())
|| cmdLine.hasOption(CommandArgsEnum.TEST.shortname())
|| cmdLine.hasOption(CommandArgsEnum.INTERACTIVE.shortname())) {
log(lvl, "Switching to ScriptRunner with option -r, -t or -i");
ScriptRunner.runscript(args);
}
new File(Settings.BaseTempPath).mkdirs();
isRunning = new File(Settings.BaseTempPath, "sikuli-ide-isrunning");
try {
isRunning.createNewFile();
isRunningFile = new FileOutputStream(isRunning);
if (null == isRunningFile.getChannel().tryLock()) {
splashArgs[5] = "Terminating on FatalError: IDE already running";
splash = new SplashFrame(splashArgs);
log(-1, splashArgs[5]);
Sikulix.pause(3);
System.exit(1);
}
} catch (Exception ex) {
splashArgs[5] = "Terminating on FatalError: cannot access IDE lock ";
splash = new SplashFrame(splashArgs);
log(-1, splashArgs[5] + "\n" + isRunning.getAbsolutePath());
Sikulix.pause(3);
System.exit(1);
}
Settings.setArgs(cmdArgs.getUserArgs(), cmdArgs.getSikuliArgs());
Settings.showJavaInfo();
Settings.printArgs();
initNativeSupport();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
log(-1, "Problem loading UIManager!\nError: %s", e.getMessage());
}
if (nativeSupport != null) {
nativeSupport.initApp(Debug.getDebugLevel() > 2 ? true : false);
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
SikuliIDE.getInstance(args);
}
#location 120
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void loadFile(String filename) {
log(lvl, "loadfile: %s", filename);
filename = FileManager.slashify(filename, false);
setSrcBundle(filename + "/");
File script = new File(filename);
_editingFile = ScriptRunner.getScriptFile(script);
if (_editingFile != null) {
scriptType = _editingFile.getAbsolutePath().substring(_editingFile.getAbsolutePath().lastIndexOf(".") + 1);
initBeforeLoad(scriptType);
try {
if (!readScript(_editingFile)) {
_editingFile = null;
}
} catch (Exception ex) {
log(-1, "read returned %s", ex.getMessage());
_editingFile = null;
}
updateDocumentListeners("loadFile");
setDirty(false);
_srcBundleTemp = false;
}
if (_editingFile == null) {
_srcBundlePath = null;
}
} | #vulnerable code
public void loadFile(String filename) {
log(lvl, "loadfile: %s", filename);
filename = FileManager.slashify(filename, false);
setSrcBundle(filename + "/");
File script = new File(filename);
_editingFile = ScriptRunner.getScriptFile(script);
if (_editingFile != null) {
scriptType = _editingFile.getAbsolutePath().substring(_editingFile.getAbsolutePath().lastIndexOf(".") + 1);
initBeforeLoad(scriptType);
try {
this.read(new BufferedReader(new InputStreamReader(
new FileInputStream(_editingFile), "UTF8")), null);
} catch (Exception ex) {
_editingFile = null;
}
updateDocumentListeners("loadFile");
setDirty(false);
_srcBundleTemp = false;
}
if (_editingFile == null) {
_srcBundlePath = null;
}
}
#location 11
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String[] args) throws FindFailed {
System.out.println("********** Running Sikulix.main");
if (args.length > 1 && args[0].toLowerCase().startsWith("runserver")) {
if (args[1].toLowerCase().contains("start")) {
RunServer.run(null);
System.exit(0);
} else {
File fRunServer = new File(RunTime.get().fSikulixStore, "RunServer");
String theServer = "";
if (fRunServer.exists()) {
theServer = FileManager.readFileToString(fRunServer).trim();
if (!theServer.isEmpty()) {
String[] parts = theServer.split(" ");
RunClient runner = new RunClient(parts[0].trim(), parts[1].trim());
runner.close(true);
fRunServer.delete();
System.exit(0);
}
}
}
}
int dl = RunTime.checkArgs(args, RunTime.Type.API);
if (dl > -1 && dl < 999) {
testNumber = dl;
Debug.on(3);
} else {
testNumber = -1;
}
testNumber = rt.getOptionNumber("testing.test", testNumber);
if (dl == 999) {
int exitCode = Runner.runScripts(args);
cleanUp(exitCode);
System.exit(exitCode);
} else if (testNumber > -1) {
if (!rt.testing) {
rt.show();
rt.testing = true;
}
Tests.runTest(testNumber);
System.exit(1);
} else {
rt = RunTime.get();
if (rt.fSxBaseJar.getName().contains("setup")) {
Sikulix.popError("Not useable!\nRun setup first!");
System.exit(0);
}
Debug.on(3);
Settings.InfoLogs = false;
Settings.ActionLogs = false;
Screen s = new Screen();
RunClient runner = new RunClient("192.168.2.122", "50001");
runner.close(true);
System.exit(1);
if (rt.runningWinApp) {
popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName());
try {
Screen scr = new Screen();
scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3);
} catch (Exception ex) {
popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName());
}
popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName());
System.exit(1);
}
String version = String.format("(%s-%s)", rt.getVersionShort(), rt.sxBuildStamp);
File lastSession = new File(rt.fSikulixStore, "LastAPIJavaScript.js");
String runSomeJS = "";
if (lastSession.exists()) {
runSomeJS = FileManager.readFileToString(lastSession);
}
runSomeJS = inputText("enter some JavaScript (know what you do - may silently die ;-)"
+ "\nexample: run(\"git*\") will run the JavaScript showcase from GitHub"
+ "\nWhat you enter now will be shown the next time.",
"API::JavaScriptRunner " + version, 10, 60, runSomeJS);
if (runSomeJS.isEmpty()) {
popup("Nothing to do!", version);
} else {
FileManager.writeStringToFile(runSomeJS, lastSession);
Runner.runjs(null, null, runSomeJS, null);
}
}
} | #vulnerable code
public static void main(String[] args) throws FindFailed {
System.out.println("********** Running Sikulix.main");
int dl = RunTime.checkArgs(args, RunTime.Type.API);
if (dl > -1 && dl < 999) {
testNumber = dl;
Debug.on(3);
} else {
testNumber = -1;
}
testNumber = rt.getOptionNumber("testing.test", testNumber);
if (dl == 999) {
int exitCode = Runner.runScripts(args);
cleanUp(exitCode);
System.exit(exitCode);
} else if (testNumber > -1) {
if (!rt.testing) {
rt.show();
rt.testing = true;
}
Tests.runTest(testNumber);
System.exit(1);
} else {
rt = RunTime.get();
if (rt.fSxBaseJar.getName().contains("setup")) {
Sikulix.popError("Not useable!\nRun setup first!");
System.exit(0);
}
Debug.on(3);
Settings.InfoLogs = false;
Settings.ActionLogs = false;
Screen s = new Screen();
RunClient runner = new RunClient("192.168.2.114", "50001");
runner.send("START");
runner.send("SDIR /Volumes/HD6/rhocke-plus/SikuliX-2014/StuffContainer/testScripts/testJavaScript");
runner.send("RUN testRunServer");
runner.close(true);
System.exit(1);
if (rt.runningWinApp) {
popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName());
try {
Screen scr = new Screen();
scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3);
} catch (Exception ex) {
popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName());
}
popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName());
System.exit(1);
}
String version = String.format("(%s-%s)", rt.getVersionShort(), rt.sxBuildStamp);
File lastSession = new File(rt.fSikulixStore, "LastAPIJavaScript.js");
String runSomeJS = "";
if (lastSession.exists()) {
runSomeJS = FileManager.readFileToString(lastSession);
}
runSomeJS = inputText("enter some JavaScript (know what you do - may silently die ;-)"
+ "\nexample: run(\"git*\") will run the JavaScript showcase from GitHub"
+ "\nWhat you enter now will be shown the next time.",
"API::JavaScriptRunner " + version, 10, 60, runSomeJS);
if (runSomeJS.isEmpty()) {
popup("Nothing to do!", version);
} else {
FileManager.writeStringToFile(runSomeJS, lastSession);
Runner.runjs(null, null, runSomeJS, null);
}
}
}
#location 39
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void drawSelection(Graphics2D g2d) {
if (srcx != destx || srcy != desty) {
int x1 = (srcx < destx) ? srcx : destx;
int y1 = (srcy < desty) ? srcy : desty;
int x2 = (srcx > destx) ? srcx : destx;
int y2 = (srcy > desty) ? srcy : desty;
rectSelection.x = x1;
rectSelection.y = y1;
rectSelection.width = (x2 - x1) + 1;
rectSelection.height = (y2 - y1) + 1;
if (rectSelection.width > 0 && rectSelection.height > 0) {
g2d.drawImage(scr_img.getSubimage(x1, y1, x2 - x1 + 1, y2 - y1 + 1),
null, x1, y1);
}
g2d.setColor(selFrameColor);
g2d.setStroke(bs);
g2d.draw(rectSelection);
int cx = (x1 + x2) / 2;
int cy = (y1 + y2) / 2;
g2d.setColor(selCrossColor);
g2d.setStroke(_StrokeCross);
g2d.drawLine(cx, y1, cx, y2);
g2d.drawLine(x1, cy, x2, cy);
if (Screen.getNumberScreens() > 1) {
drawScreenFrame(g2d, srcScreenId);
}
}
} | #vulnerable code
private void drawSelection(Graphics2D g2d) {
if (srcx != destx || srcy != desty) {
int x1 = (srcx < destx) ? srcx : destx;
int y1 = (srcy < desty) ? srcy : desty;
int x2 = (srcx > destx) ? srcx : destx;
int y2 = (srcy > desty) ? srcy : desty;
if (Screen.getNumberScreens() > 1) {
Rectangle selRect = new Rectangle(x1, y1, x2 - x1, y2 - y1);
Rectangle ubound = (new ScreenUnion()).getBounds();
selRect.x += ubound.x;
selRect.y += ubound.y;
Rectangle inBound = selRect.intersection(Screen.getBounds(srcScreenId));
x1 = inBound.x - ubound.x;
y1 = inBound.y - ubound.y;
x2 = x1 + inBound.width - 1;
y2 = y1 + inBound.height - 1;
}
rectSelection.x = x1;
rectSelection.y = y1;
rectSelection.width = (x2 - x1) + 1;
rectSelection.height = (y2 - y1) + 1;
if (rectSelection.width > 0 && rectSelection.height > 0) {
g2d.drawImage(scr_img.getSubimage(x1, y1, x2 - x1 + 1, y2 - y1 + 1),
null, x1, y1);
}
g2d.setColor(selFrameColor);
g2d.setStroke(bs);
g2d.draw(rectSelection);
int cx = (x1 + x2) / 2;
int cy = (y1 + y2) / 2;
g2d.setColor(selCrossColor);
g2d.setStroke(_StrokeCross);
g2d.drawLine(cx, y1, cx, y2);
g2d.drawLine(x1, cy, x2, cy);
if (Screen.getNumberScreens() > 1) {
drawScreenFrame(g2d, srcScreenId);
}
}
}
#location 11
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Deprecated
public static boolean removeHotkey(String key, int modifiers) {
return Key.removeHotkey(key, modifiers);
} | #vulnerable code
@Deprecated
public static boolean removeHotkey(String key, int modifiers) {
return HotkeyManager.getInstance().removeHotkey(key, modifiers);
}
#location 3
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log(lvl, "final cleanup");
if (isRunning != null) {
try {
isRunningFile.close();
} catch (IOException ex) {
}
isRunning.delete();
}
FileManager.cleanTemp();
}
});
// if (System.getProperty("sikuli.FromCommandLine") == null) {
// String[] userOptions = collectOptions("IDE", args);
// if (userOptions == null) {
// System.exit(0);
// }
// if (userOptions.length > 0) {
// for (String e : userOptions) {
// log(lvl, "arg: " + e);
// }
// args = userOptions;
// }
// }
start = (new Date()).getTime();
CommandArgs cmdArgs = new CommandArgs("IDE");
cmdLine = cmdArgs.getCommandLine(CommandArgs.scanArgs(args));
if (cmdLine == null) {
Debug.error("Did not find any valid option on command line!");
System.exit(1);
}
if (cmdLine.hasOption(CommandArgsEnum.DEBUG.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.DEBUG.longname());
if (cmdValue == null) {
Debug.setDebugLevel(3);
Debug.setLogFile("");
Settings.LogTime = true;
} else {
Debug.setDebugLevel(cmdValue);
}
}
if (cmdLine.hasOption("h")) {
cmdArgs.printHelp();
System.exit(0);
}
if (cmdLine.hasOption("c")) {
System.setProperty("sikuli.console", "false");
}
if (cmdLine.hasOption(CommandArgsEnum.LOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.LOGFILE.longname());
if (!Debug.setLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.USERLOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.USERLOGFILE.longname());
if (!Debug.setUserLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.LOAD.shortname())) {
loadScripts = cmdLine.getOptionValues(CommandArgsEnum.LOAD.longname());
log(lvl, "requested to load: %s", loadScripts);
}
if (cmdLine.hasOption(CommandArgsEnum.RUN.shortname())
|| cmdLine.hasOption(CommandArgsEnum.TEST.shortname())
|| cmdLine.hasOption(CommandArgsEnum.INTERACTIVE.shortname())) {
log(lvl, "Switching to ScriptRunner with option -r, -t or -i");
ScriptRunner.runscript(args);
}
new File(Settings.BaseTempPath).mkdirs();
isRunning = new File(Settings.BaseTempPath, "sikuli-ide-isrunning");
try {
isRunning.createNewFile();
isRunningFile = new FileOutputStream(isRunning);
if (null == isRunningFile.getChannel().tryLock()) {
Sikulix.popError("Terminating on FatalError: IDE already running");
System.exit(1);
}
} catch (Exception ex) {
Sikulix.popError("Terminating on FatalError: cannot access IDE lock for/n" + isRunning);
System.exit(1);
}
Settings.isRunningIDE = true;
if (Settings.isMac()) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "SikuliX-IDE");
}
getInstance();
Settings.setArgs(cmdArgs.getUserArgs(), cmdArgs.getSikuliArgs());
Settings.showJavaInfo();
Settings.printArgs();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//TODO UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
log(-1, "Problem loading UIManager!\nError: %s", e.getMessage());
}
ScriptRunner.initScriptingSupport();
IDESupport.initIDESupport();
sikulixIDE.initNativeSupport();
sikulixIDE.initSikuliIDE(args);
} | #vulnerable code
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log(lvl, "final cleanup");
if (isRunning != null) {
try {
isRunningFile.close();
} catch (IOException ex) {
}
isRunning.delete();
}
FileManager.cleanTemp();
}
});
// if (System.getProperty("sikuli.FromCommandLine") == null) {
// String[] userOptions = collectOptions("IDE", args);
// if (userOptions == null) {
// System.exit(0);
// }
// if (userOptions.length > 0) {
// for (String e : userOptions) {
// log(lvl, "arg: " + e);
// }
// args = userOptions;
// }
// }
start = (new Date()).getTime();
CommandArgs cmdArgs = new CommandArgs("IDE");
cmdLine = cmdArgs.getCommandLine(CommandArgs.scanArgs(args));
if (cmdLine == null) {
Debug.error("Did not find any valid option on command line!");
System.exit(1);
}
if (cmdLine.hasOption(CommandArgsEnum.DEBUG.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.DEBUG.longname());
if (cmdValue == null) {
Debug.setDebugLevel(3);
Debug.setLogFile("");
Settings.LogTime = true;
} else {
Debug.setDebugLevel(cmdValue);
}
}
if (cmdLine.hasOption("h")) {
cmdArgs.printHelp();
System.exit(0);
}
if (cmdLine.hasOption("c")) {
System.setProperty("sikuli.console", "false");
}
if (cmdLine.hasOption(CommandArgsEnum.LOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.LOGFILE.longname());
if (!Debug.setLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.USERLOGFILE.shortname())) {
cmdValue = cmdLine.getOptionValue(CommandArgsEnum.USERLOGFILE.longname());
if (!Debug.setUserLogFile(cmdValue == null ? "" : cmdValue)) {
System.exit(1);
}
}
if (cmdLine.hasOption(CommandArgsEnum.LOAD.shortname())) {
loadScripts = cmdLine.getOptionValues(CommandArgsEnum.LOAD.longname());
log(lvl, "requested to load: %s", loadScripts);
}
if (cmdLine.hasOption(CommandArgsEnum.RUN.shortname())
|| cmdLine.hasOption(CommandArgsEnum.TEST.shortname())
|| cmdLine.hasOption(CommandArgsEnum.INTERACTIVE.shortname())) {
log(lvl, "Switching to ScriptRunner with option -r, -t or -i");
ScriptRunner.runscript(args);
}
new File(Settings.BaseTempPath).mkdirs();
isRunning = new File(Settings.BaseTempPath, "sikuli-ide-isrunning");
try {
isRunning.createNewFile();
isRunningFile = new FileOutputStream(isRunning);
if (null == isRunningFile.getChannel().tryLock()) {
Sikulix.popError("Terminating on FatalError: IDE already running");
System.exit(1);
}
} catch (Exception ex) {
Sikulix.popError("Terminating on FatalError: cannot access IDE lock");
System.exit(1);
}
Settings.isRunningIDE = true;
Settings.setArgs(cmdArgs.getUserArgs(), cmdArgs.getSikuliArgs());
Settings.showJavaInfo();
Settings.printArgs();
if (Settings.isMac()) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "SikuliX-IDE");
}
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//TODO UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
log(-1, "Problem loading UIManager!\nError: %s", e.getMessage());
}
ScriptRunner.initScriptingSupport();
IDESupport.initIDESupport();
SikuliIDE.getInstance().initNativeSupport();
SikuliIDE.getInstance().initSikuliIDE(args);
}
#location 122
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
void drawMessage(Graphics2D g2d) {
if (promptMsg == null) {
return;
}
g2d.setFont(fontMsg);
g2d.setColor(new Color(1f, 1f, 1f, 1));
int sw = g2d.getFontMetrics().stringWidth(promptMsg);
int sh = g2d.getFontMetrics().getMaxAscent();
// Rectangle ubound = (new ScreenUnion()).getBounds();
Rectangle ubound = scrOCP.getBounds();
for (int i = 0; i < Screen.getNumberScreens(); i++) {
if (!Screen.getScreen(i).hasPrompt()) {
continue;
}
Rectangle bound = Screen.getBounds(i);
int cx = bound.x + (bound.width - sw) / 2 - ubound.x;
int cy = bound.y + (bound.height - sh) / 2 - ubound.y;
g2d.drawString(promptMsg, cx, cy);
}
} | #vulnerable code
void drawMessage(Graphics2D g2d) {
if (promptMsg == null) {
return;
}
g2d.setFont(fontMsg);
g2d.setColor(new Color(1f, 1f, 1f, 1));
int sw = g2d.getFontMetrics().stringWidth(promptMsg);
int sh = g2d.getFontMetrics().getMaxAscent();
Rectangle ubound = (new ScreenUnion()).getBounds();
for (int i = 0; i < Screen.getNumberScreens(); i++) {
Rectangle bound = Screen.getBounds(i);
int cx = bound.x + (bound.width - sw) / 2 - ubound.x;
int cy = bound.y + (bound.height - sh) / 2 - ubound.y;
g2d.drawString(promptMsg, cx, cy);
}
}
#location 12
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String[] args) {
System.out.println("********** Running Sikulix.main");
int dl = RunTime.checkArgs(args, RunTime.Type.API);
if (dl > -1) {
testNumber = dl;
Debug.on(3);
}
rt = RunTime.get();
testNumber = rt.getOptionNumber("testing.test", -1);
if (testNumber > -1) {
rt = RunTime.get();
if (!rt.testing) {
rt.show();
rt.testing = true;
}
Tests.runTest(testNumber);
System.exit(1);
} else {
rt = RunTime.get();
Debug.on(3);
String jythonJar = rt.SikuliLocalRepo + rt.SikuliJythonMaven;
log(0, "%s", rt.fSxBaseJar);
log(0, jythonJar);
rt.addToClasspath(jythonJar);
//addFromProject("API", "sikulixapi-1.1.0.jar");
// JythonHelper.get().addSysPath("/Users/raimundhocke/SikuliX/SikuliX-2014/API/target/classes/Lib");
//rt.dumpClassPath();
//Debug.on(4);
SikulixForJython.get();
String stuff = rt.resourceListAsString("Lib/sikuli", null);
if (rt.runningWinApp) {
popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName());
try {
Screen scr = new Screen();
scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3);
} catch (Exception ex) {
popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName());
}
popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName());
System.exit(1);
}
rt.terminate(1,"Sikulix::main: nothing to test");
}
} | #vulnerable code
public static void main(String[] args) {
System.out.println("********** Running Sikulix.main");
int dl = RunTime.checkArgs(args, RunTime.Type.API);
if (dl > -1) {
testNumber = dl;
Debug.on(3);
}
rt = RunTime.get();
testNumber = rt.getOptionNumber("testing.test", -1);
if (testNumber > -1) {
rt = RunTime.get();
if (!rt.testing) {
rt.show();
rt.testing = true;
}
Tests.runTest(testNumber);
System.exit(1);
} else {
rt = RunTime.get();
Debug.on(3);
if (rt.runningWinApp) {
popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName());
try {
Screen scr = new Screen();
scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3);
} catch (Exception ex) {
popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName());
}
popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName());
System.exit(1);
}
rt.terminate(1,"Sikulix::main: nothing to test");
}
}
#location 30
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public boolean reparse() {
File temp = null;
Element e = this.getDocument().getDefaultRootElement();
if (e.getEndOffset() - e.getStartOffset() == 1) {
return true;
}
if ((temp = reparseBefore()) != null) {
if (reparseAfter(temp)) {
updateDocumentListeners();
return true;
}
}
return false;
} | #vulnerable code
public boolean reparse() {
File temp = FileManager.createTempFile("py");
Element e = this.getDocument().getDefaultRootElement();
if (e.getEndOffset() - e.getStartOffset() == 1) {
return true;
}
try {
writeFile(temp.getAbsolutePath());
this.read(new BufferedReader(new InputStreamReader(new FileInputStream(temp), "UTF8")), null);
updateDocumentListeners();
return true;
} catch (IOException ex) {
}
return false;
}
#location 9
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void runscript(String[] args) {
if (isRunningScript) {
log(-1, "can run only one script at a time!");
return;
}
IScriptRunner currentRunner = null;
if (args != null && args.length > 1 && args[0].startsWith("-testSetup")) {
currentRunner = getRunner(null, args[1]);
if (currentRunner == null) {
args[0] = null;
} else {
String[] stmts = new String[0];
if (args.length > 2) {
stmts = new String[args.length - 2];
for (int i = 0; i < stmts.length; i++) {
stmts[i] = args[i+2];
}
}
if (0 != currentRunner.runScript(null, null, stmts, null)) {
args[0] = null;
}
}
isRunningScript = false;
return;
}
runScripts = Runner.evalArgs(args);
isRunningScript = true;
if (runTime.runningInteractive) {
int exitCode = 0;
if (currentRunner == null) {
String givenRunnerName = runTime.interactiveRunner;
if (givenRunnerName == null) {
currentRunner = getRunner(null, Runner.RDEFAULT);
} else {
currentRunner = getRunner(null, givenRunnerName);
}
}
if (currentRunner == null) {
System.exit(1);
}
exitCode = currentRunner.runInteractive(runTime.getSikuliArgs());
currentRunner.close();
Sikulix.endNormal(exitCode);
}
if (runScripts == null) {
runTime.terminate(1, "option -r without any script");
}
if (runScripts.length > 0) {
String scriptName = runScripts[0];
if (scriptName != null && !scriptName.isEmpty() && scriptName.startsWith("git*")) {
run(scriptName, runTime.getSikuliArgs());
return;
}
}
if (runScripts != null && runScripts.length > 0) {
int exitCode = 0;
runAsTest = runTime.runningTests;
for (String givenScriptName : runScripts) {
if (lastReturnCode == -1) {
log(lvl, "Exit code -1: Terminating multi-script-run");
break;
}
exitCode = new RunBox(givenScriptName, runTime.getSikuliArgs(), runAsTest).run();
lastReturnCode = exitCode;
}
System.exit(exitCode);
}
} | #vulnerable code
public static void runscript(String[] args) {
if (isRunningScript) {
log(-1, "can run only one script at a time!");
return;
}
IScriptRunner currentRunner = null;
if (args != null && args.length > 1 && args[0].startsWith("-testSetup")) {
currentRunner = getRunner(null, args[1]);
if (currentRunner == null) {
args[0] = null;
} else {
String[] stmts = new String[0];
if (args.length > 2) {
stmts = new String[args.length - 2];
for (int i = 0; i < stmts.length; i++) {
stmts[i] = args[i+2];
}
}
if (0 != currentRunner.runScript(null, null, stmts, null)) {
args[0] = null;
}
}
isRunningScript = false;
return;
}
runScripts = Runner.evalArgs(args);
isRunningScript = true;
if (runTime.runningInteractive) {
int exitCode = 0;
if (currentRunner == null) {
String givenRunnerName = runTime.interactiveRunner;
if (givenRunnerName == null) {
currentRunner = getRunner(null, Runner.RDEFAULT);
} else {
currentRunner = getRunner(null, givenRunnerName);
}
}
if (currentRunner == null) {
System.exit(1);
}
exitCode = currentRunner.runInteractive(runTime.getSikuliArgs());
currentRunner.close();
Sikulix.endNormal(exitCode);
}
if (runScripts.length > 0) {
String scriptName = runScripts[0];
if (scriptName != null && !scriptName.isEmpty() && scriptName.startsWith("git*")) {
run(scriptName, runTime.getSikuliArgs());
return;
}
}
if (runScripts != null && runScripts.length > 0) {
int exitCode = 0;
runAsTest = runTime.runningTests;
for (String givenScriptName : runScripts) {
if (lastReturnCode == -1) {
log(lvl, "Exit code -1: Terminating multi-script-run");
break;
}
exitCode = new RunBox(givenScriptName, runTime.getSikuliArgs(), runAsTest).run();
lastReturnCode = exitCode;
}
System.exit(exitCode);
}
}
#location 51
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static <T> List<T> queryObjectListSQL(String poolName, String sql, Class<T> type, Object[] params) {
List<T> returnList = null;
try {
BeanListHandler<T> resultSetHandler = new BeanListHandler<T>(type);
returnList = new QueryRunner(DB_CONNECTION_MANAGER.getDataSource(poolName)).query(sql, resultSetHandler, params);
} catch (Exception e) {
logger.error(QUERY_EXCEPTION_MESSAGE, e);
}
return returnList;
} | #vulnerable code
public static <T> List<T> queryObjectListSQL(String poolName, String sql, Class<T> type, Object[] params) {
List<T> returnList = null;
Connection con = null;
try {
con = DB_CONNECTION_MANAGER.getConnection(poolName);
if (con == null) {
throw new ConnectionException(poolName);
}
con.setAutoCommit(false);
BeanListHandler<T> resultSetHandler = new BeanListHandler<T>(type);
returnList = new QueryRunner().query(con, sql, resultSetHandler, params);
con.commit();
} catch (Exception e) {
logger.error(QUERY_EXCEPTION_MESSAGE, e);
try {
con.rollback();
} catch (SQLException e2) {
logger.error(ROLLBACK_EXCEPTION_MESSAGE, e2);
}
} finally {
DB_CONNECTION_MANAGER.freeConnection(con);
}
return returnList;
}
#location 25
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static <T> T querySingleObjectSQL(String poolName, String sql, Class<T> type, Object[] params) {
T returnObject = null;
try {
BeanHandler<T> resultSetHandler = new BeanHandler<T>(type);
returnObject = new QueryRunner(DB_CONNECTION_MANAGER.getDataSource(poolName)).query(sql, resultSetHandler, params);
} catch (Exception e) {
logger.error(QUERY_EXCEPTION_MESSAGE, e);
}
return returnObject;
} | #vulnerable code
public static <T> T querySingleObjectSQL(String poolName, String sql, Class<T> type, Object[] params) {
T returnObject = null;
Connection con = null;
try {
con = DB_CONNECTION_MANAGER.getConnection(poolName);
if (con == null) {
throw new ConnectionException(poolName);
}
con.setAutoCommit(false);
BeanHandler<T> resultSetHandler = new BeanHandler<T>(type);
returnObject = new QueryRunner().query(con, sql, resultSetHandler, params);
con.commit();
} catch (Exception e) {
logger.error(QUERY_EXCEPTION_MESSAGE, e);
try {
con.rollback();
} catch (SQLException e2) {
logger.error(ROLLBACK_EXCEPTION_MESSAGE, e2);
}
} finally {
DB_CONNECTION_MANAGER.freeConnection(con);
}
return returnObject;
}
#location 25
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
long getNextSendIndex() {
// Fast path
if (this.inflights.isEmpty()) {
return this.nextIndex;
}
// Too many in-flight requests.
if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) {
return -1L;
}
// Last request should be a AppendEntries request and has some entries.
if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) {
return this.rpcInFly.startIndex + this.rpcInFly.count;
}
return -1L;
} | #vulnerable code
void installSnapshot() {
if (this.state == State.Snapshot) {
LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId());
this.id.unlock();
return;
}
boolean doUnlock = true;
try {
Requires.requireTrue(this.reader == null,
"Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(),
this.state);
this.reader = this.options.getSnapshotStorage().open();
if (this.reader == null) {
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot"));
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final String uri = this.reader.generateURIForCopy();
if (uri == null) {
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader"));
releaseReader();
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final RaftOutter.SnapshotMeta meta = this.reader.load();
if (meta == null) {
final String snapshotPath = this.reader.getPath();
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath));
releaseReader();
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder();
rb.setTerm(this.options.getTerm());
rb.setGroupId(this.options.getGroupId());
rb.setServerId(this.options.getServerId().toString());
rb.setPeerId(this.options.getPeerId().toString());
rb.setMeta(meta);
rb.setUri(uri);
this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT;
this.statInfo.lastLogIncluded = meta.getLastIncludedIndex();
this.statInfo.lastTermIncluded = meta.getLastIncludedTerm();
final InstallSnapshotRequest request = rb.build();
this.state = State.Snapshot;
// noinspection NonAtomicOperationOnVolatileField
this.installSnapshotCounter++;
final long monotonicSendTimeMs = Utils.monotonicMs();
final int stateVersion = this.version;
final int seq = getAndIncrementReqSeq();
final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(),
request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() {
@Override
public void run(final Status status) {
onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq,
stateVersion, monotonicSendTimeMs);
}
});
addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture);
} finally {
if (doUnlock) {
this.id.unlock();
}
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
void onRpcReturned(Status status, GetFileResponse response) {
this.lock.lock();
try {
if (this.finished) {
return;
}
if (!status.isOk()) {
// Reset count to make next rpc retry the previous one
this.requestBuilder.setCount(0);
if (status.getCode() == RaftError.ECANCELED.getNumber()) {
if (this.st.isOk()) {
this.st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
// Throttled reading failure does not increase _retry_times
if (status.getCode() != RaftError.EAGAIN.getNumber()
&& ++this.retryTimes >= this.copyOptions.getMaxRetry()) {
if (this.st.isOk()) {
this.st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(),
TimeUnit.MILLISECONDS);
return;
}
this.retryTimes = 0;
Requires.requireNonNull(response, "response");
// Reset count to |real_read_size| to make next rpc get the right offset
if (response.hasReadSize() && response.getReadSize() != 0) {
this.requestBuilder.setCount(response.getReadSize());
}
if (this.outputStream != null) {
try {
response.getData().writeTo(this.outputStream);
} catch (final IOException e) {
LOG.error("Fail to write into file {}", this.destPath);
this.st.setError(RaftError.EIO, RaftError.EIO.name());
this.onFinished();
return;
}
} else {
final byte[] data = response.getData().toByteArray();
this.destBuf.put(data);
}
if (response.getEof()) {
onFinished();
return;
}
} finally {
this.lock.unlock();
}
sendNextRpc();
} | #vulnerable code
void onRpcReturned(Status status, GetFileResponse response) {
lock.lock();
try {
if (this.finished) {
return;
}
if (!status.isOk()) {
// Reset count to make next rpc retry the previous one
requestBuilder.setCount(0);
if (status.getCode() == RaftError.ECANCELED.getNumber()) {
if (st.isOk()) {
st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
// Throttled reading failure does not increase _retry_times
if (status.getCode() != RaftError.EAGAIN.getNumber()
&& ++this.retryTimes >= this.copyOptions.getMaxRetry()) {
if (st.isOk()) {
st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(),
TimeUnit.MILLISECONDS);
return;
}
this.retryTimes = 0;
Requires.requireNonNull(response, "response");
// Reset count to |real_read_size| to make next rpc get the right offset
if (response.hasReadSize() && response.getReadSize() != 0) {
this.requestBuilder.setCount(response.getReadSize());
}
if (outputStream != null) {
try {
response.getData().writeTo(outputStream);
} catch (final IOException e) {
LOG.error("Fail to write into file {}", this.destPath);
st.setError(RaftError.EIO, RaftError.EIO.name());
this.onFinished();
return;
}
} else {
final byte[] data = response.getData().toByteArray();
this.destBuf.put(data);
}
if (response.getEof()) {
onFinished();
return;
}
} finally {
lock.unlock();
}
this.sendNextRpc();
}
#location 35
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public void shutdown(final Closure done) {
List<RepeatedTimer> timers = null;
this.writeLock.lock();
try {
LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state);
if (this.state.compareTo(State.STATE_SHUTTING) < 0) {
NodeManager.getInstance().remove(this);
// If it is leader, set the wakeup_a_candidate with true;
// If it is follower, call on_stop_following in step_down
if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) {
stepDown(this.currTerm, this.state == State.STATE_LEADER,
new Status(RaftError.ESHUTDOWN, "Raft node is going to quit."));
}
this.state = State.STATE_SHUTTING;
// Stop all timers
timers = stopAllTimers();
if (this.readOnlyService != null) {
this.readOnlyService.shutdown();
}
if (this.logManager != null) {
this.logManager.shutdown();
}
if (this.metaStorage != null) {
this.metaStorage.shutdown();
}
if (this.snapshotExecutor != null) {
this.snapshotExecutor.shutdown();
}
if (this.wakingCandidate != null) {
Replicator.stop(this.wakingCandidate);
}
if (this.fsmCaller != null) {
this.fsmCaller.shutdown();
}
if (this.rpcService != null) {
this.rpcService.shutdown();
}
if (this.applyQueue != null) {
Utils.runInThread(() -> {
this.shutdownLatch = new CountDownLatch(1);
this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch);
});
} else {
final int num = GLOBAL_NUM_NODES.decrementAndGet();
LOG.info("The number of active nodes decrement to {}.", num);
}
if (this.timerManager != null) {
this.timerManager.shutdown();
}
}
if (this.state != State.STATE_SHUTDOWN) {
if (done != null) {
this.shutdownContinuations.add(done);
}
return;
}
// This node is down, it's ok to invoke done right now. Don't invoke this
// in place to avoid the dead writeLock issue when done.Run() is going to acquire
// a writeLock which is already held by the caller
if (done != null) {
Utils.runClosureInThread(done);
}
} finally {
this.writeLock.unlock();
// Destroy all timers out of lock
if (timers != null) {
destroyAllTimers(timers);
}
}
} | #vulnerable code
@Override
public void shutdown(final Closure done) {
this.writeLock.lock();
try {
LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state);
if (this.state.compareTo(State.STATE_SHUTTING) < 0) {
NodeManager.getInstance().remove(this);
// If it is leader, set the wakeup_a_candidate with true;
// If it is follower, call on_stop_following in step_down
if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) {
stepDown(this.currTerm, this.state == State.STATE_LEADER,
new Status(RaftError.ESHUTDOWN, "Raft node is going to quit."));
}
this.state = State.STATE_SHUTTING;
// Destroy all timers
if (this.electionTimer != null) {
this.electionTimer.destroy();
}
if (this.voteTimer != null) {
this.voteTimer.destroy();
}
if (this.stepDownTimer != null) {
this.stepDownTimer.destroy();
}
if (this.snapshotTimer != null) {
this.snapshotTimer.destroy();
}
if (this.readOnlyService != null) {
this.readOnlyService.shutdown();
}
if (this.logManager != null) {
this.logManager.shutdown();
}
if (this.metaStorage != null) {
this.metaStorage.shutdown();
}
if (this.snapshotExecutor != null) {
this.snapshotExecutor.shutdown();
}
if (this.wakingCandidate != null) {
Replicator.stop(this.wakingCandidate);
}
if (this.fsmCaller != null) {
this.fsmCaller.shutdown();
}
if (this.rpcService != null) {
this.rpcService.shutdown();
}
if (this.applyQueue != null) {
Utils.runInThread(() -> {
this.shutdownLatch = new CountDownLatch(1);
this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch);
});
} else {
final int num = GLOBAL_NUM_NODES.decrementAndGet();
LOG.info("The number of active nodes decrement to {}.", num);
}
if (this.timerManager != null) {
this.timerManager.shutdown();
}
}
if (this.state != State.STATE_SHUTDOWN) {
if (done != null) {
this.shutdownContinuations.add(done);
}
return;
}
// This node is down, it's ok to invoke done right now. Don't invoke this
// in place to avoid the dead writeLock issue when done.Run() is going to acquire
// a writeLock which is already held by the caller
if (done != null) {
Utils.runClosureInThread(done);
}
} finally {
this.writeLock.unlock();
}
}
#location 26
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
void onRpcReturned(Status status, GetFileResponse response) {
this.lock.lock();
try {
if (this.finished) {
return;
}
if (!status.isOk()) {
// Reset count to make next rpc retry the previous one
this.requestBuilder.setCount(0);
if (status.getCode() == RaftError.ECANCELED.getNumber()) {
if (this.st.isOk()) {
this.st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
// Throttled reading failure does not increase _retry_times
if (status.getCode() != RaftError.EAGAIN.getNumber()
&& ++this.retryTimes >= this.copyOptions.getMaxRetry()) {
if (this.st.isOk()) {
this.st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(),
TimeUnit.MILLISECONDS);
return;
}
this.retryTimes = 0;
Requires.requireNonNull(response, "response");
// Reset count to |real_read_size| to make next rpc get the right offset
if (response.hasReadSize() && response.getReadSize() != 0) {
this.requestBuilder.setCount(response.getReadSize());
}
if (this.outputStream != null) {
try {
response.getData().writeTo(this.outputStream);
} catch (final IOException e) {
LOG.error("Fail to write into file {}", this.destPath);
this.st.setError(RaftError.EIO, RaftError.EIO.name());
this.onFinished();
return;
}
} else {
final byte[] data = response.getData().toByteArray();
this.destBuf.put(data);
}
if (response.getEof()) {
onFinished();
return;
}
} finally {
this.lock.unlock();
}
sendNextRpc();
} | #vulnerable code
void onRpcReturned(Status status, GetFileResponse response) {
lock.lock();
try {
if (this.finished) {
return;
}
if (!status.isOk()) {
// Reset count to make next rpc retry the previous one
requestBuilder.setCount(0);
if (status.getCode() == RaftError.ECANCELED.getNumber()) {
if (st.isOk()) {
st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
// Throttled reading failure does not increase _retry_times
if (status.getCode() != RaftError.EAGAIN.getNumber()
&& ++this.retryTimes >= this.copyOptions.getMaxRetry()) {
if (st.isOk()) {
st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(),
TimeUnit.MILLISECONDS);
return;
}
this.retryTimes = 0;
Requires.requireNonNull(response, "response");
// Reset count to |real_read_size| to make next rpc get the right offset
if (response.hasReadSize() && response.getReadSize() != 0) {
this.requestBuilder.setCount(response.getReadSize());
}
if (outputStream != null) {
try {
response.getData().writeTo(outputStream);
} catch (final IOException e) {
LOG.error("Fail to write into file {}", this.destPath);
st.setError(RaftError.EIO, RaftError.EIO.name());
this.onFinished();
return;
}
} else {
final byte[] data = response.getData().toByteArray();
this.destBuf.put(data);
}
if (response.getEof()) {
onFinished();
return;
}
} finally {
lock.unlock();
}
this.sendNextRpc();
}
#location 57
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public boolean disconnect(final Endpoint endpoint) {
final RpcClient rc = this.rpcClient;
if (rc == null) {
return true;
}
LOG.info("Disconnect from {}.", endpoint);
rc.closeConnection(endpoint.toString());
return true;
} | #vulnerable code
@Override
public boolean disconnect(final Endpoint endpoint) {
LOG.info("Disconnect from {}", endpoint);
this.rpcClient.closeConnection(endpoint.toString());
return true;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public void addStateListener(final long regionId, final StateListener listener) {
this.stateListenerContainer.addStateListener(regionId, listener);
} | #vulnerable code
@Override
public void addStateListener(final long regionId, final StateListener listener) {
checkState();
if (this.storeEngine == null) {
throw new IllegalStateException("current node do not have store engine");
}
final RegionEngine regionEngine = this.storeEngine.getRegionEngine(regionId);
if (regionEngine == null) {
throw new IllegalStateException("current node do not have this region engine[" + regionId + "]");
}
regionEngine.getFsm().addStateListener(listener);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request,
final AppendEntriesResponse response, final long rpcSendTime) {
if (id == null) {
// replicator already was destroyed.
return;
}
final long startTimeMs = Utils.nowMs();
Replicator r;
if ((r = (Replicator) id.lock()) == null) {
return;
}
boolean doUnlock = true;
try {
final boolean isLogDebugEnabled = LOG.isDebugEnabled();
StringBuilder sb = null;
if (isLogDebugEnabled) {
sb = new StringBuilder("Node "). //
append(r.options.getGroupId()).append(":").append(r.options.getServerId()). //
append(" received HeartbeatResponse from "). //
append(r.options.getPeerId()). //
append(" prevLogIndex=").append(request.getPrevLogIndex()). //
append(" prevLogTerm=").append(request.getPrevLogTerm());
}
if (!status.isOk()) {
if (isLogDebugEnabled) {
sb.append(" fail, sleep.");
LOG.debug(sb.toString());
}
r.state = State.Probe;
notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status);
if (++r.consecutiveErrorTimes % 10 == 0) {
LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(),
r.consecutiveErrorTimes, status);
}
r.startHeartbeatTimer(startTimeMs);
return;
}
r.consecutiveErrorTimes = 0;
if (response.getTerm() > r.options.getTerm()) {
if (isLogDebugEnabled) {
sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ")
.append(r.options.getTerm());
LOG.debug(sb.toString());
}
final NodeImpl node = r.options.getNode();
r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true);
r.destroy();
node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE,
"Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId()));
return;
}
if (!response.getSuccess() && response.hasLastLogIndex()) {
if (isLogDebugEnabled) {
sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ")
.append(response.getLastLogIndex());
LOG.debug(sb.toString());
}
LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId());
doUnlock = false;
r.sendEmptyEntries(false);
r.startHeartbeatTimer(startTimeMs);
return;
}
if (isLogDebugEnabled) {
LOG.debug(sb.toString());
}
if (rpcSendTime > r.lastRpcSendTimestamp) {
r.lastRpcSendTimestamp = rpcSendTime;
}
r.startHeartbeatTimer(startTimeMs);
} finally {
if (doUnlock) {
id.unlock();
}
}
} | #vulnerable code
static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request,
final AppendEntriesResponse response, final long rpcSendTime) {
if (id == null) {
// replicator already was destroyed.
return;
}
final long startTimeMs = Utils.nowMs();
Replicator r;
if ((r = (Replicator) id.lock()) == null) {
return;
}
boolean doUnlock = true;
try {
final boolean isLogDebugEnabled = LOG.isDebugEnabled();
StringBuilder sb = null;
if (isLogDebugEnabled) {
sb = new StringBuilder("Node "). //
append(r.options.getGroupId()).append(":").append(r.options.getServerId()). //
append(" received HeartbeatResponse from "). //
append(r.options.getPeerId()). //
append(" prevLogIndex=").append(request.getPrevLogIndex()). //
append(" prevLogTerm=").append(request.getPrevLogTerm());
}
if (!status.isOk()) {
if (isLogDebugEnabled) {
sb.append(" fail, sleep.");
LOG.debug(sb.toString());
}
r.state = State.Probe;
if (++r.consecutiveErrorTimes % 10 == 0) {
LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(),
r.consecutiveErrorTimes, status);
}
r.startHeartbeatTimer(startTimeMs);
return;
}
r.consecutiveErrorTimes = 0;
if (response.getTerm() > r.options.getTerm()) {
if (isLogDebugEnabled) {
sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ")
.append(r.options.getTerm());
LOG.debug(sb.toString());
}
final NodeImpl node = r.options.getNode();
r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true);
r.destroy();
node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE,
"Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId()));
return;
}
if (!response.getSuccess() && response.hasLastLogIndex()) {
if (isLogDebugEnabled) {
sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ")
.append(response.getLastLogIndex());
LOG.debug(sb.toString());
}
LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId());
doUnlock = false;
r.sendEmptyEntries(false);
r.startHeartbeatTimer(startTimeMs);
return;
}
if (isLogDebugEnabled) {
LOG.debug(sb.toString());
}
if (rpcSendTime > r.lastRpcSendTimestamp) {
r.lastRpcSendTimestamp = rpcSendTime;
}
r.startHeartbeatTimer(startTimeMs);
} finally {
if (doUnlock) {
id.unlock();
}
}
}
#location 59
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static ThreadId start(final ReplicatorOptions opts, final RaftOptions raftOptions) {
if (opts.getLogManager() == null || opts.getBallotBox() == null || opts.getNode() == null) {
throw new IllegalArgumentException("Invalid ReplicatorOptions.");
}
final Replicator r = new Replicator(opts, raftOptions);
if (!r.rpcService.connect(opts.getPeerId().getEndpoint())) {
LOG.error("Fail to init sending channel to {}", opts.getPeerId());
// Return and it will be retried later.
return null;
}
// Register replicator metric set.
final MetricRegistry metricRegistry = opts.getNode().getNodeMetrics().getMetricRegistry();
if (metricRegistry != null) {
try {
final String replicatorMetricName = getReplicatorMetricName(opts);
if (!metricRegistry.getNames().contains(replicatorMetricName)) {
metricRegistry.register(replicatorMetricName, new ReplicatorMetricSet(opts, r));
}
} catch (final IllegalArgumentException e) {
// ignore
}
}
// Start replication
r.id = new ThreadId(r, r);
r.id.lock();
notifyReplicatorStatusListener(r, ReplicatorEvent.CREATED);
LOG.info("Replicator={}@{} is started", r.id, r.options.getPeerId());
r.catchUpClosure = null;
r.lastRpcSendTimestamp = Utils.monotonicMs();
r.startHeartbeatTimer(Utils.nowMs());
// id.unlock in sendEmptyEntries
r.sendEmptyEntries(false);
return r.id;
} | #vulnerable code
public static ThreadId start(final ReplicatorOptions opts, final RaftOptions raftOptions) {
if (opts.getLogManager() == null || opts.getBallotBox() == null || opts.getNode() == null) {
throw new IllegalArgumentException("Invalid ReplicatorOptions.");
}
final Replicator r = new Replicator(opts, raftOptions);
if (!r.rpcService.connect(opts.getPeerId().getEndpoint())) {
LOG.error("Fail to init sending channel to {}", opts.getPeerId());
// Return and it will be retried later.
return null;
}
// Register replicator metric set.
final MetricRegistry metricRegistry = opts.getNode().getNodeMetrics().getMetricRegistry();
if (metricRegistry != null) {
try {
final String replicatorMetricName = getReplicatorMetricName(opts);
if (!metricRegistry.getNames().contains(replicatorMetricName)) {
metricRegistry.register(replicatorMetricName, new ReplicatorMetricSet(opts, r));
}
} catch (final IllegalArgumentException e) {
// ignore
}
}
// Start replication
r.id = new ThreadId(r, r);
r.id.lock();
LOG.info("Replicator={}@{} is started", r.id, r.options.getPeerId());
r.catchUpClosure = null;
r.lastRpcSendTimestamp = Utils.monotonicMs();
r.startHeartbeatTimer(Utils.nowMs());
// id.unlock in sendEmptyEntries
r.sendEmptyEntries(false);
return r.id;
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public <T extends Message> Future<Message> invokeWithDone(final Endpoint endpoint, final Message request,
final InvokeContext ctx,
final RpcResponseClosure<T> done, final int timeoutMs,
final Executor rpcExecutor) {
final RpcClient rc = this.rpcClient;
final FutureImpl<Message> future = new FutureImpl<>();
try {
if (rc == null) {
future.failure(new IllegalStateException("Client service is uninitialized."));
// should be in another thread to avoid dead locking.
Utils.runClosureInThread(done, new Status(RaftError.EINTERNAL, "Client service is uninitialized."));
return future;
}
final Url rpcUrl = this.rpcAddressParser.parse(endpoint.toString());
rc.invokeWithCallback(rpcUrl, request, ctx, new InvokeCallback() {
@SuppressWarnings("unchecked")
@Override
public void onResponse(final Object result) {
if (future.isCancelled()) {
onCanceled(request, done);
return;
}
Status status = Status.OK();
if (result instanceof ErrorResponse) {
final ErrorResponse eResp = (ErrorResponse) result;
status = new Status();
status.setCode(eResp.getErrorCode());
if (eResp.hasErrorMsg()) {
status.setErrorMsg(eResp.getErrorMsg());
}
} else {
if (done != null) {
done.setResponse((T) result);
}
}
if (done != null) {
try {
done.run(status);
} catch (final Throwable t) {
LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
}
}
if (!future.isDone()) {
future.setResult((Message) result);
}
}
@Override
public void onException(final Throwable e) {
if (future.isCancelled()) {
onCanceled(request, done);
return;
}
if (done != null) {
try {
done.run(new Status(e instanceof InvokeTimeoutException ? RaftError.ETIMEDOUT
: RaftError.EINTERNAL, "RPC exception:" + e.getMessage()));
} catch (final Throwable t) {
LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
}
}
if (!future.isDone()) {
future.failure(e);
}
}
@Override
public Executor getExecutor() {
return rpcExecutor != null ? rpcExecutor : AbstractBoltClientService.this.rpcExecutor;
}
}, timeoutMs <= 0 ? this.rpcOptions.getRpcDefaultTimeout() : timeoutMs);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
future.failure(e);
// should be in another thread to avoid dead locking.
Utils.runClosureInThread(done, new Status(RaftError.EINTR, "Sending rpc was interrupted"));
} catch (final RemotingException e) {
future.failure(e);
// should be in another thread to avoid dead locking.
Utils.runClosureInThread(done,
new Status(RaftError.EINTERNAL, "Fail to send a RPC request:" + e.getMessage()));
}
return future;
} | #vulnerable code
public <T extends Message> Future<Message> invokeWithDone(final Endpoint endpoint, final Message request,
final InvokeContext ctx,
final RpcResponseClosure<T> done, final int timeoutMs,
final Executor rpcExecutor) {
final FutureImpl<Message> future = new FutureImpl<>();
try {
final Url rpcUrl = this.rpcAddressParser.parse(endpoint.toString());
this.rpcClient.invokeWithCallback(rpcUrl, request, ctx, new InvokeCallback() {
@SuppressWarnings("unchecked")
@Override
public void onResponse(final Object result) {
if (future.isCancelled()) {
onCanceled(request, done);
return;
}
Status status = Status.OK();
if (result instanceof ErrorResponse) {
final ErrorResponse eResp = (ErrorResponse) result;
status = new Status();
status.setCode(eResp.getErrorCode());
if (eResp.hasErrorMsg()) {
status.setErrorMsg(eResp.getErrorMsg());
}
} else {
if (done != null) {
done.setResponse((T) result);
}
}
if (done != null) {
try {
done.run(status);
} catch (final Throwable t) {
LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
}
}
if (!future.isDone()) {
future.setResult((Message) result);
}
}
@Override
public void onException(final Throwable e) {
if (future.isCancelled()) {
onCanceled(request, done);
return;
}
if (done != null) {
try {
done.run(new Status(e instanceof InvokeTimeoutException ? RaftError.ETIMEDOUT
: RaftError.EINTERNAL, "RPC exception:" + e.getMessage()));
} catch (final Throwable t) {
LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
}
}
if (!future.isDone()) {
future.failure(e);
}
}
@Override
public Executor getExecutor() {
return rpcExecutor != null ? rpcExecutor : AbstractBoltClientService.this.rpcExecutor;
}
}, timeoutMs <= 0 ? this.rpcOptions.getRpcDefaultTimeout() : timeoutMs);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
future.failure(e);
// should be in another thread to avoid dead locking.
Utils.runClosureInThread(done, new Status(RaftError.EINTR, "Sending rpc was interrupted"));
} catch (final RemotingException e) {
future.failure(e);
// should be in another thread to avoid dead locking.
Utils.runClosureInThread(done,
new Status(RaftError.EINTERNAL, "Fail to send a RPC request:" + e.getMessage()));
}
return future;
}
#location 65
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
long getNextSendIndex() {
// Fast path
if (this.inflights.isEmpty()) {
return this.nextIndex;
}
// Too many in-flight requests.
if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) {
return -1L;
}
// Last request should be a AppendEntries request and has some entries.
if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) {
return this.rpcInFly.startIndex + this.rpcInFly.count;
}
return -1L;
} | #vulnerable code
void installSnapshot() {
if (this.state == State.Snapshot) {
LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId());
this.id.unlock();
return;
}
boolean doUnlock = true;
try {
Requires.requireTrue(this.reader == null,
"Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(),
this.state);
this.reader = this.options.getSnapshotStorage().open();
if (this.reader == null) {
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot"));
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final String uri = this.reader.generateURIForCopy();
if (uri == null) {
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader"));
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final RaftOutter.SnapshotMeta meta = this.reader.load();
if (meta == null) {
final String snapshotPath = this.reader.getPath();
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath));
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder();
rb.setTerm(this.options.getTerm());
rb.setGroupId(this.options.getGroupId());
rb.setServerId(this.options.getServerId().toString());
rb.setPeerId(this.options.getPeerId().toString());
rb.setMeta(meta);
rb.setUri(uri);
this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT;
this.statInfo.lastLogIncluded = meta.getLastIncludedIndex();
this.statInfo.lastTermIncluded = meta.getLastIncludedTerm();
final InstallSnapshotRequest request = rb.build();
this.state = State.Snapshot;
// noinspection NonAtomicOperationOnVolatileField
this.installSnapshotCounter++;
final long monotonicSendTimeMs = Utils.monotonicMs();
final int stateVersion = this.version;
final int seq = getAndIncrementReqSeq();
final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(),
request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() {
@Override
public void run(final Status status) {
onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq,
stateVersion, monotonicSendTimeMs);
}
});
addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture);
} finally {
if (doUnlock) {
this.id.unlock();
}
}
}
#location 55
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
long getNextSendIndex() {
// Fast path
if (this.inflights.isEmpty()) {
return this.nextIndex;
}
// Too many in-flight requests.
if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) {
return -1L;
}
// Last request should be a AppendEntries request and has some entries.
if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) {
return this.rpcInFly.startIndex + this.rpcInFly.count;
}
return -1L;
} | #vulnerable code
void destroy() {
final ThreadId savedId = this.id;
LOG.info("Replicator {} is going to quit", savedId);
this.id = null;
releaseReader();
// Unregister replicator metric set
if (this.options.getNode().getNodeMetrics().isEnabled()) {
this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options));
}
this.state = State.Destroyed;
notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED);
savedId.unlockAndDestroy();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
long getNextSendIndex() {
// Fast path
if (this.inflights.isEmpty()) {
return this.nextIndex;
}
// Too many in-flight requests.
if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) {
return -1L;
}
// Last request should be a AppendEntries request and has some entries.
if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) {
return this.rpcInFly.startIndex + this.rpcInFly.count;
}
return -1L;
} | #vulnerable code
void destroy() {
final ThreadId savedId = this.id;
LOG.info("Replicator {} is going to quit", savedId);
this.id = null;
releaseReader();
// Unregister replicator metric set
if (this.options.getNode().getNodeMetrics().isEnabled()) {
this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options));
}
this.state = State.Destroyed;
notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED);
savedId.unlockAndDestroy();
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
long getNextSendIndex() {
// Fast path
if (this.inflights.isEmpty()) {
return this.nextIndex;
}
// Too many in-flight requests.
if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) {
return -1L;
}
// Last request should be a AppendEntries request and has some entries.
if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) {
return this.rpcInFly.startIndex + this.rpcInFly.count;
}
return -1L;
} | #vulnerable code
void destroy() {
final ThreadId savedId = this.id;
LOG.info("Replicator {} is going to quit", savedId);
this.id = null;
if (this.reader != null) {
Utils.closeQuietly(this.reader);
this.reader = null;
}
// Unregister replicator metric set
if (this.options.getNode().getNodeMetrics().getMetricRegistry() != null) {
this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options));
}
this.state = State.Destroyed;
savedId.unlockAndDestroy();
}
#location 14
#vulnerability type INTERFACE_NOT_THREAD_SAFE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
void onRpcReturned(Status status, GetFileResponse response) {
this.lock.lock();
try {
if (this.finished) {
return;
}
if (!status.isOk()) {
// Reset count to make next rpc retry the previous one
this.requestBuilder.setCount(0);
if (status.getCode() == RaftError.ECANCELED.getNumber()) {
if (this.st.isOk()) {
this.st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
// Throttled reading failure does not increase _retry_times
if (status.getCode() != RaftError.EAGAIN.getNumber()
&& ++this.retryTimes >= this.copyOptions.getMaxRetry()) {
if (this.st.isOk()) {
this.st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(),
TimeUnit.MILLISECONDS);
return;
}
this.retryTimes = 0;
Requires.requireNonNull(response, "response");
// Reset count to |real_read_size| to make next rpc get the right offset
if (response.hasReadSize() && response.getReadSize() != 0) {
this.requestBuilder.setCount(response.getReadSize());
}
if (this.outputStream != null) {
try {
response.getData().writeTo(this.outputStream);
} catch (final IOException e) {
LOG.error("Fail to write into file {}", this.destPath);
this.st.setError(RaftError.EIO, RaftError.EIO.name());
this.onFinished();
return;
}
} else {
final byte[] data = response.getData().toByteArray();
this.destBuf.put(data);
}
if (response.getEof()) {
onFinished();
return;
}
} finally {
this.lock.unlock();
}
sendNextRpc();
} | #vulnerable code
void sendNextRpc() {
this.timer = null;
final long offset = requestBuilder.getOffset() + requestBuilder.getCount();
final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE;
this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true);
this.lock.lock();
try {
if (this.finished) {
return;
}
// throttle
long newMaxCount = maxCount;
if (this.snapshotThrottle != null) {
newMaxCount = snapshotThrottle.throttledByThroughput(maxCount);
if (newMaxCount == 0) {
// Reset count to make next rpc retry the previous one
this.requestBuilder.setCount(0);
this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(),
TimeUnit.MILLISECONDS);
return;
}
}
this.requestBuilder.setCount(newMaxCount);
LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint);
this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(),
this.copyOptions.getTimeoutMs(), done);
} finally {
lock.unlock();
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
long getNextSendIndex() {
// Fast path
if (this.inflights.isEmpty()) {
return this.nextIndex;
}
// Too many in-flight requests.
if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) {
return -1L;
}
// Last request should be a AppendEntries request and has some entries.
if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) {
return this.rpcInFly.startIndex + this.rpcInFly.count;
}
return -1L;
} | #vulnerable code
void installSnapshot() {
if (this.state == State.Snapshot) {
LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId());
this.id.unlock();
return;
}
boolean doUnlock = true;
try {
Requires.requireTrue(this.reader == null,
"Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(),
this.state);
this.reader = this.options.getSnapshotStorage().open();
if (this.reader == null) {
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot"));
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final String uri = this.reader.generateURIForCopy();
if (uri == null) {
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader"));
releaseReader();
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final RaftOutter.SnapshotMeta meta = this.reader.load();
if (meta == null) {
final String snapshotPath = this.reader.getPath();
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath));
releaseReader();
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder();
rb.setTerm(this.options.getTerm());
rb.setGroupId(this.options.getGroupId());
rb.setServerId(this.options.getServerId().toString());
rb.setPeerId(this.options.getPeerId().toString());
rb.setMeta(meta);
rb.setUri(uri);
this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT;
this.statInfo.lastLogIncluded = meta.getLastIncludedIndex();
this.statInfo.lastTermIncluded = meta.getLastIncludedTerm();
final InstallSnapshotRequest request = rb.build();
this.state = State.Snapshot;
// noinspection NonAtomicOperationOnVolatileField
this.installSnapshotCounter++;
final long monotonicSendTimeMs = Utils.monotonicMs();
final int stateVersion = this.version;
final int seq = getAndIncrementReqSeq();
final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(),
request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() {
@Override
public void run(final Status status) {
onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq,
stateVersion, monotonicSendTimeMs);
}
});
addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture);
} finally {
if (doUnlock) {
this.id.unlock();
}
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
long getNextSendIndex() {
// Fast path
if (this.inflights.isEmpty()) {
return this.nextIndex;
}
// Too many in-flight requests.
if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) {
return -1L;
}
// Last request should be a AppendEntries request and has some entries.
if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) {
return this.rpcInFly.startIndex + this.rpcInFly.count;
}
return -1L;
} | #vulnerable code
void installSnapshot() {
if (this.state == State.Snapshot) {
LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId());
this.id.unlock();
return;
}
boolean doUnlock = true;
try {
Requires.requireTrue(this.reader == null,
"Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(),
this.state);
this.reader = this.options.getSnapshotStorage().open();
if (this.reader == null) {
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot"));
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final String uri = this.reader.generateURIForCopy();
if (uri == null) {
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader"));
releaseReader();
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final RaftOutter.SnapshotMeta meta = this.reader.load();
if (meta == null) {
final String snapshotPath = this.reader.getPath();
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath));
releaseReader();
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder();
rb.setTerm(this.options.getTerm());
rb.setGroupId(this.options.getGroupId());
rb.setServerId(this.options.getServerId().toString());
rb.setPeerId(this.options.getPeerId().toString());
rb.setMeta(meta);
rb.setUri(uri);
this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT;
this.statInfo.lastLogIncluded = meta.getLastIncludedIndex();
this.statInfo.lastTermIncluded = meta.getLastIncludedTerm();
final InstallSnapshotRequest request = rb.build();
this.state = State.Snapshot;
// noinspection NonAtomicOperationOnVolatileField
this.installSnapshotCounter++;
final long monotonicSendTimeMs = Utils.monotonicMs();
final int stateVersion = this.version;
final int seq = getAndIncrementReqSeq();
final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(),
request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() {
@Override
public void run(final Status status) {
onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq,
stateVersion, monotonicSendTimeMs);
}
});
addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture);
} finally {
if (doUnlock) {
this.id.unlock();
}
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
long getNextSendIndex() {
// Fast path
if (this.inflights.isEmpty()) {
return this.nextIndex;
}
// Too many in-flight requests.
if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) {
return -1L;
}
// Last request should be a AppendEntries request and has some entries.
if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) {
return this.rpcInFly.startIndex + this.rpcInFly.count;
}
return -1L;
} | #vulnerable code
void sendEntries() {
boolean doUnlock = true;
try {
long prevSendIndex = -1;
while (true) {
final long nextSendingIndex = getNextSendIndex();
if (nextSendingIndex > prevSendIndex) {
if (sendEntries(nextSendingIndex)) {
prevSendIndex = nextSendingIndex;
} else {
doUnlock = false;
// id already unlock in sendEntries when it returns false.
break;
}
} else {
break;
}
}
} finally {
if (doUnlock) {
this.id.unlock();
}
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request,
final AppendEntriesResponse response, final long rpcSendTime) {
if (id == null) {
// replicator already was destroyed.
return;
}
final long startTimeMs = Utils.nowMs();
Replicator r;
if ((r = (Replicator) id.lock()) == null) {
return;
}
boolean doUnlock = true;
try {
final boolean isLogDebugEnabled = LOG.isDebugEnabled();
StringBuilder sb = null;
if (isLogDebugEnabled) {
sb = new StringBuilder("Node "). //
append(r.options.getGroupId()).append(":").append(r.options.getServerId()). //
append(" received HeartbeatResponse from "). //
append(r.options.getPeerId()). //
append(" prevLogIndex=").append(request.getPrevLogIndex()). //
append(" prevLogTerm=").append(request.getPrevLogTerm());
}
if (!status.isOk()) {
if (isLogDebugEnabled) {
sb.append(" fail, sleep.");
LOG.debug(sb.toString());
}
r.state = State.Probe;
notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status);
if (++r.consecutiveErrorTimes % 10 == 0) {
LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(),
r.consecutiveErrorTimes, status);
}
r.startHeartbeatTimer(startTimeMs);
return;
}
r.consecutiveErrorTimes = 0;
if (response.getTerm() > r.options.getTerm()) {
if (isLogDebugEnabled) {
sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ")
.append(r.options.getTerm());
LOG.debug(sb.toString());
}
final NodeImpl node = r.options.getNode();
r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true);
r.destroy();
node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE,
"Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId()));
return;
}
if (!response.getSuccess() && response.hasLastLogIndex()) {
if (isLogDebugEnabled) {
sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ")
.append(response.getLastLogIndex());
LOG.debug(sb.toString());
}
LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId());
doUnlock = false;
r.sendEmptyEntries(false);
r.startHeartbeatTimer(startTimeMs);
return;
}
if (isLogDebugEnabled) {
LOG.debug(sb.toString());
}
if (rpcSendTime > r.lastRpcSendTimestamp) {
r.lastRpcSendTimestamp = rpcSendTime;
}
r.startHeartbeatTimer(startTimeMs);
} finally {
if (doUnlock) {
id.unlock();
}
}
} | #vulnerable code
static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request,
final AppendEntriesResponse response, final long rpcSendTime) {
if (id == null) {
// replicator already was destroyed.
return;
}
final long startTimeMs = Utils.nowMs();
Replicator r;
if ((r = (Replicator) id.lock()) == null) {
return;
}
boolean doUnlock = true;
try {
final boolean isLogDebugEnabled = LOG.isDebugEnabled();
StringBuilder sb = null;
if (isLogDebugEnabled) {
sb = new StringBuilder("Node "). //
append(r.options.getGroupId()).append(":").append(r.options.getServerId()). //
append(" received HeartbeatResponse from "). //
append(r.options.getPeerId()). //
append(" prevLogIndex=").append(request.getPrevLogIndex()). //
append(" prevLogTerm=").append(request.getPrevLogTerm());
}
if (!status.isOk()) {
if (isLogDebugEnabled) {
sb.append(" fail, sleep.");
LOG.debug(sb.toString());
}
r.state = State.Probe;
if (++r.consecutiveErrorTimes % 10 == 0) {
LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(),
r.consecutiveErrorTimes, status);
}
r.startHeartbeatTimer(startTimeMs);
return;
}
r.consecutiveErrorTimes = 0;
if (response.getTerm() > r.options.getTerm()) {
if (isLogDebugEnabled) {
sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ")
.append(r.options.getTerm());
LOG.debug(sb.toString());
}
final NodeImpl node = r.options.getNode();
r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true);
r.destroy();
node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE,
"Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId()));
return;
}
if (!response.getSuccess() && response.hasLastLogIndex()) {
if (isLogDebugEnabled) {
sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ")
.append(response.getLastLogIndex());
LOG.debug(sb.toString());
}
LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId());
doUnlock = false;
r.sendEmptyEntries(false);
r.startHeartbeatTimer(startTimeMs);
return;
}
if (isLogDebugEnabled) {
LOG.debug(sb.toString());
}
if (rpcSendTime > r.lastRpcSendTimestamp) {
r.lastRpcSendTimestamp = rpcSendTime;
}
r.startHeartbeatTimer(startTimeMs);
} finally {
if (doUnlock) {
id.unlock();
}
}
}
#location 47
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
void onRpcReturned(Status status, GetFileResponse response) {
this.lock.lock();
try {
if (this.finished) {
return;
}
if (!status.isOk()) {
// Reset count to make next rpc retry the previous one
this.requestBuilder.setCount(0);
if (status.getCode() == RaftError.ECANCELED.getNumber()) {
if (this.st.isOk()) {
this.st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
// Throttled reading failure does not increase _retry_times
if (status.getCode() != RaftError.EAGAIN.getNumber()
&& ++this.retryTimes >= this.copyOptions.getMaxRetry()) {
if (this.st.isOk()) {
this.st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(),
TimeUnit.MILLISECONDS);
return;
}
this.retryTimes = 0;
Requires.requireNonNull(response, "response");
// Reset count to |real_read_size| to make next rpc get the right offset
if (response.hasReadSize() && response.getReadSize() != 0) {
this.requestBuilder.setCount(response.getReadSize());
}
if (this.outputStream != null) {
try {
response.getData().writeTo(this.outputStream);
} catch (final IOException e) {
LOG.error("Fail to write into file {}", this.destPath);
this.st.setError(RaftError.EIO, RaftError.EIO.name());
this.onFinished();
return;
}
} else {
final byte[] data = response.getData().toByteArray();
this.destBuf.put(data);
}
if (response.getEof()) {
onFinished();
return;
}
} finally {
this.lock.unlock();
}
sendNextRpc();
} | #vulnerable code
void onRpcReturned(Status status, GetFileResponse response) {
lock.lock();
try {
if (this.finished) {
return;
}
if (!status.isOk()) {
// Reset count to make next rpc retry the previous one
requestBuilder.setCount(0);
if (status.getCode() == RaftError.ECANCELED.getNumber()) {
if (st.isOk()) {
st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
// Throttled reading failure does not increase _retry_times
if (status.getCode() != RaftError.EAGAIN.getNumber()
&& ++this.retryTimes >= this.copyOptions.getMaxRetry()) {
if (st.isOk()) {
st.setError(status.getCode(), status.getErrorMsg());
this.onFinished();
return;
}
}
this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(),
TimeUnit.MILLISECONDS);
return;
}
this.retryTimes = 0;
Requires.requireNonNull(response, "response");
// Reset count to |real_read_size| to make next rpc get the right offset
if (response.hasReadSize() && response.getReadSize() != 0) {
this.requestBuilder.setCount(response.getReadSize());
}
if (outputStream != null) {
try {
response.getData().writeTo(outputStream);
} catch (final IOException e) {
LOG.error("Fail to write into file {}", this.destPath);
st.setError(RaftError.EIO, RaftError.EIO.name());
this.onFinished();
return;
}
} else {
final byte[] data = response.getData().toByteArray();
this.destBuf.put(data);
}
if (response.getEof()) {
onFinished();
return;
}
} finally {
lock.unlock();
}
this.sendNextRpc();
}
#location 35
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public void shutdown(final Closure done) {
List<RepeatedTimer> timers = null;
this.writeLock.lock();
try {
LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state);
if (this.state.compareTo(State.STATE_SHUTTING) < 0) {
NodeManager.getInstance().remove(this);
// If it is leader, set the wakeup_a_candidate with true;
// If it is follower, call on_stop_following in step_down
if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) {
stepDown(this.currTerm, this.state == State.STATE_LEADER,
new Status(RaftError.ESHUTDOWN, "Raft node is going to quit."));
}
this.state = State.STATE_SHUTTING;
// Stop all timers
timers = stopAllTimers();
if (this.readOnlyService != null) {
this.readOnlyService.shutdown();
}
if (this.logManager != null) {
this.logManager.shutdown();
}
if (this.metaStorage != null) {
this.metaStorage.shutdown();
}
if (this.snapshotExecutor != null) {
this.snapshotExecutor.shutdown();
}
if (this.wakingCandidate != null) {
Replicator.stop(this.wakingCandidate);
}
if (this.fsmCaller != null) {
this.fsmCaller.shutdown();
}
if (this.rpcService != null) {
this.rpcService.shutdown();
}
if (this.applyQueue != null) {
Utils.runInThread(() -> {
this.shutdownLatch = new CountDownLatch(1);
this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch);
});
} else {
final int num = GLOBAL_NUM_NODES.decrementAndGet();
LOG.info("The number of active nodes decrement to {}.", num);
}
if (this.timerManager != null) {
this.timerManager.shutdown();
}
}
if (this.state != State.STATE_SHUTDOWN) {
if (done != null) {
this.shutdownContinuations.add(done);
}
return;
}
// This node is down, it's ok to invoke done right now. Don't invoke this
// in place to avoid the dead writeLock issue when done.Run() is going to acquire
// a writeLock which is already held by the caller
if (done != null) {
Utils.runClosureInThread(done);
}
} finally {
this.writeLock.unlock();
// Destroy all timers out of lock
if (timers != null) {
destroyAllTimers(timers);
}
}
} | #vulnerable code
@Override
public void shutdown(final Closure done) {
this.writeLock.lock();
try {
LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state);
if (this.state.compareTo(State.STATE_SHUTTING) < 0) {
NodeManager.getInstance().remove(this);
// If it is leader, set the wakeup_a_candidate with true;
// If it is follower, call on_stop_following in step_down
if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) {
stepDown(this.currTerm, this.state == State.STATE_LEADER,
new Status(RaftError.ESHUTDOWN, "Raft node is going to quit."));
}
this.state = State.STATE_SHUTTING;
// Destroy all timers
if (this.electionTimer != null) {
this.electionTimer.destroy();
}
if (this.voteTimer != null) {
this.voteTimer.destroy();
}
if (this.stepDownTimer != null) {
this.stepDownTimer.destroy();
}
if (this.snapshotTimer != null) {
this.snapshotTimer.destroy();
}
if (this.readOnlyService != null) {
this.readOnlyService.shutdown();
}
if (this.logManager != null) {
this.logManager.shutdown();
}
if (this.metaStorage != null) {
this.metaStorage.shutdown();
}
if (this.snapshotExecutor != null) {
this.snapshotExecutor.shutdown();
}
if (this.wakingCandidate != null) {
Replicator.stop(this.wakingCandidate);
}
if (this.fsmCaller != null) {
this.fsmCaller.shutdown();
}
if (this.rpcService != null) {
this.rpcService.shutdown();
}
if (this.applyQueue != null) {
Utils.runInThread(() -> {
this.shutdownLatch = new CountDownLatch(1);
this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch);
});
} else {
final int num = GLOBAL_NUM_NODES.decrementAndGet();
LOG.info("The number of active nodes decrement to {}.", num);
}
if (this.timerManager != null) {
this.timerManager.shutdown();
}
}
if (this.state != State.STATE_SHUTDOWN) {
if (done != null) {
this.shutdownContinuations.add(done);
}
return;
}
// This node is down, it's ok to invoke done right now. Don't invoke this
// in place to avoid the dead writeLock issue when done.Run() is going to acquire
// a writeLock which is already held by the caller
if (done != null) {
Utils.runClosureInThread(done);
}
} finally {
this.writeLock.unlock();
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
long getNextSendIndex() {
// Fast path
if (this.inflights.isEmpty()) {
return this.nextIndex;
}
// Too many in-flight requests.
if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) {
return -1L;
}
// Last request should be a AppendEntries request and has some entries.
if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) {
return this.rpcInFly.startIndex + this.rpcInFly.count;
}
return -1L;
} | #vulnerable code
void installSnapshot() {
if (this.state == State.Snapshot) {
LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId());
this.id.unlock();
return;
}
boolean doUnlock = true;
try {
Requires.requireTrue(this.reader == null,
"Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(),
this.state);
this.reader = this.options.getSnapshotStorage().open();
if (this.reader == null) {
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot"));
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final String uri = this.reader.generateURIForCopy();
if (uri == null) {
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader"));
releaseReader();
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final RaftOutter.SnapshotMeta meta = this.reader.load();
if (meta == null) {
final String snapshotPath = this.reader.getPath();
final NodeImpl node = this.options.getNode();
final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT);
error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath));
releaseReader();
this.id.unlock();
doUnlock = false;
node.onError(error);
return;
}
final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder();
rb.setTerm(this.options.getTerm());
rb.setGroupId(this.options.getGroupId());
rb.setServerId(this.options.getServerId().toString());
rb.setPeerId(this.options.getPeerId().toString());
rb.setMeta(meta);
rb.setUri(uri);
this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT;
this.statInfo.lastLogIncluded = meta.getLastIncludedIndex();
this.statInfo.lastTermIncluded = meta.getLastIncludedTerm();
final InstallSnapshotRequest request = rb.build();
this.state = State.Snapshot;
// noinspection NonAtomicOperationOnVolatileField
this.installSnapshotCounter++;
final long monotonicSendTimeMs = Utils.monotonicMs();
final int stateVersion = this.version;
final int seq = getAndIncrementReqSeq();
final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(),
request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() {
@Override
public void run(final Status status) {
onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq,
stateVersion, monotonicSendTimeMs);
}
});
addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture);
} finally {
if (doUnlock) {
this.id.unlock();
}
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testRead() throws IOException {
//noinspection UnstableApiUsage
BufferedReader in = new BufferedReader(new InputStreamReader(Resources.getResource("event.txt").openStream(), Charsets.UTF_8));
Event ev = Event.read(in);
assert ev != null;
assertEquals(444691, ev.getUid());
assertEquals(1382920806122L, ev.getTime());
assertEquals("static/image-4", ev.getOp());
assertEquals(-599092377, ev.getIp());
ev = Event.read(in);
assert ev != null;
assertEquals(49664, ev.getUid());
assertEquals(1382926154968L, ev.getTime());
assertEquals("login", ev.getOp());
assertEquals(950354974, ev.getIp());
} | #vulnerable code
@Test
public void testRead() throws IOException, ParseException, Event.EventFormatException {
BufferedReader in = new BufferedReader(new InputStreamReader(Resources.getResource("event.txt").openStream(), Charsets.UTF_8));
Event ev = Event.read(in);
assertEquals(444691, ev.getUid());
assertEquals(1382920806122L, ev.getTime());
assertEquals("static/image-4", ev.getOp());
assertEquals(-599092377, ev.getIp());
ev = Event.read(in);
assertEquals(49664, ev.getUid());
assertEquals(1382926154968L, ev.getTime());
assertEquals("login", ev.getOp());
assertEquals(950354974, ev.getIp());
}
#location 5
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testRead() throws IOException {
//noinspection UnstableApiUsage
BufferedReader in = new BufferedReader(new InputStreamReader(Resources.getResource("event.txt").openStream(), Charsets.UTF_8));
Event ev = Event.read(in);
assert ev != null;
assertEquals(444691, ev.getUid());
assertEquals(1382920806122L, ev.getTime());
assertEquals("static/image-4", ev.getOp());
assertEquals(-599092377, ev.getIp());
ev = Event.read(in);
assert ev != null;
assertEquals(49664, ev.getUid());
assertEquals(1382926154968L, ev.getTime());
assertEquals("login", ev.getOp());
assertEquals(950354974, ev.getIp());
} | #vulnerable code
@Test
public void testRead() throws IOException, ParseException, Event.EventFormatException {
BufferedReader in = new BufferedReader(new InputStreamReader(Resources.getResource("event.txt").openStream(), Charsets.UTF_8));
Event ev = Event.read(in);
assertEquals(444691, ev.getUid());
assertEquals(1382920806122L, ev.getTime());
assertEquals("static/image-4", ev.getOp());
assertEquals(-599092377, ev.getIp());
ev = Event.read(in);
assertEquals(49664, ev.getUid());
assertEquals(1382926154968L, ev.getTime());
assertEquals("login", ev.getOp());
assertEquals(950354974, ev.getIp());
}
#location 10
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public String getIpAddress() {
HttpServletRequest request = getRequest();
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("http_client_ip");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip != null && ip.indexOf(",") != -1) {
ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
} | #vulnerable code
public String getIpAddress() {
HttpServletRequest request = getRequest();
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("http_client_ip");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip != null && ip.indexOf(",") != -1) {
ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
}
return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
}
#location 22
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public VersionOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader,
DatabaseOperationOption option, PrintStream printStream, MigrationHook upHook, MigrationHook downHook) {
if (option == null) {
option = new DatabaseOperationOption();
}
List<Change> changesInDb = getChangelog(connectionProvider, option);
List<Change> migrations = migrationsLoader.getMigrations();
Change specified = new Change(version);
if (!migrations.contains(specified)) {
throw new MigrationException("A migration for the specified version number does not exist.");
}
Change lastChangeInDb = changesInDb.isEmpty() ? null : changesInDb.get(changesInDb.size() - 1);
if (lastChangeInDb == null || specified.compareTo(lastChangeInDb) > 0) {
println(printStream, "Upgrading to: " + version);
int steps = 0;
for (Change change : migrations) {
if (change.compareTo(lastChangeInDb) > 0 && change.compareTo(specified) < 1) {
steps++;
}
}
new UpOperation(steps).operate(connectionProvider, migrationsLoader, option, printStream, upHook);
} else if (specified.compareTo(lastChangeInDb) < 0) {
println(printStream, "Downgrading to: " + version);
int steps = 0;
for (Change change : migrations) {
if (change.compareTo(specified) > -1 && change.compareTo(lastChangeInDb) < 0) {
steps++;
}
}
new DownOperation(steps).operate(connectionProvider, migrationsLoader, option, printStream, downHook);
} else {
println(printStream, "Already at version: " + version);
}
println(printStream);
return this;
} | #vulnerable code
public VersionOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader,
DatabaseOperationOption option, PrintStream printStream, MigrationHook upHook, MigrationHook downHook) {
if (option == null) {
option = new DatabaseOperationOption();
}
ensureVersionExists(migrationsLoader);
Change change = getLastAppliedChange(connectionProvider, option);
if (change == null || version.compareTo(change.getId()) > 0) {
println(printStream, "Upgrading to: " + version);
UpOperation up = new UpOperation(1);
while (!version.equals(change.getId())) {
up.operate(connectionProvider, migrationsLoader, option, printStream, upHook);
change = getLastAppliedChange(connectionProvider, option);
}
} else if (version.compareTo(change.getId()) < 0) {
println(printStream, "Downgrading to: " + version);
DownOperation down = new DownOperation(1);
while (!version.equals(change.getId())) {
down.operate(connectionProvider, migrationsLoader, option, printStream, downHook);
change = getLastAppliedChange(connectionProvider, option);
}
} else {
println(printStream, "Already at version: " + version);
}
println(printStream);
return this;
}
#location 11
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testGetConfiguredTemplate() {
String templateName = "";
try {
FileWriter fileWriter = new FileWriter(tempFile);
try {
fileWriter.append("new_command.template=templates/col_new_template_migration.sql");
fileWriter.flush();
templateName = ExternalResources.getConfiguredTemplate(tempFile.getAbsolutePath(),
"new_command.template");
assertEquals("templates/col_new_template_migration.sql", templateName);
} finally {
fileWriter.close();
}
} catch (Exception e) {
fail("Test failed with execption: " + e.getMessage());
}
} | #vulnerable code
@Test
public void testGetConfiguredTemplate() {
String templateName = "";
try {
FileWriter fileWriter = new FileWriter(tempFile);
fileWriter.append("new_command.template=templates/col_new_template_migration.sql");
fileWriter.flush();
templateName = ExternalResources.getConfiguredTemplate(tempFile.getAbsolutePath(), "new_command.template");
assertEquals("templates/col_new_template_migration.sql", templateName);
} catch (Exception e) {
fail("Test failed with execption: " + e.getMessage());
}
}
#location 8
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public VersionOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader,
DatabaseOperationOption option, PrintStream printStream, MigrationHook upHook, MigrationHook downHook) {
if (option == null) {
option = new DatabaseOperationOption();
}
List<Change> changesInDb = getChangelog(connectionProvider, option);
List<Change> migrations = migrationsLoader.getMigrations();
Change specified = new Change(version);
if (!migrations.contains(specified)) {
throw new MigrationException("A migration for the specified version number does not exist.");
}
Change lastChangeInDb = changesInDb.isEmpty() ? null : changesInDb.get(changesInDb.size() - 1);
if (lastChangeInDb == null || specified.compareTo(lastChangeInDb) > 0) {
println(printStream, "Upgrading to: " + version);
int steps = 0;
for (Change change : migrations) {
if (change.compareTo(lastChangeInDb) > 0 && change.compareTo(specified) < 1) {
steps++;
}
}
new UpOperation(steps).operate(connectionProvider, migrationsLoader, option, printStream, upHook);
} else if (specified.compareTo(lastChangeInDb) < 0) {
println(printStream, "Downgrading to: " + version);
int steps = 0;
for (Change change : migrations) {
if (change.compareTo(specified) > -1 && change.compareTo(lastChangeInDb) < 0) {
steps++;
}
}
new DownOperation(steps).operate(connectionProvider, migrationsLoader, option, printStream, downHook);
} else {
println(printStream, "Already at version: " + version);
}
println(printStream);
return this;
} | #vulnerable code
public VersionOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader,
DatabaseOperationOption option, PrintStream printStream, MigrationHook upHook, MigrationHook downHook) {
if (option == null) {
option = new DatabaseOperationOption();
}
ensureVersionExists(migrationsLoader);
Change change = getLastAppliedChange(connectionProvider, option);
if (change == null || version.compareTo(change.getId()) > 0) {
println(printStream, "Upgrading to: " + version);
UpOperation up = new UpOperation(1);
while (!version.equals(change.getId())) {
up.operate(connectionProvider, migrationsLoader, option, printStream, upHook);
change = getLastAppliedChange(connectionProvider, option);
}
} else if (version.compareTo(change.getId()) < 0) {
println(printStream, "Downgrading to: " + version);
DownOperation down = new DownOperation(1);
while (!version.equals(change.getId())) {
down.operate(connectionProvider, migrationsLoader, option, printStream, downHook);
change = getLastAppliedChange(connectionProvider, option);
}
} else {
println(printStream, "Already at version: " + version);
}
println(printStream);
return this;
}
#location 11
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testGetConfiguredTemplate() {
String templateName = "";
try {
FileWriter fileWriter = new FileWriter(tempFile);
try {
fileWriter.append("new_command.template=templates/col_new_template_migration.sql");
fileWriter.flush();
templateName = ExternalResources.getConfiguredTemplate(tempFile.getAbsolutePath(),
"new_command.template");
assertEquals("templates/col_new_template_migration.sql", templateName);
} finally {
fileWriter.close();
}
} catch (Exception e) {
fail("Test failed with execption: " + e.getMessage());
}
} | #vulnerable code
@Test
public void testGetConfiguredTemplate() {
String templateName = "";
try {
FileWriter fileWriter = new FileWriter(tempFile);
fileWriter.append("new_command.template=templates/col_new_template_migration.sql");
fileWriter.flush();
templateName = ExternalResources.getConfiguredTemplate(tempFile.getAbsolutePath(), "new_command.template");
assertEquals("templates/col_new_template_migration.sql", templateName);
} catch (Exception e) {
fail("Test failed with execption: " + e.getMessage());
}
}
#location 11
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private static void save(MethodNode methodNode) {
try {
MethodNodeService methodNodeService = ApplicationContextHelper.popBean(MethodNodeService.class);
assert methodNodeService != null;
methodNodeService.saveNotRedo(methodNode);
} catch (Exception e) {
e.printStackTrace();
}
} | #vulnerable code
private static void save(MethodNode methodNode) {
try {
MethodNodeService methodNodeService = ApplicationContextHelper.popBean(MethodNodeService.class);
methodNodeService.saveNotRedo(methodNode);
} catch (Exception e) {
logger.error("methodNodeService保存方法节点失败");
e.printStackTrace();
}
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
InplaceFileConverter(RuleSet ruleSet) {
this.lineConverter = new LineConverter(ruleSet);
lineTerminator = System.getProperty("line.separator");
} | #vulnerable code
void convert(File file, byte[] input) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(input);
Reader reader = new InputStreamReader(bais);
BufferedReader breader = new BufferedReader(reader);
FileWriter fileWriter = new FileWriter(file);
while (true) {
String line = breader.readLine();
if (line != null) {
String[] replacement = lineConverter.getReplacement(line);
writeReplacement(fileWriter, replacement);
} else {
fileWriter.close();
break;
}
}
}
#location 14
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public boolean contains(Marker other) {
if (other == null) {
throw new IllegalArgumentException("Other cannot be null");
}
if (this.equals(other)) {
return true;
}
if (hasReferences()) {
for (int i = 0; i < referenceList.size(); i++) {
Marker ref = (Marker) referenceList.get(i);
if (ref.contains(other)) {
return true;
}
}
}
return false;
} | #vulnerable code
public boolean contains(Marker other) {
if (other == null) {
throw new IllegalArgumentException("Other cannot be null");
}
if (this.equals(other)) {
return true;
}
if (hasReferences()) {
for (int i = 0; i < refereceList.size(); i++) {
Marker ref = (Marker) refereceList.get(i);
if (ref.contains(other)) {
return true;
}
}
}
return false;
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public boolean contains(String name) {
if(name == null) {
throw new IllegalArgumentException("Other cannot be null");
}
if (this.name.equals(name)) {
return true;
}
if (hasChildren()) {
for(int i = 0; i < children.size(); i++) {
Marker child = (Marker) children.get(i);
if(child.contains(name)) {
return true;
}
}
}
return false;
} | #vulnerable code
public boolean contains(String name) {
if(name == null) {
return false;
}
if(factory.exists(name)) {
Marker other = factory.getMarker(name);
return contains(other);
} else {
return false;
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private static boolean deleteFileOrDirectory(File path) throws MojoFailureException {
if (path.isDirectory()) {
File[] files = path.listFiles();
if (null != files) {
for (File file : files) {
if (file.isDirectory()) {
if (!deleteFileOrDirectory(file)) {
throw new MojoFailureException("Can't delete dir " + file);
}
} else {
if (!file.delete()) {
throw new MojoFailureException("Can't delete file " + file);
}
}
}
}
return path.delete();
} else {
return path.delete();
}
} | #vulnerable code
private static boolean deleteFileOrDirectory(File path) throws MojoFailureException {
if (path.isDirectory()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
if (!deleteFileOrDirectory(files[i])) {
throw new MojoFailureException("Can't delete dir " + files[i]);
}
} else {
if (!files[i].delete()) {
throw new MojoFailureException("Can't delete file " + files[i]);
}
}
}
return path.delete();
} else {
return path.delete();
}
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public final void evalLispFile() {
// Loop.evalLisp("default", new InputStreamReader(LispEvaluatorTest.class.getResourceAsStream("funcs.lisp")));
} | #vulnerable code
@Test
public final void evalLispFile() {
Loop.evalLisp("default", new InputStreamReader(LispEvaluatorTest.class.getResourceAsStream("funcs.lisp")));
}
#location 3
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Property(trials = TRIALS)
public void shouldCollectToListWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) {
// given
executor = threadPoolExecutor(unitsOfWork);
long expectedDuration = expectedDuration(parallelism, unitsOfWork, BLOCKING_MILLIS);
Map.Entry<List<Long>, Long> result = timed(collectWith(f -> parallelToList(f, executor, parallelism), unitsOfWork));
assertThat(result)
.satisfies(e -> {
assertThat(e.getValue())
.isGreaterThanOrEqualTo(expectedDuration)
.isCloseTo(expectedDuration, offset(CONSTANT_DELAY));
assertThat(e.getKey()).hasSize(unitsOfWork);
});
} | #vulnerable code
@Property(trials = TRIALS)
public void shouldCollectToListWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) {
// given
executor = threadPoolExecutor(unitsOfWork);
long expectedDuration = expectedDuration(parallelism, unitsOfWork, BLOCKING_MILLIS);
Map.Entry<List<Long>, Long> result = timed(collectWith(parallelToList(executor, parallelism), unitsOfWork));
assertThat(result)
.satisfies(e -> {
assertThat(e.getValue())
.isGreaterThanOrEqualTo(expectedDuration)
.isCloseTo(expectedDuration, offset(CONSTANT_DELAY));
assertThat(e.getKey()).hasSize(unitsOfWork);
});
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Property(trials = 10)
public void shouldCollectToCollectionWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) {
// given
executor = threadPoolExecutor(unitsOfWork);
long expectedDuration = expectedDuration(parallelism, unitsOfWork);
Map.Entry<List<Long>, Long> result = timed(collectWith(parallelToCollection(ArrayList::new, executor, parallelism), unitsOfWork));
assertThat(result)
.satisfies(e -> {
assertThat(e.getValue())
.isGreaterThanOrEqualTo(expectedDuration)
.isCloseTo(expectedDuration, offset(CONSTANT_DELAY));
assertThat(e.getKey()).hasSize(unitsOfWork);
});
} | #vulnerable code
@Property(trials = 10)
public void shouldCollectToCollectionWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) {
// given
executor = threadPoolExecutor(unitsOfWork);
long expectedDuration = expectedDuration(parallelism, unitsOfWork);
Map.Entry<List<Long>, Long> result = timed(collectWith(inParallelToCollection(ArrayList::new, executor, parallelism), unitsOfWork));
assertThat(result)
.satisfies(e -> {
assertThat(e.getValue())
.isGreaterThanOrEqualTo(expectedDuration)
.isCloseTo(expectedDuration, offset(CONSTANT_DELAY));
assertThat(e.getKey()).hasSize(unitsOfWork);
});
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Property(trials = 10)
public void shouldCollectToListWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) {
// given
executor = threadPoolExecutor(unitsOfWork);
long expectedDuration = expectedDuration(parallelism, unitsOfWork);
Map.Entry<List<Long>, Long> result = timed(collectWith(parallelToList(executor, parallelism), unitsOfWork));
assertThat(result)
.satisfies(e -> {
assertThat(e.getValue())
.isGreaterThanOrEqualTo(expectedDuration)
.isCloseTo(expectedDuration, offset(CONSTANT_DELAY));
assertThat(e.getKey()).hasSize(unitsOfWork);
});
} | #vulnerable code
@Property(trials = 10)
public void shouldCollectToListWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) {
// given
executor = threadPoolExecutor(unitsOfWork);
long expectedDuration = expectedDuration(parallelism, unitsOfWork);
Map.Entry<List<Long>, Long> result = timed(collectWith(inParallelToList(executor, parallelism), unitsOfWork));
assertThat(result)
.satisfies(e -> {
assertThat(e.getValue())
.isGreaterThanOrEqualTo(expectedDuration)
.isCloseTo(expectedDuration, offset(CONSTANT_DELAY));
assertThat(e.getKey()).hasSize(unitsOfWork);
});
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void testToMap() throws SQLException {
assertTrue(this.rs.next());
Map m = processor.toMap(this.rs);
assertEquals(COLS, m.keySet().size());
assertEquals("1", m.get("one"));
assertEquals("2", m.get("TWO"));
assertEquals("3", m.get("Three"));
assertTrue(this.rs.next());
m = processor.toMap(this.rs);
assertEquals(COLS, m.keySet().size());
assertEquals("4", m.get("One")); // case shouldn't matter
assertEquals("5", m.get("two"));
assertEquals("6", m.get("THREE"));
assertFalse(this.rs.next());
} | #vulnerable code
public void testToMap() throws SQLException {
int rowCount = 0;
Map m = null;
while (this.rs.next()) {
m = processor.toMap(this.rs);
assertNotNull(m);
assertEquals(COLS, m.keySet().size());
rowCount++;
}
assertEquals(ROWS, rowCount);
assertEquals("4", m.get("One")); // case shouldn't matter
assertEquals("5", m.get("two"));
assertEquals("6", m.get("THREE"));
}
#location 13
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void testToArray() throws SQLException {
Object[] a = null;
assertTrue(this.rs.next());
a = processor.toArray(this.rs);
assertEquals(COLS, a.length);
assertEquals("1", a[0]);
assertEquals("2", a[1]);
assertEquals("3", a[2]);
assertTrue(this.rs.next());
a = processor.toArray(this.rs);
assertEquals(COLS, a.length);
assertEquals("4", a[0]);
assertEquals("5", a[1]);
assertEquals("6", a[2]);
assertFalse(this.rs.next());
} | #vulnerable code
public void testToArray() throws SQLException {
int rowCount = 0;
Object[] a = null;
while (this.rs.next()) {
a = processor.toArray(this.rs);
assertEquals(COLS, a.length);
rowCount++;
}
assertEquals(ROWS, rowCount);
assertEquals("4", a[0]);
assertEquals("5", a[1]);
assertEquals("6", a[2]);
}
#location 12
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void testColumnNameHandle() throws SQLException {
ResultSetHandler<Map<Integer,Map<String,Object>>> h = new KeyedHandler<Integer>("intTest");
Map<Integer,Map<String,Object>> results = h.handle(this.rs);
assertNotNull(results);
assertEquals(ROWS, results.size());
Map<String,Object> row = null;
for(Entry<Integer, Map<String, Object>> entry : results.entrySet())
{
Object key = entry.getKey();
assertNotNull(key);
row = entry.getValue();
assertNotNull(row);
assertEquals(COLS, row.keySet().size());
}
row = results.get(3);
assertEquals("4", row.get("one"));
assertEquals("5", row.get("TWO"));
assertEquals("6", row.get("Three"));
} | #vulnerable code
public void testColumnNameHandle() throws SQLException {
ResultSetHandler<Map<Object,Map<String,Object>>> h = new KeyedHandler("three");
Map<Object,Map<String,Object>> results = h.handle(this.rs);
assertNotNull(results);
assertEquals(ROWS, results.size());
Map<String,Object> row = null;
for(Entry<Object, Map<String, Object>> entry : results.entrySet())
{
Object key = entry.getKey();
assertNotNull(key);
row = entry.getValue();
assertNotNull(row);
assertEquals(COLS, row.keySet().size());
}
row = results.get("6");
assertEquals("4", row.get("one"));
assertEquals("5", row.get("TWO"));
assertEquals("6", row.get("Three"));
}
#location 18
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void testHandle() throws SQLException {
ResultSetHandler h = new MapListHandler();
List results = (List) h.handle(this.rs);
assertNotNull(results);
assertEquals(ROWS, results.size());
Iterator iter = results.iterator();
Map row = null;
assertTrue(iter.hasNext());
row = (Map) iter.next();
assertEquals(COLS, row.keySet().size());
assertEquals("1", row.get("one"));
assertEquals("2", row.get("TWO"));
assertEquals("3", row.get("Three"));
assertTrue(iter.hasNext());
row = (Map) iter.next();
assertEquals(COLS, row.keySet().size());
assertEquals("4", row.get("one"));
assertEquals("5", row.get("TWO"));
assertEquals("6", row.get("Three"));
assertFalse(iter.hasNext());
} | #vulnerable code
public void testHandle() throws SQLException {
ResultSetHandler h = new MapListHandler();
List results = (List) h.handle(this.rs);
assertNotNull(results);
assertEquals(ROWS, results.size());
Iterator iter = results.iterator();
Map row = null;
while (iter.hasNext()) {
row = (Map) iter.next();
assertEquals(COLS, row.keySet().size());
}
assertEquals("4", row.get("one"));
assertEquals("5", row.get("TWO"));
assertEquals("6", row.get("Three"));
}
#location 15
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void testToBean() throws SQLException, ParseException {
TestBean row = null;
assertTrue(this.rs.next());
row = (TestBean) processor.toBean(this.rs, TestBean.class);
assertEquals("1", row.getOne());
assertEquals("2", row.getTwo());
assertEquals("3", row.getThree());
assertEquals("not set", row.getDoNotSet());
assertTrue(this.rs.next());
row = (TestBean) processor.toBean(this.rs, TestBean.class);
assertEquals("4", row.getOne());
assertEquals("5", row.getTwo());
assertEquals("6", row.getThree());
assertEquals("not set", row.getDoNotSet());
assertEquals(3, row.getIntTest());
assertEquals(new Integer(4), row.getIntegerTest());
assertEquals(null, row.getNullObjectTest());
assertEquals(0, row.getNullPrimitiveTest());
// test date -> string handling
assertNotNull(row.getNotDate());
assertTrue(!"not a date".equals(row.getNotDate()));
datef.parse(row.getNotDate());
assertFalse(this.rs.next());
} | #vulnerable code
public void testToBean() throws SQLException, ParseException {
int rowCount = 0;
TestBean b = null;
while (this.rs.next()) {
b = (TestBean) processor.toBean(this.rs, TestBean.class);
assertNotNull(b);
rowCount++;
}
assertEquals(ROWS, rowCount);
assertEquals("4", b.getOne());
assertEquals("5", b.getTwo());
assertEquals("6", b.getThree());
assertEquals("not set", b.getDoNotSet());
assertEquals(3, b.getIntTest());
assertEquals(new Integer(4), b.getIntegerTest());
assertEquals(null, b.getNullObjectTest());
assertEquals(0, b.getNullPrimitiveTest());
// test date -> string handling
assertNotNull(b.getNotDate());
assertTrue(!"not a date".equals(b.getNotDate()));
datef.parse(b.getNotDate());
}
#location 12
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void saveModel(String filePath) throws IOException {
ObjectOutput oot = new ObjectOutputStream(new FileOutputStream(filePath));
oot.writeObject(this);
} | #vulnerable code
public void saveModel(String filePath) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath))) ;
writeMap(bw,idWordMap) ;
writeMap(bw,word2Mc) ;
writeMap(bw,ww2Mc.get()) ;
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static int getIntValue(String value) {
if (StringUtil.isBlank(value)) {
return 0;
}
return castToInteger(value);
} | #vulnerable code
public static int getIntValue(String value) {
if (StringUtil.isBlank(value)) {
return 0;
}
return castToInt(value);
}
#location 5
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void saveModel(String filePath) throws IOException {
ObjectOutput oot = new ObjectOutputStream(new FileOutputStream(filePath));
oot.writeObject(this);
} | #vulnerable code
public void saveModel(String filePath) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath))) ;
writeMap(bw,idWordMap) ;
writeMap(bw,word2Mc) ;
writeMap(bw,ww2Mc.get()) ;
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
@SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine")
public synchronized void launch(SlaveComputer computer, TaskListener listener) {
if (!(computer instanceof KubernetesComputer)) {
throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer");
}
KubernetesComputer kubernetesComputer = (KubernetesComputer) computer;
computer.setAcceptingTasks(false);
KubernetesSlave slave = kubernetesComputer.getNode();
if (slave == null) {
throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName());
}
if (launched) {
LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName());
computer.setAcceptingTasks(true);
return;
}
final PodTemplate template = slave.getTemplate();
try {
KubernetesClient client = slave.getKubernetesCloud().connect();
Pod pod = template.build(slave);
slave.assignPod(pod);
String podName = pod.getMetadata().getName();
String namespace = Arrays.asList( //
pod.getMetadata().getNamespace(),
template.getNamespace(), client.getNamespace()) //
.stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null);
slave.setNamespace(namespace);
LOGGER.log(Level.FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName });
pod = client.pods().inNamespace(namespace).create(pod);
LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName });
listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName);
TaskListener runListener = template.getListener();
runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName);
template.getWorkspaceVolume().createVolume(client, pod.getMetadata());
watcher = new AllContainersRunningPodWatcher(client, pod, runListener);
try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher);
Watch w2 = eventWatch(client, podName, namespace, runListener)) {
assert watcher != null; // assigned 3 lines above
watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS);
}
LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName });
// We need the pod to be running and connected before returning
// otherwise this method keeps being called multiple times
List<String> validStates = ImmutableList.of("Running");
int waitForSlaveToConnect = template.getSlaveConnectTimeout();
int waitedForSlave;
// now wait for agent to be online
SlaveComputer slaveComputer = null;
String status = null;
List<ContainerStatus> containerStatuses = null;
long lastReportTimestamp = System.currentTimeMillis();
for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) {
slaveComputer = slave.getComputer();
if (slaveComputer == null) {
throw new IllegalStateException("Node was deleted, computer is null");
}
if (slaveComputer.isOnline()) {
break;
}
// Check that the pod hasn't failed already
pod = client.pods().inNamespace(namespace).withName(podName).get();
if (pod == null) {
throw new IllegalStateException("Pod no longer exists: " + podName);
}
status = pod.getStatus().getPhase();
if (!validStates.contains(status)) {
break;
}
containerStatuses = pod.getStatus().getContainerStatuses();
List<ContainerStatus> terminatedContainers = new ArrayList<>();
for (ContainerStatus info : containerStatuses) {
if (info != null) {
if (info.getState().getTerminated() != null) {
// Container has errored
LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}",
new Object[] { podName, info.getState().getTerminated(), info.getName() });
listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName,
info.getState().getTerminated(), info.getName());
terminatedContainers.add(info);
}
}
}
checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client);
if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) {
LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}",
new Object[]{podName, waitedForSlave, waitForSlaveToConnect});
listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave,
waitForSlaveToConnect);
lastReportTimestamp = System.currentTimeMillis();
}
Thread.sleep(1000);
}
if (slaveComputer == null || slaveComputer.isOffline()) {
logLastLines(containerStatuses, podName, namespace, slave, null, client);
throw new IllegalStateException(
"Agent is not connected after " + waitedForSlave + " seconds, status: " + status);
}
computer.setAcceptingTasks(true);
launched = true;
try {
// We need to persist the "launched" setting...
slave.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e);
}
} catch (Throwable ex) {
setProblem(ex);
LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex);
LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName());
try {
slave.terminate();
} catch (IOException | InterruptedException e) {
LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e);
}
throw Throwables.propagate(ex);
}
} | #vulnerable code
@Override
@SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine")
public synchronized void launch(SlaveComputer computer, TaskListener listener) {
if (!(computer instanceof KubernetesComputer)) {
throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer");
}
KubernetesComputer kubernetesComputer = (KubernetesComputer) computer;
computer.setAcceptingTasks(false);
KubernetesSlave slave = kubernetesComputer.getNode();
if (slave == null) {
throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName());
}
if (launched) {
LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName());
computer.setAcceptingTasks(true);
return;
}
final PodTemplate template = slave.getTemplate();
try {
KubernetesClient client = slave.getKubernetesCloud().connect();
Pod pod = template.build(slave);
slave.assignPod(pod);
String podName = pod.getMetadata().getName();
String namespace = Arrays.asList( //
pod.getMetadata().getNamespace(),
template.getNamespace(), client.getNamespace()) //
.stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null);
slave.setNamespace(namespace);
LOGGER.log(Level.FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName });
pod = client.pods().inNamespace(namespace).create(pod);
LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName });
listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName);
TaskListener runListener = template.getListener();
runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName);
template.getWorkspaceVolume().createVolume(client, pod.getMetadata());
watcher = new AllContainersRunningPodWatcher(client, pod, runListener);
try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher);
Watch w2 = eventWatch(client, podName, namespace, runListener)) {
assert watcher != null; // assigned 3 lines above
watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS);
} catch (InvalidPodTemplateException e) {
LOGGER.info("Caught invalid pod template exception");
switch (e.getReason()) {
case "ImagePullBackOff":
runListener.getLogger().printf(e.getMessage());
PodUtils.cancelInvalidPodTemplateJob(pod, "ImagePullBackOff");
break;
default:
LOGGER.warning("Unknown reason for InvalidPodTemplateException : " + e.getReason());
break;
}
}
LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName });
// We need the pod to be running and connected before returning
// otherwise this method keeps being called multiple times
List<String> validStates = ImmutableList.of("Running");
int waitForSlaveToConnect = template.getSlaveConnectTimeout();
int waitedForSlave;
// now wait for agent to be online
SlaveComputer slaveComputer = null;
String status = null;
List<ContainerStatus> containerStatuses = null;
long lastReportTimestamp = System.currentTimeMillis();
for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) {
slaveComputer = slave.getComputer();
if (slaveComputer == null) {
throw new IllegalStateException("Node was deleted, computer is null");
}
if (slaveComputer.isOnline()) {
break;
}
// Check that the pod hasn't failed already
pod = client.pods().inNamespace(namespace).withName(podName).get();
if (pod == null) {
throw new IllegalStateException("Pod no longer exists: " + podName);
}
status = pod.getStatus().getPhase();
if (!validStates.contains(status)) {
break;
}
containerStatuses = pod.getStatus().getContainerStatuses();
List<ContainerStatus> terminatedContainers = new ArrayList<>();
for (ContainerStatus info : containerStatuses) {
if (info != null) {
if (info.getState().getTerminated() != null) {
// Container has errored
LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}",
new Object[] { podName, info.getState().getTerminated(), info.getName() });
listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName,
info.getState().getTerminated(), info.getName());
terminatedContainers.add(info);
}
}
}
checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client);
if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) {
LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}",
new Object[]{podName, waitedForSlave, waitForSlaveToConnect});
listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave,
waitForSlaveToConnect);
lastReportTimestamp = System.currentTimeMillis();
}
Thread.sleep(1000);
}
if (slaveComputer == null || slaveComputer.isOffline()) {
logLastLines(containerStatuses, podName, namespace, slave, null, client);
throw new IllegalStateException(
"Agent is not connected after " + waitedForSlave + " seconds, status: " + status);
}
computer.setAcceptingTasks(true);
launched = true;
try {
// We need to persist the "launched" setting...
slave.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e);
}
} catch (Throwable ex) {
setProblem(ex);
LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex);
LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName());
try {
slave.terminate();
} catch (IOException | InterruptedException e) {
LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e);
}
throw Throwables.propagate(ex);
}
}
#location 51
#vulnerability type CHECKERS_PRINTF_ARGS |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Pod getPodTemplate(KubernetesSlave slave, Label label) {
final PodTemplate template = getTemplate(label);
String id = getIdForLabel(label);
List<EnvVar> env = new ArrayList<EnvVar>(3);
// always add some env vars
env.add(new EnvVar("JENKINS_SECRET", slave.getComputer().getJnlpMac(), null));
env.add(new EnvVar("JENKINS_LOCATION_URL", JenkinsLocationConfiguration.get().getUrl(), null));
String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl;
env.add(new EnvVar("JENKINS_URL", url, null));
if (!StringUtils.isBlank(jenkinsTunnel)) {
env.add(new EnvVar("JENKINS_TUNNEL", jenkinsTunnel, null));
}
url = url.endsWith("/") ? url : url + "/";
env.add(new EnvVar("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp", null));
return new PodBuilder()
.withNewMetadata()
.withName(slave.getNodeName())
.withLabels(getLabelsFor(id))
.endMetadata()
.withNewSpec()
.addNewContainer()
.withName(CONTAINER_NAME)
.withImage(template.getImage())
.withNewSecurityContext()
.withPrivileged(template.isPrivileged())
.endSecurityContext()
.withEnv(env)
.withCommand(parseDockerCommand(template.getCommand()))
.addToArgs(slave.getComputer().getJnlpMac())
.addToArgs(slave.getComputer().getName())
.endContainer()
.withRestartPolicy("Never")
.endSpec()
.build();
} | #vulnerable code
private Pod getPodTemplate(KubernetesSlave slave, Label label) {
final PodTemplate template = getTemplate(label);
String id = getIdForLabel(label);
Pod pod = new Pod();
KubernetesHelper.setName(pod, slave.getNodeName());
pod.getMetadata().setLabels(getLabelsFor(id));
Container manifestContainer = new Container();
manifestContainer.setName(CONTAINER_NAME);
manifestContainer.setImage(template.getImage());
if (template.isPrivileged())
manifestContainer.setSecurityContext(new SecurityContext(null, true, null, null));
List<EnvVar> env = new ArrayList<EnvVar>(3);
// always add some env vars
env.add(new EnvVar("JENKINS_SECRET", slave.getComputer().getJnlpMac(), null));
env.add(new EnvVar("JENKINS_LOCATION_URL", JenkinsLocationConfiguration.get().getUrl(), null));
String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl;
env.add(new EnvVar("JENKINS_URL", url, null));
if (!StringUtils.isBlank(jenkinsTunnel)) {
env.add(new EnvVar("JENKINS_TUNNEL", jenkinsTunnel, null));
}
url = url.endsWith("/") ? url : url + "/";
env.add(new EnvVar("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp", null));
manifestContainer.setEnv(env);
// command: SECRET SLAVE_NAME
List<String> cmd = parseDockerCommand(template.getCommand());
List<String> args = parseDockerCommand(template.getArgs());
args = args == null ? new ArrayList<String>(2) : args;
args.add(slave.getComputer().getJnlpMac()); // secret
args.add(slave.getComputer().getName()); // name
manifestContainer.setCommand(cmd);
manifestContainer.setArgs(args);
List<Container> containers = new ArrayList<Container>();
containers.add(manifestContainer);
PodSpec podSpec = new PodSpec();
pod.setSpec(podSpec);
podSpec.setContainers(containers);
podSpec.setRestartPolicy("Never");
return pod;
}
#location 13
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1}" + serverUrl,
new String[] { getDisplayName(), serverUrl });
client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify,
connectTimeout, readTimeout).createClient();
LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}" + serverUrl,
new String[] { getDisplayName(), serverUrl });
return client;
} | #vulnerable code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes host " + getDisplayName() + " URL " + serverUrl);
if (client == null) {
synchronized (this) {
if (client == null) {
client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout)
.createClient();
}
}
}
return client;
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Pod getPodTemplate(KubernetesSlave slave, Label label) {
DockerTemplate template = getTemplate(label);
String id = getIdForLabel(label);
Pod podTemplate = new Pod();
podTemplate.setId(slave.getNodeName());
// labels
podTemplate.setLabels(getLabelsFor(id));
Container container = new Container();
container.setName(CONTAINER_NAME);
container.setImage(template.image);
// environment
// List<EnvironmentVariable> env = new
// ArrayList<EnvironmentVariable>(template.environment.length + 3);
List<EnvironmentVariable> env = new ArrayList<EnvironmentVariable>(3);
// always add some env vars
env.add(new EnvironmentVariable("JENKINS_SECRET", slave.getComputer().getJnlpMac()));
env.add(new EnvironmentVariable("JENKINS_URL", JenkinsLocationConfiguration.get().getUrl()));
String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl;
url = url.endsWith("/") ? url : url + "/";
env.add(new EnvironmentVariable("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp"));
if (!StringUtils.isBlank(jenkinsTunnel)) {
env.add(new EnvironmentVariable("JENKINS_TUNNEL", jenkinsTunnel));
}
// for (int i = 0; i < template.environment.length; i++) {
// String[] split = template.environment[i].split("=");
// env.add(new EnvironmentVariable(split[0], split[1]));
// }
container.setEnv(env);
// ports
// TODO open ports defined in template
// container.setPorts(new Port(22, RAND.nextInt((65535 - 49152) + 1) +
// 49152));
// command: SECRET SLAVE_NAME
List<String> cmd = parseDockerCommand(template.dockerCommand);
cmd = cmd == null ? new ArrayList<String>(2) : cmd;
cmd.add(slave.getComputer().getJnlpMac()); // secret
cmd.add(slave.getComputer().getName()); // name
container.setCommand(cmd);
Manifest manifest = new Manifest(Collections.singletonList(container), null);
podTemplate.setDesiredState(new State(manifest));
return podTemplate;
} | #vulnerable code
private Pod getPodTemplate(KubernetesSlave slave, Label label) {
DockerTemplate template = getTemplate(label);
String id = getIdForLabel(label);
Pod podTemplate = new Pod();
podTemplate.setId(slave.getNodeName());
// labels
podTemplate.setLabels(getLabelsFor(id));
Container container = new Container();
container.setName(CONTAINER_NAME);
container.setImage(template.image);
// environment
// List<EnvironmentVariable> env = new
// ArrayList<EnvironmentVariable>(template.environment.length + 3);
List<EnvironmentVariable> env = new ArrayList<EnvironmentVariable>(3);
// always add some env vars
env.add(new EnvironmentVariable("JENKINS_SECRET", slave.getComputer().getJnlpMac()));
env.add(new EnvironmentVariable("JENKINS_URL", JenkinsLocationConfiguration.get().getUrl()));
String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl;
url = url.endsWith("/") ? url : url + "/";
env.add(new EnvironmentVariable("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp"));
if (!StringUtils.isBlank(jenkinsTunnel)) {
env.add(new EnvironmentVariable("JENKINS_TUNNEL", jenkinsTunnel));
}
// for (int i = 0; i < template.environment.length; i++) {
// String[] split = template.environment[i].split("=");
// env.add(new EnvironmentVariable(split[0], split[1]));
// }
container.setEnv(env);
// ports
// TODO open ports defined in template
// container.setPorts(new Port(22, RAND.nextInt((65535 - 49152) + 1) +
// 49152));
// command: SECRET SLAVE_NAME
List<String> cmd = parseDockerCommand(template.dockerCommand);
cmd.addAll(ImmutableList.of(slave.getComputer().getJnlpMac(), slave.getComputer().getName()));
container.setCommand(cmd);
Manifest manifest = new Manifest(Collections.singletonList(container), null);
podTemplate.setDesiredState(new State(manifest));
return podTemplate;
}
#location 40
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void validatePod(Pod pod) {
assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels());
// check containers
Map<String, Container> containers = pod.getSpec().getContainers().stream()
.collect(Collectors.toMap(Container::getName, Function.identity()));
assertEquals(2, containers.size());
assertEquals("busybox", containers.get("busybox").getImage());
assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage());
// check volumes and volume mounts
Map<String, Volume> volumes = pod.getSpec().getVolumes().stream()
.collect(Collectors.toMap(Volume::getName, Function.identity()));
assertEquals(3, volumes.size());
assertNotNull(volumes.get("workspace-volume"));
assertNotNull(volumes.get("empty-volume"));
assertNotNull(volumes.get("host-volume"));
List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts();
assertEquals(2, mounts.size());
assertEquals(new VolumeMount("/container/data", "host-volume", null, null), mounts.get(0));
assertEquals(new VolumeMount("/home/jenkins", "workspace-volume", false, null), mounts.get(1));
mounts = containers.get("jnlp").getVolumeMounts();
assertEquals(1, mounts.size());
} | #vulnerable code
private void validatePod(Pod pod) {
assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels());
// check containers
Map<String, Container> containers = new HashMap<>();
for (Container c : pod.getSpec().getContainers()) {
containers.put(c.getName(), c);
}
assertEquals(2, containers.size());
assertEquals("busybox", containers.get("busybox").getImage());
assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage());
// check volumes and volume mounts
Map<String, Volume> volumes = new HashMap<>();
for (Volume v : pod.getSpec().getVolumes()) {
volumes.put(v.getName(), v);
}
assertEquals(2, volumes.size());
assertNotNull(volumes.get("workspace-volume"));
assertNotNull(volumes.get("empty-volume"));
List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts();
assertEquals(1, mounts.size());
mounts = containers.get("jnlp").getVolumeMounts();
assertEquals(1, mounts.size());
}
#location 12
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1}" + serverUrl,
new String[] { getDisplayName(), serverUrl });
client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify,
connectTimeout, readTimeout).createClient();
LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}" + serverUrl,
new String[] { getDisplayName(), serverUrl });
return client;
} | #vulnerable code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes host " + getDisplayName() + " URL " + serverUrl);
if (client == null) {
synchronized (this) {
if (client == null) {
client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout)
.createClient();
}
}
}
return client;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void validatePod(Pod pod) {
assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels());
// check containers
Map<String, Container> containers = pod.getSpec().getContainers().stream()
.collect(Collectors.toMap(Container::getName, Function.identity()));
assertEquals(2, containers.size());
assertEquals("busybox", containers.get("busybox").getImage());
assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage());
// check volumes and volume mounts
Map<String, Volume> volumes = pod.getSpec().getVolumes().stream()
.collect(Collectors.toMap(Volume::getName, Function.identity()));
assertEquals(3, volumes.size());
assertNotNull(volumes.get("workspace-volume"));
assertNotNull(volumes.get("empty-volume"));
assertNotNull(volumes.get("host-volume"));
List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts();
assertEquals(2, mounts.size());
assertEquals(new VolumeMount("/container/data", "host-volume", null, null), mounts.get(0));
assertEquals(new VolumeMount("/home/jenkins", "workspace-volume", false, null), mounts.get(1));
mounts = containers.get("jnlp").getVolumeMounts();
assertEquals(1, mounts.size());
} | #vulnerable code
private void validatePod(Pod pod) {
assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels());
// check containers
Map<String, Container> containers = new HashMap<>();
for (Container c : pod.getSpec().getContainers()) {
containers.put(c.getName(), c);
}
assertEquals(2, containers.size());
assertEquals("busybox", containers.get("busybox").getImage());
assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage());
// check volumes and volume mounts
Map<String, Volume> volumes = new HashMap<>();
for (Volume v : pod.getSpec().getVolumes()) {
volumes.put(v.getName(), v);
}
assertEquals(2, volumes.size());
assertNotNull(volumes.get("workspace-volume"));
assertNotNull(volumes.get("empty-volume"));
List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts();
assertEquals(1, mounts.size());
mounts = containers.get("jnlp").getVolumeMounts();
assertEquals(1, mounts.size());
}
#location 11
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private static List<KubernetesCloud> getUsageRestrictedKubernetesClouds() {
List<KubernetesCloud> clouds = Jenkins.get().clouds
.getAll(KubernetesCloud.class)
.stream()
.filter(KubernetesCloud::isUsageRestricted)
.collect(Collectors.toList());
Collections.sort(clouds, Comparator.<Cloud, String>comparing(o -> o.name));
return clouds;
} | #vulnerable code
private static List<KubernetesCloud> getUsageRestrictedKubernetesClouds() {
List<KubernetesCloud> clouds = new ArrayList<>();
for (Cloud cloud : Jenkins.getInstance().clouds) {
if(cloud instanceof KubernetesCloud) {
if (((KubernetesCloud) cloud).isUsageRestricted()) {
clouds.add((KubernetesCloud) cloud);
}
}
}
Collections.sort(clouds, CLOUD_BY_NAME);
return clouds;
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public void onResume() {
super.onResume();
Cloud cloud = Jenkins.get().getCloud(cloudName);
if (cloud == null) {
throw new RuntimeException(String.format("Cloud does not exist: %s", cloudName));
}
if (!(cloud instanceof KubernetesCloud)) {
throw new RuntimeException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName,
cloud.getClass().getName()));
}
KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud;
kubernetesCloud.addDynamicTemplate(newTemplate);
} | #vulnerable code
@Override
public void onResume() {
super.onResume();
Cloud cloud = Jenkins.getInstance().getCloud(cloudName);
if (cloud == null) {
throw new RuntimeException(String.format("Cloud does not exist: %s", cloudName));
}
if (!(cloud instanceof KubernetesCloud)) {
throw new RuntimeException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName,
cloud.getClass().getName()));
}
KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud;
kubernetesCloud.addDynamicTemplate(newTemplate);
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException, ExecutionException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1} namespace {2}",
new String[] { getDisplayName(), serverUrl, namespace });
KubernetesClient client = KubernetesClientProvider.createClient(name, serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify,
connectTimeout, readTimeout, maxRequestsPerHost);
LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}", new String[] { getDisplayName(), serverUrl });
return client;
} | #vulnerable code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException, ExecutionException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1} namespace {2}",
new String[] { getDisplayName(), serverUrl, namespace });
client = KubernetesClientProvider.createClient(name, serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify,
connectTimeout, readTimeout, maxRequestsPerHost);
LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}", new String[] { getDisplayName(), serverUrl });
return client;
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Node call() throws Exception {
return KubernetesSlave
.builder()
.podTemplate(cloud.getUnwrappedTemplate(t))
.cloud(cloud)
.build();
} | #vulnerable code
public Node call() throws Exception {
RetentionStrategy retentionStrategy;
if (t.getIdleMinutes() == 0) {
retentionStrategy = new OnceRetentionStrategy(cloud.getRetentionTimeout());
} else {
retentionStrategy = new CloudRetentionStrategy(t.getIdleMinutes());
}
final PodTemplate unwrappedTemplate = PodTemplateUtils.unwrap(cloud.getTemplate(label),
cloud.getDefaultsProviderTemplate(), cloud.getTemplates());
return new KubernetesSlave(unwrappedTemplate, unwrappedTemplate.getName(), cloud.name,
unwrappedTemplate.getLabel(), retentionStrategy);
}
#location 11
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public boolean start() throws Exception {
Cloud cloud = Jenkins.get().getCloud(cloudName);
if (cloud == null) {
throw new AbortException(String.format("Cloud does not exist: %s", cloudName));
}
if (!(cloud instanceof KubernetesCloud)) {
throw new AbortException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName,
cloud.getClass().getName()));
}
KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud;
Run<?, ?> run = getContext().get(Run.class);
if (kubernetesCloud.isUsageRestricted()) {
checkAccess(run, kubernetesCloud);
}
PodTemplateContext podTemplateContext = getContext().get(PodTemplateContext.class);
String parentTemplates = podTemplateContext != null ? podTemplateContext.getName() : null;
String label = step.getLabel();
if (label == null) {
label = labelify(run.getExternalizableId());
}
//Let's generate a random name based on the user specified to make sure that we don't have
//issues with concurrent builds, or messing with pre-existing configuration
String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
String stepName = step.getName();
if (stepName == null) {
stepName = label;
}
String name = String.format(NAME_FORMAT, stepName, randString);
String namespace = checkNamespace(kubernetesCloud, podTemplateContext);
newTemplate = new PodTemplate();
newTemplate.setName(name);
newTemplate.setNamespace(namespace);
if (step.getInheritFrom() == null) {
newTemplate.setInheritFrom(Strings.emptyToNull(parentTemplates));
} else {
newTemplate.setInheritFrom(Strings.emptyToNull(step.getInheritFrom()));
}
newTemplate.setInstanceCap(step.getInstanceCap());
newTemplate.setIdleMinutes(step.getIdleMinutes());
newTemplate.setSlaveConnectTimeout(step.getSlaveConnectTimeout());
newTemplate.setLabel(label);
newTemplate.setEnvVars(step.getEnvVars());
newTemplate.setVolumes(step.getVolumes());
if (step.getWorkspaceVolume() != null) {
newTemplate.setWorkspaceVolume(step.getWorkspaceVolume());
}
newTemplate.setContainers(step.getContainers());
newTemplate.setNodeSelector(step.getNodeSelector());
newTemplate.setNodeUsageMode(step.getNodeUsageMode());
newTemplate.setServiceAccount(step.getServiceAccount());
newTemplate.setAnnotations(step.getAnnotations());
newTemplate.setYamlMergeStrategy(step.getYamlMergeStrategy());
if(run!=null) {
String url = ((KubernetesCloud)cloud).getJenkinsUrlOrNull();
if(url != null) {
newTemplate.getAnnotations().add(new PodAnnotation("buildUrl", url + run.getUrl()));
}
}
newTemplate.setImagePullSecrets(
step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList()));
newTemplate.setYaml(step.getYaml());
if (step.isShowRawYamlSet()) {
newTemplate.setShowRawYaml(step.isShowRawYaml());
}
newTemplate.setPodRetention(step.getPodRetention());
if(step.getActiveDeadlineSeconds() != 0) {
newTemplate.setActiveDeadlineSeconds(step.getActiveDeadlineSeconds());
}
for (ContainerTemplate container : newTemplate.getContainers()) {
if (!PodTemplateUtils.validateContainerName(container.getName())) {
throw new AbortException(Messages.RFC1123_error(container.getName()));
}
}
Collection<String> errors = PodTemplateUtils.validateYamlContainerNames(newTemplate.getYamls());
if (!errors.isEmpty()) {
throw new AbortException(Messages.RFC1123_error(String.join(", ", errors)));
}
// Note that after JENKINS-51248 this must be a single label atom, not a space-separated list, unlike PodTemplate.label generally.
if (!PodTemplateUtils.validateLabel(newTemplate.getLabel())) {
throw new AbortException(Messages.label_error(newTemplate.getLabel()));
}
kubernetesCloud.addDynamicTemplate(newTemplate);
BodyInvoker invoker = getContext().newBodyInvoker().withContexts(step, new PodTemplateContext(namespace, name)).withCallback(new PodTemplateCallback(newTemplate));
if (step.getLabel() == null) {
invoker.withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), EnvironmentExpander.constant(Collections.singletonMap("POD_LABEL", label))));
}
invoker.start();
return false;
} | #vulnerable code
@Override
public boolean start() throws Exception {
Cloud cloud = Jenkins.getInstance().getCloud(cloudName);
if (cloud == null) {
throw new AbortException(String.format("Cloud does not exist: %s", cloudName));
}
if (!(cloud instanceof KubernetesCloud)) {
throw new AbortException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName,
cloud.getClass().getName()));
}
KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud;
Run<?, ?> run = getContext().get(Run.class);
if (kubernetesCloud.isUsageRestricted()) {
checkAccess(run, kubernetesCloud);
}
PodTemplateContext podTemplateContext = getContext().get(PodTemplateContext.class);
String parentTemplates = podTemplateContext != null ? podTemplateContext.getName() : null;
String label = step.getLabel();
if (label == null) {
label = labelify(run.getExternalizableId());
}
//Let's generate a random name based on the user specified to make sure that we don't have
//issues with concurrent builds, or messing with pre-existing configuration
String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
String stepName = step.getName();
if (stepName == null) {
stepName = label;
}
String name = String.format(NAME_FORMAT, stepName, randString);
String namespace = checkNamespace(kubernetesCloud, podTemplateContext);
newTemplate = new PodTemplate();
newTemplate.setName(name);
newTemplate.setNamespace(namespace);
if (step.getInheritFrom() == null) {
newTemplate.setInheritFrom(Strings.emptyToNull(parentTemplates));
} else {
newTemplate.setInheritFrom(Strings.emptyToNull(step.getInheritFrom()));
}
newTemplate.setInstanceCap(step.getInstanceCap());
newTemplate.setIdleMinutes(step.getIdleMinutes());
newTemplate.setSlaveConnectTimeout(step.getSlaveConnectTimeout());
newTemplate.setLabel(label);
newTemplate.setEnvVars(step.getEnvVars());
newTemplate.setVolumes(step.getVolumes());
if (step.getWorkspaceVolume() != null) {
newTemplate.setWorkspaceVolume(step.getWorkspaceVolume());
}
newTemplate.setContainers(step.getContainers());
newTemplate.setNodeSelector(step.getNodeSelector());
newTemplate.setNodeUsageMode(step.getNodeUsageMode());
newTemplate.setServiceAccount(step.getServiceAccount());
newTemplate.setAnnotations(step.getAnnotations());
newTemplate.setYamlMergeStrategy(step.getYamlMergeStrategy());
if(run!=null) {
String url = ((KubernetesCloud)cloud).getJenkinsUrlOrNull();
if(url != null) {
newTemplate.getAnnotations().add(new PodAnnotation("buildUrl", url + run.getUrl()));
}
}
newTemplate.setImagePullSecrets(
step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList()));
newTemplate.setYaml(step.getYaml());
if (step.isShowRawYamlSet()) {
newTemplate.setShowRawYaml(step.isShowRawYaml());
}
newTemplate.setPodRetention(step.getPodRetention());
if(step.getActiveDeadlineSeconds() != 0) {
newTemplate.setActiveDeadlineSeconds(step.getActiveDeadlineSeconds());
}
for (ContainerTemplate container : newTemplate.getContainers()) {
if (!PodTemplateUtils.validateContainerName(container.getName())) {
throw new AbortException(Messages.RFC1123_error(container.getName()));
}
}
Collection<String> errors = PodTemplateUtils.validateYamlContainerNames(newTemplate.getYamls());
if (!errors.isEmpty()) {
throw new AbortException(Messages.RFC1123_error(String.join(", ", errors)));
}
// Note that after JENKINS-51248 this must be a single label atom, not a space-separated list, unlike PodTemplate.label generally.
if (!PodTemplateUtils.validateLabel(newTemplate.getLabel())) {
throw new AbortException(Messages.label_error(newTemplate.getLabel()));
}
kubernetesCloud.addDynamicTemplate(newTemplate);
BodyInvoker invoker = getContext().newBodyInvoker().withContexts(step, new PodTemplateContext(namespace, name)).withCallback(new PodTemplateCallback(newTemplate));
if (step.getLabel() == null) {
invoker.withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), EnvironmentExpander.constant(Collections.singletonMap("POD_LABEL", label))));
}
invoker.start();
return false;
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private boolean addProvisionedSlave(@Nonnull PodTemplate template, @CheckForNull Label label) throws Exception {
if (containerCap == 0) {
return true;
}
KubernetesClient client = connect();
String templateNamespace = template.getNamespace();
// If template's namespace is not defined, take the
// Kubernetes Namespace.
if (Strings.isNullOrEmpty(templateNamespace)) {
templateNamespace = client.getNamespace();
}
PodList slaveList = client.pods().inNamespace(templateNamespace).withLabels(getLabels()).list();
List<Pod> allActiveSlavePods = null;
// JENKINS-53370 check for nulls
if (slaveList != null && slaveList.getItems() != null) {
allActiveSlavePods = slaveList.getItems().stream() //
.filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
.collect(Collectors.toList());
}
Map<String, String> labelsMap = new HashMap<>(this.getLabels());
labelsMap.putAll(template.getLabelsMap());
PodList templateSlaveList = client.pods().inNamespace(templateNamespace).withLabels(labelsMap).list();
// JENKINS-53370 check for nulls
List<Pod> activeTemplateSlavePods = null;
if (templateSlaveList != null && templateSlaveList.getItems() != null) {
activeTemplateSlavePods = templateSlaveList.getItems().stream()
.filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
.collect(Collectors.toList());
}
if (allActiveSlavePods != null && containerCap <= allActiveSlavePods.size()) {
LOGGER.log(Level.INFO,
"Total container cap of {0} reached, not provisioning: {1} running or pending in namespace {2} with Kubernetes labels {3}",
new Object[] { containerCap, allActiveSlavePods.size(), templateNamespace, getLabels() });
return false;
}
if (activeTemplateSlavePods != null && allActiveSlavePods != null && template.getInstanceCap() <= activeTemplateSlavePods.size()) {
LOGGER.log(Level.INFO,
"Template instance cap of {0} reached for template {1}, not provisioning: {2} running or pending in namespace {3} with label \"{4}\" and Kubernetes labels {5}",
new Object[] { template.getInstanceCap(), template.getName(), allActiveSlavePods.size(),
templateNamespace, label == null ? "" : label.toString(), labelsMap });
return false;
}
return true;
} | #vulnerable code
private boolean addProvisionedSlave(@Nonnull PodTemplate template, @CheckForNull Label label) throws Exception {
if (containerCap == 0) {
return true;
}
KubernetesClient client = connect();
String templateNamespace = template.getNamespace();
// If template's namespace is not defined, take the
// Kubernetes Namespace.
if (Strings.isNullOrEmpty(templateNamespace)) {
templateNamespace = client.getNamespace();
}
PodList slaveList = client.pods().inNamespace(templateNamespace).withLabels(getLabels()).list();
List<Pod> allActiveSlavePods = null;
// JENKINS-53370 check for nulls
if (slaveList != null && slaveList.getItems() != null) {
allActiveSlavePods = slaveList.getItems().stream() //
.filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
.collect(Collectors.toList());
}
Map<String, String> labelsMap = new HashMap<>(this.getLabels());
labelsMap.putAll(template.getLabelsMap());
PodList templateSlaveList = client.pods().inNamespace(templateNamespace).withLabels(labelsMap).list();
List<Pod> activeTemplateSlavePods = templateSlaveList.getItems().stream()
.filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
.collect(Collectors.toList());
if (allActiveSlavePods != null && containerCap <= allActiveSlavePods.size()) {
LOGGER.log(Level.INFO,
"Total container cap of {0} reached, not provisioning: {1} running or pending in namespace {2} with Kubernetes labels {3}",
new Object[] { containerCap, allActiveSlavePods.size(), templateNamespace, getLabels() });
return false;
}
if (activeTemplateSlavePods != null && allActiveSlavePods != null && template.getInstanceCap() <= activeTemplateSlavePods.size()) {
LOGGER.log(Level.INFO,
"Template instance cap of {0} reached for template {1}, not provisioning: {2} running or pending in namespace {3} with label \"{4}\" and Kubernetes labels {5}",
new Object[] { template.getInstanceCap(), template.getName(), allActiveSlavePods.size(),
templateNamespace, label == null ? "" : label.toString(), labelsMap });
return false;
}
return true;
}
#location 26
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void runInPod() throws Exception {
SemaphoreStep.waitForStart("podTemplate/1", b);
List<PodTemplate> templates = podTemplatesWithLabel(name.getMethodName(), cloud.getAllTemplates());
assertThat(templates, hasSize(1));
SemaphoreStep.success("podTemplate/1", null);
// check if build failed
assertTrue("Build has failed early: " + b.getResult(), b.isBuilding() || Result.SUCCESS.equals(b.getResult()));
LOGGER.log(Level.INFO, "Found templates with label runInPod: {0}", templates);
for (PodTemplate template : cloud.getAllTemplates()) {
LOGGER.log(Level.INFO, "Cloud template \"{0}\" labels: {1}",
new Object[] { template.getName(), template.getLabelSet() });
}
Map<String, String> labels = getLabels(cloud, this, name);
SemaphoreStep.waitForStart("pod/1", b);
PodList pods = cloud.connect().pods().withLabels(labels).list();
assertThat(
"Expected one pod with labels " + labels + " but got: "
+ pods.getItems().stream().map(pod -> pod.getMetadata()).collect(Collectors.toList()),
pods.getItems(), hasSize(1));
SemaphoreStep.success("pod/1", null);
for (String msg : logs.getMessages()) {
System.out.println(msg);
}
PodTemplate template = templates.get(0);
List<PodAnnotation> annotations = template.getAnnotations();
assertNotNull(annotations);
boolean foundBuildUrl=false;
for(PodAnnotation pd : annotations)
{
if(pd.getKey().equals("buildUrl"))
{
assertTrue(pd.getValue().contains(p.getUrl()));
foundBuildUrl=true;
}
}
assertTrue(foundBuildUrl);
assertEquals(Integer.MAX_VALUE, template.getInstanceCap());
assertThat(template.getLabelsMap(), hasEntry("jenkins/" + name.getMethodName(), "true"));
Pod pod = pods.getItems().get(0);
LOGGER.log(Level.INFO, "One pod found: {0}", pod);
assertThat(pod.getMetadata().getLabels(), hasEntry("jenkins", "slave"));
assertThat("Pod labels are wrong: " + pod, pod.getMetadata().getLabels(), hasEntry("jenkins/" + name.getMethodName(), "true"));
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("script file contents: ", b);
assertFalse("There are pods leftover after test execution, see previous logs",
deletePods(cloud.connect(), getLabels(cloud, this, name), true));
} | #vulnerable code
@Test
public void runInPod() throws Exception {
List<PodTemplate> templates = null;
while (b.isBuilding() && (templates = podTemplatesWithLabel(name.getMethodName(), cloud.getAllTemplates())).isEmpty()) {
LOGGER.log(Level.INFO, "Waiting for runInPod template to be created");
Thread.sleep(1000);
}
// check if build failed
assertTrue("Build has failed early: " + b.getResult(), b.isBuilding() || Result.SUCCESS.equals(b.getResult()));
LOGGER.log(Level.INFO, "Found templates with label runInPod: {0}", templates);
for (PodTemplate template : cloud.getAllTemplates()) {
LOGGER.log(Level.INFO, "Cloud template \"{0}\" labels: {1}",
new Object[] { template.getName(), template.getLabelSet() });
}
Map<String, String> labels = getLabels(cloud, this, name);
PodList pods = new PodListBuilder().withItems(Collections.emptyList()).build();
while (pods.getItems().isEmpty()) {
LOGGER.log(Level.INFO, "Waiting for pods to be created with labels: {0}", labels);
pods = cloud.connect().pods().withLabels(labels).list();
Thread.sleep(1000);
}
for (String msg : logs.getMessages()) {
System.out.println(msg);
}
assertThat(templates, hasSize(1));
PodTemplate template = templates.get(0);
List<PodAnnotation> annotations = template.getAnnotations();
assertNotNull(annotations);
boolean foundBuildUrl=false;
for(PodAnnotation pd : annotations)
{
if(pd.getKey().equals("buildUrl"))
{
assertTrue(pd.getValue().contains(p.getUrl()));
foundBuildUrl=true;
}
}
assertTrue(foundBuildUrl);
assertEquals(Integer.MAX_VALUE, template.getInstanceCap());
assertThat(template.getLabelsMap(), hasEntry("jenkins/" + name.getMethodName(), "true"));
assertThat(
"Expected one pod with labels " + labels + " but got: "
+ pods.getItems().stream().map(pod -> pod.getMetadata()).collect(Collectors.toList()),
pods.getItems(), hasSize(1));
Pod pod = pods.getItems().get(0);
LOGGER.log(Level.INFO, "One pod found: {0}", pod);
assertThat(pod.getMetadata().getLabels(), hasEntry("jenkins", "slave"));
assertThat("Pod labels are wrong: " + pod, pod.getMetadata().getLabels(), hasEntry("jenkins/" + name.getMethodName(), "true"));
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("script file contents: ", b);
assertFalse("There are pods leftover after test execution, see previous logs",
deletePods(cloud.connect(), getLabels(cloud, this, name), true));
}
#location 31
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) {
if (!isAvailable(conversionQuery)) {
return null;
}
CurrencyUnit base = conversionQuery.getBaseCurrency();
CurrencyUnit term = conversionQuery.getCurrency();
LocalDate timestamp = getTimeStamp(conversionQuery);
ExchangeRate rate1 = lookupRate(currencyToSdr.get(base), timestamp);
ExchangeRate rate2 = lookupRate(sdrToCurrency.get(term), timestamp);
if (base.equals(SDR)) {
return rate2;
} else if (term.equals(SDR)) {
return rate1;
}
if (Objects.isNull(rate1) || Objects.isNull(rate2)) {
return null;
}
ExchangeRateBuilder builder =
new ExchangeRateBuilder(ConversionContext.of(CONTEXT.getProviderName(), RateType.HISTORIC));
builder.setBase(base);
builder.setTerm(term);
builder.setFactor(multiply(rate1.getFactor(), rate2.getFactor()));
builder.setRateChain(rate1, rate2);
return builder.build();
} | #vulnerable code
@Override
public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) {
if (!isAvailable(conversionQuery)) {
return null;
}
CurrencyUnit base = conversionQuery.getBaseCurrency();
CurrencyUnit term = conversionQuery.getCurrency();
LocalDate timestamp = conversionQuery.get(LocalDate.class);
if (timestamp == null) {
LocalDateTime dateTime = conversionQuery.get(LocalDateTime.class);
if (dateTime != null) {
timestamp = dateTime.toLocalDate();
}
}
ExchangeRate rate1 = lookupRate(currencyToSdr.get(base), timestamp);
ExchangeRate rate2 = lookupRate(sdrToCurrency.get(term), timestamp);
if (base.equals(SDR)) {
return rate2;
} else if (term.equals(SDR)) {
return rate1;
}
if (Objects.isNull(rate1) || Objects.isNull(rate2)) {
return null;
}
ExchangeRateBuilder builder =
new ExchangeRateBuilder(ConversionContext.of(CONTEXT.getProviderName(), RateType.HISTORIC));
builder.setBase(base);
builder.setTerm(term);
builder.setFactor(multiply(rate1.getFactor(), rate2.getFactor()));
builder.setRateChain(rate1, rate2);
return builder.build();
}
#location 29
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void run() {
serverLog.logSystem("PLASMA INDEXING", "started word cache management");
int check;
// permanently flush cache elements
while (!(terminate)) {
if (hashScore.size() < 100) try {Thread.currentThread().sleep(10000);} catch (InterruptedException e) {}
while ((!(terminate)) && (cache != null) && (hashScore.size() > 0)) try {
check = hashScore.size();
flushSpecific(false);
//serverLog.logDebug("PLASMA INDEXING", "single flush. bevore=" + check + "; after=" + hashScore.size());
try {Thread.currentThread().sleep(10 + ((maxWords / 10) / (1 + hashScore.size())));} catch (InterruptedException e) {}
} catch (IOException e) {
serverLog.logError("PLASMA INDEXING", "PANIK! exception in main cache loop: " + e.getMessage());
e.printStackTrace();
terminate = true;
cache = null;
}
}
serverLog.logSystem("PLASMA INDEXING", "CATCHED TERMINATION SIGNAL: start final flush");
// close all;
try {
// first flush everything
while ((hashScore.size() > 0) && (System.currentTimeMillis() < terminateUntil)) {
flushSpecific(false);
}
// then close file cache:
pic.close();
} catch (IOException e) {
serverLog.logDebug("PLASMA INDEXING", "interrupted final flush: " + e.toString());
}
// report
if (hashScore.size() == 0)
serverLog.logSystem("PLASMA INDEXING", "finished final flush; flushed all words");
else
serverLog.logError("PLASMA INDEXING", "terminated final flush; " + hashScore.size() + " words lost");
// delete data
cache = null;
hashScore = null;
} | #vulnerable code
public void run() {
serverLog.logSystem("PLASMA INDEXING", "started word cache management");
int check;
// permanently flush cache elements
while (!(terminate)) {
if (hashScore.size() < 100) try {Thread.currentThread().sleep(10000);} catch (InterruptedException e) {}
while ((!(terminate)) && (cache != null) && (hashScore.size() > 0)) try {
//check = hashScore.size();
flushSpecific(false);
//serverLog.logDebug("PLASMA INDEXING", "single flush. bevore=" + check + "; after=" + hashScore.size());
try {Thread.currentThread().sleep(10 + ((maxWords / 10) / (1 + hashScore.size())));} catch (InterruptedException e) {}
} catch (IOException e) {
serverLog.logError("PLASMA INDEXING", "PANIK! exception in main cache loop: " + e.getMessage());
e.printStackTrace();
terminate = true;
cache = null;
}
}
serverLog.logSystem("PLASMA INDEXING", "CATCHED TERMINATION SIGNAL: start final flush");
// close all;
try {
// first flush everything
while ((hashScore.size() > 0) && (System.currentTimeMillis() < terminateUntil)) {
flushSpecific(false);
}
// then close file cache:
pic.close();
} catch (IOException e) {
serverLog.logDebug("PLASMA INDEXING", "interrupted final flush: " + e.toString());
}
// report
if (hashScore.size() == 0)
serverLog.logSystem("PLASMA INDEXING", "finished final flush; flushed all words");
else
serverLog.logError("PLASMA INDEXING", "terminated final flush; " + hashScore.size() + " words lost");
// delete data
cache = null;
hashScore = null;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public String readLine() throws IOException {
// with these functions, we consider a line as always terminated by CRLF
byte[] bb = new byte[80];
int bbsize = 0;
int c;
while (true) {
c = read();
if (c < 0) {
if (bbsize == 0) return null; else return new String(bb, 0, bbsize);
}
if (c == cr) continue;
if (c == lf) return new String(bb, 0, bbsize);
// append to bb
if (bbsize == bb.length) {
// extend bb size
byte[] newbb = new byte[bb.length * 2];
System.arraycopy(bb, 0, newbb, 0, bb.length);
bb = newbb;
newbb = null;
}
bb[bbsize++] = (byte) c;
}
} | #vulnerable code
public String readLine() throws IOException {
// with these functions, we consider a line as always terminated by CRLF
serverByteBuffer sb = new serverByteBuffer();
int c;
while (true) {
c = read();
if (c < 0) {
if (sb.length() == 0) return null; else return sb.toString();
}
if (c == cr) continue;
if (c == lf) return sb.toString();
sb.append((byte) c);
}
}
#location 8
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void respondError(OutputStream respond, String origerror, int errorcase, String url) {
FileInputStream fis = null;
try {
// set rewrite values
serverObjects tp = new serverObjects();
tp.put("errormessage", errorcase);
tp.put("httperror", origerror);
tp.put("url", url);
// rewrite the file
File file = new File(htRootPath, "/proxymsg/error.html");
byte[] result;
ByteArrayOutputStream o = new ByteArrayOutputStream();
fis = new FileInputStream(file);
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes());
o.close();
result = o.toByteArray();
// return header
httpHeader header = new httpHeader();
header.put("Date", httpc.dateString(httpc.nowDate()));
header.put("Content-type", "text/html");
header.put("Content-length", "" + o.size());
header.put("Pragma", "no-cache");
// write the array to the client
respondHeader(respond, origerror, header);
serverFileUtils.write(result, respond);
respond.flush();
} catch (IOException e) {
} finally {
if (fis != null) try { fis.close(); } catch (Exception e) {}
}
} | #vulnerable code
private void respondError(OutputStream respond, String origerror, int errorcase, String url) {
try {
// set rewrite values
serverObjects tp = new serverObjects();
tp.put("errormessage", errorcase);
tp.put("httperror", origerror);
tp.put("url", url);
// rewrite the file
File file = new File(htRootPath, "/proxymsg/error.html");
byte[] result;
ByteArrayOutputStream o = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(file);
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes());
o.close();
result = o.toByteArray();
// return header
httpHeader header = new httpHeader();
header.put("Date", httpc.dateString(httpc.nowDate()));
header.put("Content-type", "text/html");
header.put("Content-length", "" + o.size());
header.put("Pragma", "no-cache");
// write the array to the client
respondHeader(respond, origerror, header);
serverFileUtils.write(result, respond);
respond.flush();
} catch (IOException e) {
}
}
#location 14
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private static TreeMap loadMap(String mapname, String filename, String sep) {
TreeMap map = new TreeMap();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
String line;
int pos;
while ((line = br.readLine()) != null) {
line = line.trim();
if ((line.length() > 0) && (!(line.startsWith("#"))) && ((pos = line.indexOf(sep)) > 0))
map.put(line.substring(0, pos).trim().toLowerCase(), line.substring(pos + sep.length()).trim());
}
serverLog.logInfo("PROXY", "read " + mapname + " map from file " + filename);
} catch (IOException e) {
} finally {
if (br != null) try { br.close(); } catch (Exception e) {}
}
return map;
} | #vulnerable code
private static TreeMap loadMap(String mapname, String filename, String sep) {
TreeMap map = new TreeMap();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
String line;
int pos;
while ((line = br.readLine()) != null) {
line = line.trim();
if ((line.length() > 0) && (!(line.startsWith("#"))) && ((pos = line.indexOf(sep)) > 0))
map.put(line.substring(0, pos).trim().toLowerCase(), line.substring(pos + sep.length()).trim());
}
br.close();
serverLog.logInfo("PROXY", "read " + mapname + " map from file " + filename);
} catch (IOException e) {}
return map;
}
#location 14
#vulnerability type RESOURCE_LEAK |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.