output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
@SuppressWarnings( "ConstantConditions" )
@Test
public void shouldHandleNullAuthToken() throws Throwable
{
// Given
AuthToken token = null;
try ( Driver driver = GraphDatabase.driver( neo4j.address(), token ) )
{
Session session = driver.session();
// When
session.close();
// Then
assertFalse( session.isOpen() );
}
} | #vulnerable code
@SuppressWarnings( "ConstantConditions" )
@Test
public void shouldHandleNullAuthToken() throws Throwable
{
// Given
AuthToken token = null;
Driver driver = GraphDatabase.driver( neo4j.address(), token);
Session session = driver.session();
// When
session.close();
// Then
assertFalse( session.isOpen() );
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void shouldContainTimeInformation()
{
// Given
ResultSummary summary = session.run( "UNWIND range(1,1000) AS n RETURN n AS number" ).consume();
// Then
assertThat( summary.resultAvailableAfter( TimeUnit.MILLISECONDS ), greaterThanOrEqualTo( 0L ) );
assertThat( summary.resultConsumedAfter( TimeUnit.MILLISECONDS ), greaterThanOrEqualTo( 0L ) );
} | #vulnerable code
@Test
void shouldContainTimeInformation()
{
// Given
ResultSummary summary = session.run( "UNWIND range(1,1000) AS n RETURN n AS number" ).consume();
// Then
ServerVersion serverVersion = ServerVersion.version( summary.server().version() );
if ( STATEMENT_RESULT_TIMINGS.availableIn( serverVersion ) )
{
assertThat( summary.resultAvailableAfter( TimeUnit.MILLISECONDS ), greaterThanOrEqualTo( 0L ) );
assertThat( summary.resultConsumedAfter( TimeUnit.MILLISECONDS ), greaterThanOrEqualTo( 0L ) );
}
else
{
//Not passed through by older versions of the server
assertThat( summary.resultAvailableAfter( TimeUnit.MILLISECONDS ), equalTo( -1L ) );
assertThat( summary.resultConsumedAfter( TimeUnit.MILLISECONDS ), equalTo( -1L ) );
}
}
#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 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 8
#vulnerability type RESOURCE_LEAK | 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 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void saveX509Cert( Certificate[] certs, File certFile ) throws GeneralSecurityException, IOException
{
try ( BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) ) )
{
for ( Certificate cert : certs )
{
String certStr = Base64.getEncoder().encodeToString( cert.getEncoded() ).replaceAll( "(.{64})", "$1\n" );
writer.write( BEGIN_CERT );
writer.newLine();
writer.write( certStr );
writer.newLine();
writer.write( END_CERT );
writer.newLine();
}
}
} | #vulnerable code
public static void saveX509Cert( Certificate[] certs, File certFile ) throws GeneralSecurityException, IOException
{
BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) );
for ( Certificate cert : certs )
{
String certStr = Base64.getEncoder().encodeToString( cert.getEncoded() ).replaceAll( "(.{64})", "$1\n" );
writer.write( BEGIN_CERT );
writer.newLine();
writer.write( certStr );
writer.newLine();
writer.write( END_CERT );
writer.newLine();
}
writer.close();
}
#location 17
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldKnowSessionIsClosed() throws Throwable
{
// Given
try( Driver driver = GraphDatabase.driver( neo4j.address() ) )
{
Session session = driver.session();
// When
session.close();
// Then
assertFalse( session.isOpen() );
}
} | #vulnerable code
@Test
public void shouldKnowSessionIsClosed() throws Throwable
{
// Given
Driver driver = GraphDatabase.driver( neo4j.address() );
Session session = driver.session();
// When
session.close();
// Then
assertFalse( session.isOpen() );
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldBeAbleToUseSessionAgainWhenTransactionIsClosed() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( true );
sess.beginTransaction().close();
// When
sess.run( "whatever" );
// Then
verify( mock ).sync();
} | #vulnerable code
@Test
public void shouldBeAbleToUseSessionAgainWhenTransactionIsClosed() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( true );
InternalSession sess = new InternalSession( mock );
sess.beginTransaction().close();
// When
sess.run( "whatever" );
// Then
verify( mock ).sync();
}
#location 15
#vulnerability type RESOURCE_LEAK | 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( "not_reuse_connection.script", 9001 );
//START servers
StubServer readServer = StubServer.start( "empty.script", 9002 );
StubServer writeServer1 = StubServer.start( "dead_server.script", 9003 );
StubServer writeServer2 = StubServer.start( "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 = ((NetworkSession) ((RoutingNetworkSession) readSession).delegate).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( "not_reuse_connection.script", 9001 );
//START servers
StubServer readServer = StubServer.start( "empty.script", 9002 );
StubServer writeServer1 = StubServer.start( "dead_server.script", 9003 );
StubServer writeServer2 = StubServer.start( "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 ) );
}
#location 26
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldNotCloseSessionFactoryMultipleTimes()
{
SessionFactory sessionFactory = sessionFactoryMock();
InternalDriver driver = newDriver( sessionFactory );
assertNull( await( driver.closeAsync() ) );
assertNull( await( driver.closeAsync() ) );
assertNull( await( driver.closeAsync() ) );
verify( sessionFactory ).close();
} | #vulnerable code
@Test
public void shouldNotCloseSessionFactoryMultipleTimes()
{
SessionFactory sessionFactory = sessionFactoryMock();
InternalDriver driver = newDriver( sessionFactory );
assertNull( getBlocking( driver.closeAsync() ) );
assertNull( getBlocking( driver.closeAsync() ) );
assertNull( getBlocking( driver.closeAsync() ) );
verify( sessionFactory ).close();
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void shouldSendReadAccessModeInStatementMetadata() throws Exception
{
StubServer server = StubServer.start( "hello_run_exit_read.script", 9001 );
try ( Driver driver = GraphDatabase.driver( "bolt://localhost:9001", INSECURE_CONFIG );
Session session = driver.session( AccessMode.READ ) )
{
List<String> names = session.run( "MATCH (n) RETURN n.name" ).list( record -> record.get( 0 ).asString() );
assertEquals( asList( "Foo", "Bar" ), names );
}
finally
{
assertEquals( 0, server.exitStatus() );
}
} | #vulnerable code
@Test
void shouldSendReadAccessModeInStatementMetadata() throws Exception
{
StubServer server = StubServer.start( "hello_run_exit_read.script", 9001 );
Config config = Config.builder()
.withoutEncryption()
.build();
try ( Driver driver = GraphDatabase.driver( "bolt://localhost:9001", config );
Session session = driver.session( AccessMode.READ ) )
{
List<String> names = session.run( "MATCH (n) RETURN n.name" ).list( record -> record.get( 0 ).asString() );
assertEquals( asList( "Foo", "Bar" ), names );
}
finally
{
assertEquals( 0, server.exitStatus() );
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldExplainConnectionError() throws Throwable
{
// Expect
exception.expect( ClientException.class );
exception.expectMessage( "Unable to connect to 'localhost' on port 7777, ensure the database is running " +
"and that there is a working network connection to it." );
// When
try ( Driver driver = GraphDatabase.driver( "bolt://localhost:7777" );
Session session = driver.session()) {}
} | #vulnerable code
@Test
public void shouldExplainConnectionError() throws Throwable
{
// Expect
exception.expect( ClientException.class );
exception.expectMessage( "Unable to connect to 'localhost' on port 7777, ensure the database is running " +
"and that there is a working network connection to it." );
// When
try ( Driver driver = GraphDatabase.driver( "bolt://localhost:7777" ) )
{
driver.session();
}
}
#location 12
#vulnerability type RESOURCE_LEAK | 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
@Test
public void shouldNotPutBackPurgedConnection() throws IOException, InterruptedException, StubServer.ForceKilled
{
// Given
StubServer server = StubServer.start( "not_reuse_connection.script", 9001 );
//START servers
StubServer readServer = StubServer.start( "empty.script", 9002 );
StubServer writeServer1 = StubServer.start( "dead_server.script", 9003 );
StubServer writeServer2 = StubServer.start( "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 = ((NetworkSession) ((RoutingNetworkSession) readSession).delegate).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( "not_reuse_connection.script", 9001 );
//START servers
StubServer readServer = StubServer.start( "empty.script", 9002 );
StubServer writeServer1 = StubServer.start( "dead_server.script", 9003 );
StubServer writeServer2 = StubServer.start( "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 ) );
}
#location 25
#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 shouldSyncOnRun() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( true );
InternalSession sess = new InternalSession( mock );
// When
sess.run( "whatever" );
// Then
verify( mock ).sync();
} | #vulnerable code
@Test
public void shouldSyncOnRun() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
InternalSession sess = new InternalSession( mock );
// When
sess.run( "whatever" );
// Then
verify( mock ).sync();
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldLoadCSV() throws Throwable
{
// Given
try( Driver driver = GraphDatabase.driver( neo4j.address() );
Session session = driver.session() )
{
String csvFileUrl = createLocalIrisData( session );
// When
StatementResult result = session.run(
"USING PERIODIC COMMIT 40\n" +
"LOAD CSV WITH HEADERS FROM {csvFileUrl} AS l\n" +
"MATCH (c:Class {name: l.class_name})\n" +
"CREATE (s:Sample {sepal_length: l.sepal_length, sepal_width: l.sepal_width, petal_length: l.petal_length, petal_width: l.petal_width})\n" +
"CREATE (c)<-[:HAS_CLASS]-(s) " +
"RETURN count(*) AS c",
parameters( "csvFileUrl", csvFileUrl ) );
// Then
assertThat( result.next().get( "c" ).asInt(), equalTo( 150 ) );
assertFalse( result.hasNext() );
}
} | #vulnerable code
@Test
public void shouldLoadCSV() throws Throwable
{
// Given
Driver driver = GraphDatabase.driver( neo4j.address() );
Session session = driver.session();
String csvFileUrl = createLocalIrisData( session );
// When
StatementResult result = session.run(
"USING PERIODIC COMMIT 40\n" +
"LOAD CSV WITH HEADERS FROM {csvFileUrl} AS l\n" +
"MATCH (c:Class {name: l.class_name})\n" +
"CREATE (s:Sample {sepal_length: l.sepal_length, sepal_width: l.sepal_width, petal_length: l.petal_length, petal_width: l.petal_width})\n" +
"CREATE (c)<-[:HAS_CLASS]-(s) " +
"RETURN count(*) AS c",
parameters( "csvFileUrl", csvFileUrl ) );
// Then
assertThat( result.next().get( "c" ).asInt(), equalTo( 150 ) );
assertFalse( result.hasNext() );
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldNotAllowMoreStatementsInSessionWhileConnectionClosed() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( false );
// Expect
exception.expect( ClientException.class );
// When
sess.run( "whatever" );
} | #vulnerable code
@Test
public void shouldNotAllowMoreStatementsInSessionWhileConnectionClosed() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( false );
InternalSession sess = new InternalSession( mock );
// Expect
exception.expect( ClientException.class );
// When
sess.run( "whatever" );
}
#location 13
#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
void shouldNotSendWriteAccessModeInStatementMetadata() throws Exception
{
StubServer server = StubServer.start( "hello_run_exit.script", 9001 );
try ( Driver driver = GraphDatabase.driver( "bolt://localhost:9001", INSECURE_CONFIG );
Session session = driver.session( AccessMode.WRITE ) )
{
List<String> names = session.run( "MATCH (n) RETURN n.name" ).list( record -> record.get( 0 ).asString() );
assertEquals( asList( "Foo", "Bar" ), names );
}
finally
{
assertEquals( 0, server.exitStatus() );
}
} | #vulnerable code
@Test
void shouldNotSendWriteAccessModeInStatementMetadata() throws Exception
{
StubServer server = StubServer.start( "hello_run_exit.script", 9001 );
Config config = Config.builder()
.withoutEncryption()
.build();
try ( Driver driver = GraphDatabase.driver( "bolt://localhost:9001", config );
Session session = driver.session( AccessMode.WRITE ) )
{
List<String> names = session.run( "MATCH (n) RETURN n.name" ).list( record -> record.get( 0 ).asString() );
assertEquals( asList( "Foo", "Bar" ), names );
}
finally
{
assertEquals( 0, server.exitStatus() );
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void load() throws IOException
{
if ( !knownHosts.exists() )
{
return;
}
assertKnownHostFileReadable();
try ( BufferedReader reader = new BufferedReader( new FileReader( knownHosts ) ) )
{
String line;
while ( (line = reader.readLine()) != null )
{
if ( (!line.trim().startsWith( "#" )) )
{
String[] strings = line.split( " " );
if ( strings[0].trim().equals( serverId ) )
{
// load the certificate
fingerprint = strings[1].trim();
return;
}
}
}
}
} | #vulnerable code
private void load() throws IOException
{
if ( !knownHosts.exists() )
{
return;
}
assertKnownHostFileReadable();
BufferedReader reader = new BufferedReader( new FileReader( knownHosts ) );
String line;
while ( (line = reader.readLine()) != null )
{
if ( (!line.trim().startsWith( "#" )) )
{
String[] strings = line.split( " " );
if ( strings[0].trim().equals( serverId ) )
{
// load the certificate
fingerprint = strings[1].trim();
return;
}
}
}
reader.close();
}
#location 20
#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
@Test
public void shouldGetHelpfulErrorWhenTryingToConnectToHttpPort() throws Throwable
{
// Given
//the http server needs some time to start up
Thread.sleep( 2000 );
try( Driver driver = GraphDatabase.driver( "bolt://localhost:7474",
Config.build().withEncryptionLevel( Config.EncryptionLevel.NONE ).toConfig() ) )
{
// Expect
exception.expect( ClientException.class );
exception.expectMessage(
"Server responded HTTP. Make sure you are not trying to connect to the http endpoint " +
"(HTTP defaults to port 7474 whereas BOLT defaults to port 7687)" );
// When
try(Session session = driver.session() ){}
}
} | #vulnerable code
@Test
public void shouldGetHelpfulErrorWhenTryingToConnectToHttpPort() throws Throwable
{
// Given
//the http server needs some time to start up
Thread.sleep( 2000 );
Driver driver = GraphDatabase.driver( "bolt://localhost:7474", Config.build().withEncryptionLevel(
Config.EncryptionLevel.NONE ).toConfig());
// Expect
exception.expect( ClientException.class );
exception.expectMessage( "Server responded HTTP. Make sure you are not trying to connect to the http endpoint " +
"(HTTP defaults to port 7474 whereas BOLT defaults to port 7687)" );
// When
driver.session();
}
#location 16
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
Config config = Config.build().withEncryptionLevel( Config.EncryptionLevel.REQUIRED ).toConfig();
try( Driver driver = GraphDatabase.driver( URI.create( Neo4jRunner.DEFAULT_URL ), config );
Session session = driver.session() )
{
StatementResult result = session.run( "RETURN 1" );
assertEquals( 1, result.next().get( 0 ).asInt() );
assertFalse( result.hasNext() );
}
} | #vulnerable code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
Config config = Config.build().withEncryptionLevel( Config.EncryptionLevel.REQUIRED ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
StatementResult result = driver.session().run( "RETURN 1" );
assertEquals( 1, result.next().get( 0 ).asInt() );
assertFalse( result.hasNext() );
driver.close();
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFields() throws Exception
{
// GIVEN
ResultBuilder builder = new ResultBuilder( "<unknown>", ParameterSupport.NO_PARAMETERS );
builder.keys( new String[]{"k1"} );
builder.record( new Value[]{value(42)} );
ResultCursor result = builder.build();
result.first();
// WHEN
List<Entry<Integer>> fields = Extract.fields( result, integerExtractor() );
// THEN
assertThat( fields, equalTo( Collections.singletonList( InternalEntry.of( "k1", 42 ) ) ) );
} | #vulnerable code
@Test
public void testFields() throws Exception
{
// GIVEN
ResultBuilder builder = new ResultBuilder( "<unknown>", ParameterSupport.NO_PARAMETERS );
builder.keys( new String[]{"k1"} );
builder.record( new Value[]{value(42)} );
Result result = builder.build();
result.first();
// WHEN
List<Entry<Integer>> fields = Extract.fields( result, integerExtractor() );
// THEN
assertThat( fields, equalTo( Collections.singletonList( InternalEntry.of( "k1", 42 ) ) ) );
}
#location 12
#vulnerability type RESOURCE_LEAK | 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( "not_reuse_connection.script", 9001 );
//START servers
StubServer readServer = StubServer.start( "empty.script", 9002 );
StubServer writeServer1 = StubServer.start( "dead_server.script", 9003 );
StubServer writeServer2 = StubServer.start( "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 = ((NetworkSession) ((RoutingNetworkSession) readSession).delegate).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( "not_reuse_connection.script", 9001 );
//START servers
StubServer readServer = StubServer.start( "empty.script", 9002 );
StubServer writeServer1 = StubServer.start( "dead_server.script", 9003 );
StubServer writeServer2 = StubServer.start( "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 ) );
}
#location 22
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void connectThrowsForUnknownAuthToken()
{
ConnectionSettings settings = new ConnectionSettings( mock( AuthToken.class ) );
RecordingSocketConnector connector = new RecordingSocketConnector( settings );
try
{
connector.connect( LOCAL_DEFAULT );
fail( "Exception expected" );
}
catch ( Exception e )
{
assertThat( e, instanceOf( ClientException.class ) );
}
} | #vulnerable code
@Test
public void connectThrowsForUnknownAuthToken()
{
ConnectionSettings settings = new ConnectionSettings( mock( AuthToken.class ) );
TestSocketConnector connector = new TestSocketConnector( settings, insecure(), loggingMock() );
try
{
connector.connect( LOCAL_DEFAULT );
fail( "Exception expected" );
}
catch ( Exception e )
{
assertThat( e, instanceOf( ClientException.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 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 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
private int runRuby(File ruFile, String[] stmts, String[] scriptPaths) {
int exitCode = 0;
String stmt = "";
boolean fromIDE = false;
String filename = "<script>";
try {
if (null == ruFile) {
log(lvl, "runRuby: running statements");
StringBuilder buffer = new StringBuilder();
for (String e : stmts) {
buffer.append(e);
}
interpreter.setScriptFilename(filename);
interpreter.runScriptlet(buffer.toString());
} else {
filename = ruFile.getAbsolutePath();
if (scriptPaths != null) {
BufferedReader script = new BufferedReader(
new InputStreamReader(
new FileInputStream(ruFile.getAbsolutePath()), "UTF-8"));
// TODO implement compile only !!!
if (scriptPaths[0].toUpperCase().equals(COMPILE_ONLY)) {
log(lvl, "runRuby: running COMPILE_ONLY");
EvalUnit unit = interpreter.parse(script, filename);
//unit.run();
} else {
if (scriptPaths.length > 1) {
filename = FileManager.slashify(scriptPaths[0], true)
+ scriptPaths[1] + ".sikuli";
log(lvl, "runRuby: running script from IDE: \n" + filename);
fromIDE = true;
} else {
filename = scriptPaths[0];
log(lvl, "runRuby: running script: \n" + filename);
}
interpreter.runScriptlet(script, filename);
}
} else {
log(-1, "runRuby: invalid arguments");
exitCode = -1;
}
}
} catch (Exception e) {
java.util.regex.Pattern p
= java.util.regex.Pattern.compile("SystemExit: ([0-9]+)");
Matcher matcher = p.matcher(e.toString());
//TODO error stop I18N
if (matcher.find()) {
exitCode = Integer.parseInt(matcher.group(1));
Debug.info("Exit code: " + exitCode);
} else {
//log(-1,_I("msgStopped"));
if (null != ruFile) {
exitCode = findErrorSource(e, filename, scriptPaths);
} else {
Debug.error("runRuby: Ruby exception: %s with %s", e.getMessage(), stmt);
}
if (fromIDE) {
exitCode *= -1;
} else {
exitCode = 1;
}
}
}
return exitCode;
} | #vulnerable code
private int runRuby(File ruFile, String[] stmts, String[] scriptPaths) {
int exitCode = 0;
String stmt = "";
boolean fromIDE = false;
String filename = "<script>";
try {
if (null == ruFile) {
log(lvl, "runRuby: running statements");
StringBuilder buffer = new StringBuilder();
for (String e : stmts) {
buffer.append(e);
}
interpreter.setScriptFilename(filename);
interpreter.runScriptlet(buffer.toString());
} else {
filename = ruFile.getAbsolutePath();
if (scriptPaths != null) {
FileReader script = new FileReader(ruFile.getAbsolutePath());
// TODO implement compile only !!!
if (scriptPaths[0].toUpperCase().equals(COMPILE_ONLY)) {
log(lvl, "runRuby: running COMPILE_ONLY");
EvalUnit unit = interpreter.parse(script, filename);
//unit.run();
} else {
if (scriptPaths.length > 1) {
filename = FileManager.slashify(scriptPaths[0], true)
+ scriptPaths[1] + ".sikuli";
log(lvl, "runRuby: running script from IDE: \n" + filename);
fromIDE = true;
} else {
filename = scriptPaths[0];
log(lvl, "runRuby: running script: \n" + filename);
}
interpreter.runScriptlet(script, filename);
}
} else {
log(-1, "runRuby: invalid arguments");
exitCode = -1;
}
}
} catch (Exception e) {
java.util.regex.Pattern p
= java.util.regex.Pattern.compile("SystemExit: ([0-9]+)");
Matcher matcher = p.matcher(e.toString());
//TODO error stop I18N
if (matcher.find()) {
exitCode = Integer.parseInt(matcher.group(1));
Debug.info("Exit code: " + exitCode);
} else {
//log(-1,_I("msgStopped"));
if (null != ruFile) {
exitCode = findErrorSource(e, filename, scriptPaths);
} else {
Debug.error("runRuby: Ruby exception: %s with %s", e.getMessage(), stmt);
}
if (fromIDE) {
exitCode *= -1;
} else {
exitCode = 1;
}
}
}
return exitCode;
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public ScreenImage capture(Rectangle rect) {
Debug.log(3, "ScreenUnion: capture: " + rect);
Screen s = Screen.getPrimaryScreen();
Location tl = new Location(rect.getLocation());
for (Screen sx : Screen.screens) {
if (sx.contains(tl)) {
s = sx;
break;
}
}
ScreenImage si = s.capture(rect);
return si;
} | #vulnerable code
@Override
public ScreenImage capture(Rectangle rect) {
Debug.log(3, "ScreenUnion: capture: " + rect);
return Region.create(rect).getScreen().capture(rect);
}
#location 4
#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
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 64
#vulnerability type THREAD_SAFETY_VIOLATION | 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", 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();
Debug.on(3);
Settings.InfoLogs = false;
Settings.ActionLogs = false;
App.focus("NetBeans");
File aFile = rt.fSxProject;
rt.addToClasspath(new File(aFile, "Setup/target/Setup/sikulix.jar").getPath());
String aClass = "org.sikuli.ide.SikuliIDE";
String res = "sikulixtessdata/sikulixcontent";
URL aURL = rt.resourceLocation(res, aClass);
Screen s = new Screen();
ImagePath.add("org.sikuli.script.Sikulix/ImagesAPI.sikuli");
Image.dump();
Match m = s.find("netblogo");
// s.hover();
Settings.OcrTextRead = true;
String t = m.right(1000).highlight(2).text();
log(3, "|%s|", t);
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", 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();
Debug.on(3);
Settings.InfoLogs = false;
Settings.ActionLogs = false;
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 37
#vulnerability type NULL_DEREFERENCE | 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
<PatternString> Component createTargetComponent(org.sikuli.script.Image img) {
JLabel cause = null;
JPanel dialog = new JPanel();
dialog.setLayout(new BorderLayout());
if (img.isValid()) {
if (!img.isText()) {
Image bimage = img.get(false);
if (bimage != null) {
String rescale = "";
JLabel iconLabel = new JLabel();
int w = bimage.getWidth(this);
int h = bimage.getHeight(this);
if (w > 500) {
w = 500;
h = -h;
rescale = " (rescaled 500x...)";
}
if (h > 300) {
h = 300;
w = -w;
rescale = " (rescaled ...x300)";
}
if (h < 0 && w < 0) {
w = 500;
h = 300;
rescale = " (rescaled 500x300)";
}
bimage = bimage.getScaledInstance(w, h, Image.SCALE_DEFAULT);
iconLabel.setIcon(new ImageIcon(bimage));
cause = new JLabel("Cannot find " + img.getName() + rescale);
dialog.add(iconLabel, BorderLayout.PAGE_END);
}
} else {
cause = new JLabel("Sikuli cannot find text:" + img.getName());
}
}
if (isCapture) {
cause = new JLabel("Request to capture: " + img.getName());
}
dialog.add(cause, BorderLayout.PAGE_START);
return dialog;
} | #vulnerable code
<PatternString> Component createTargetComponent(org.sikuli.script.Image img) {
JLabel cause = null;
JPanel dialog = new JPanel();
dialog.setLayout(new BorderLayout());
if (img.isValid()) {
if (!img.isText()) {
String rescale = "";
Image bimage = img.get();
JLabel iconLabel = new JLabel();
int w = bimage.getWidth(this);
int h = bimage.getHeight(this);
if (w > 500) {
w = 500;
h = -h;
rescale = " (rescaled 500x...)";
}
if (h > 300) {
h = 300;
w = -w;
rescale = " (rescaled ...x300)";
}
if (h < 0 && w < 0) {
w = 500;
h = 300;
rescale = " (rescaled 500x300)";
}
bimage = bimage.getScaledInstance(w, h, Image.SCALE_DEFAULT);
iconLabel.setIcon(new ImageIcon(bimage));
cause = new JLabel("Cannot find " + img.getName() + rescale);
dialog.add(iconLabel, BorderLayout.PAGE_END);
} else {
cause = new JLabel("Sikuli cannot find text:" + img.getName());
}
}
if (isCapture) {
cause = new JLabel("Request to capture: " + img.getName());
}
dialog.add(cause, BorderLayout.PAGE_START);
return dialog;
}
#location 10
#vulnerability type NULL_DEREFERENCE | 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
void findTarget(final String patFilename, final Location initOffset) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Region screenUnion = Region.create(0, 0, 1, 1);
Finder f = new Finder(_simg, screenUnion);
try {
f.find(patFilename);
if (f.hasNext()) {
//TODO rewrite completely for ScreenUnion
Screen s = (Screen) screenUnion.getScreen();
s.setAsScreenUnion();
_match = f.next();
s.setAsScreen();
if (initOffset != null) {
setTarget(initOffset.x, initOffset.y);
} else {
setTarget(0, 0);
}
}
_img = ImageIO.read(new File(patFilename));
} catch (IOException e) {
Debug.error(me + "Can't load " + patFilename);
}
synchronized (PatternPaneTargetOffset.this) {
_finding = false;
}
repaint();
}
});
thread.start();
} | #vulnerable code
void paintLoading(Graphics2D g2d) {
int w = getWidth(), h = getHeight();
g2d.setColor(new Color(0, 0, 0, 200));
g2d.fillRect(0, 0, w, h);
BufferedImage spinner = _loading.getFrame();
g2d.drawImage(spinner, null, w / 2 - spinner.getWidth() / 2, h / 2 - spinner.getHeight() / 2);
repaint();
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Deprecated
public static boolean addHotkey(String key, int modifiers, HotkeyListener listener) {
return Key.addHotkey(key, modifiers, listener);
} | #vulnerable code
@Deprecated
public static boolean addHotkey(String key, int modifiers, HotkeyListener listener) {
return HotkeyManager.getInstance().addHotkey(key, modifiers, listener);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static synchronized RunTime get(Type typ, String[] clArgs) {
if (runTime == null) {
runTime = new RunTime();
if (null != clArgs) {
int debugLevel = checkArgs(clArgs, typ);
if (Type.IDE.equals(typ)) {
if(debugLevel == -1) {
Debug.on(3);
Debug.log(3, "RunTime: option -d detected --- log goes to SikulixLog.txt");
Debug.setLogFile("");
Settings.LogTime = true;
System.setProperty("sikuli.console", "false");
} else if (debugLevel == 999) {
runTime.runningScripts = true;
}
}
}
if (Type.API.equals(typ)) {
Debug.init();
}
//<editor-fold defaultstate="collapsed" desc="versions">
String vJava = System.getProperty("java.runtime.version");
String vVM = System.getProperty("java.vm.version");
String vClass = System.getProperty("java.class.version");
String vSysArch = System.getProperty("sikuli.arch");
if (null != vSysArch) {
vSysArch = System.getProperty("os.arch");
}
if (vSysArch != null && vSysArch.contains("32")) {
runTime.javaArch = 32;
}
try {
runTime.javaVersion = Integer.parseInt(vJava.substring(2, 3));
runTime.javaShow = String.format("java %d-%d version %s vm %s class %s arch %s",
runTime.javaVersion, runTime.javaArch, vJava, vVM, vClass, vSysArch);
} catch (Exception ex) {
runTime.log(-1, "Java version not detected (using 7): %s", vJava);
runTime.javaVersion = 7;
runTime.javaShow = String.format("java ?7?-%d version %s vm %s class %s arch %s",
runTime.javaArch, vJava, vVM, vClass, vSysArch);
runTime.logp(runTime.javaShow);
runTime.dumpSysProps();
}
if (Debug.getDebugLevel() > runTime.minLvl) {
runTime.dumpSysProps();
}
runTime.osVersion = runTime.osVersionSysProp;
String os = runTime.osNameSysProp.toLowerCase();
if (os.startsWith("windows")) {
runTime.runningOn = theSystem.WIN;
runTime.sysName = "windows";
runTime.osName = "Windows";
runTime.runningWindows = true;
} else if (os.startsWith("mac")) {
runTime.runningOn = theSystem.MAC;
runTime.sysName = "mac";
runTime.osName = "Mac OSX";
runTime.runningMac = true;
} else if (os.startsWith("linux")) {
runTime.runningOn = theSystem.LUX;
runTime.sysName = "linux";
runTime.osName = "Linux";
runTime.runningLinux = true;
} else {
runTime.terminate(-1, "running on not supported System: %s (%s)", os, runTime.osVersion);
}
//</editor-fold>
debugLevelSaved = Debug.getDebugLevel();
debugLogfileSaved = Debug.logfile;
String aFolder = System.getProperty("user.home");
if (aFolder == null || aFolder.isEmpty() || !(runTime.fUserDir = new File(aFolder)).exists()) {
runTime.terminate(-1, "JavaSystemProperty::user.home not valid");
}
aFolder = System.getProperty("user.dir");
if (aFolder == null || aFolder.isEmpty() || !(runTime.fWorkDir = new File(aFolder)).exists()) {
runTime.terminate(-1, "JavaSystemProperty::user.dir not valid");
}
File fDebug = new File(runTime.fUserDir, "SikulixDebug.txt");
if (fDebug.exists()) {
if (Debug.getDebugLevel() == 0) {
Debug.setDebugLevel(3);
}
Debug.setLogFile(fDebug.getAbsolutePath());
if (Type.IDE.equals(typ)) {
System.setProperty("sikuli.console", "false");
}
runTime.logp("auto-debugging with level %d into:\n%s", Debug.getDebugLevel(), fDebug);
}
runTime.fTestFolder = new File(runTime.fUserDir, "SikulixTest");
runTime.fTestFile = new File(runTime.fTestFolder, "SikulixTest.txt");
runTime.loadOptions(typ);
int dl = runTime.getOptionNumber("debug.level");
if (dl > 0 && Debug.getDebugLevel() < 2) {
Debug.setDebugLevel(dl);
}
if (Debug.getDebugLevel() > 1) {
runTime.dumpOptions();
}
if (Type.SETUP.equals(typ)) {
Debug.setDebugLevel(3);
}
Settings.init(); // force Settings initialization
runTime.initSikulixOptions();
runTime.init(typ);
if (Type.IDE.equals(typ)) {
runTime.initIDEbefore();
runTime.initAPI();
runTime.initIDEafter();
} else {
runTime.initAPI();
if (Type.SETUP.equals(typ)) {
runTime.initSetup();
}
}
}
if (testingWinApp && !runTime.runningWindows) {
runTime.terminate(1, "***** for testing winapp: not running on Windows");
}
return runTime;
} | #vulnerable code
public static synchronized RunTime get(Type typ, String[] clArgs) {
if (runTime == null) {
runTime = new RunTime();
if (null != clArgs) {
int debugLevel = checkArgs(clArgs, typ);
if (Type.IDE.equals(typ)) {
if(debugLevel == -1) {
Debug.on(3);
Debug.log(3, "RunTime: option -d detected --- log goes to SikulixLog.txt");
Debug.setLogFile("");
Settings.LogTime = true;
System.setProperty("sikuli.console", "false");
} else if (debugLevel == 999) {
runTime.runningScripts = true;
}
}
}
if (Type.API.equals(typ)) {
Debug.init();
}
//<editor-fold defaultstate="collapsed" desc="versions">
String vJava = System.getProperty("java.runtime.version");
String vVM = System.getProperty("java.vm.version");
String vClass = System.getProperty("java.class.version");
String vSysArch = System.getProperty("os.arch");
if (vSysArch.contains("64")) {
runTime.javaArch = 64;
}
try {
runTime.javaVersion = Integer.parseInt(vJava.substring(2, 3));
runTime.javaShow = String.format("java %d-%d version %s vm %s class %s arch %s",
runTime.javaVersion, runTime.javaArch, vJava, vVM, vClass, vSysArch);
} catch (Exception ex) {
runTime.log(-1, "Java version not detected (using 7): %s", vJava);
runTime.javaVersion = 7;
runTime.javaShow = String.format("java ?7?-%d version %s vm %s class %s arch %s",
runTime.javaArch, vJava, vVM, vClass, vSysArch);
}
if (Debug.getDebugLevel() > runTime.minLvl) {
runTime.dumpSysProps();
}
runTime.osVersion = runTime.osVersionSysProp;
String os = runTime.osNameSysProp.toLowerCase();
if (os.startsWith("windows")) {
runTime.runningOn = theSystem.WIN;
runTime.sysName = "windows";
runTime.osName = "Windows";
runTime.runningWindows = true;
} else if (os.startsWith("mac")) {
runTime.runningOn = theSystem.MAC;
runTime.sysName = "mac";
runTime.osName = "Mac OSX";
runTime.runningMac = true;
} else if (os.startsWith("linux")) {
runTime.runningOn = theSystem.LUX;
runTime.sysName = "linux";
runTime.osName = "Linux";
runTime.runningLinux = true;
} else {
runTime.terminate(-1, "running on not supported System: %s (%s)", os, runTime.osVersion);
}
//</editor-fold>
debugLevelSaved = Debug.getDebugLevel();
debugLogfileSaved = Debug.logfile;
String aFolder = System.getProperty("user.home");
if (aFolder == null || aFolder.isEmpty() || !(runTime.fUserDir = new File(aFolder)).exists()) {
runTime.terminate(-1, "JavaSystemProperty::user.home not valid");
}
aFolder = System.getProperty("user.dir");
if (aFolder == null || aFolder.isEmpty() || !(runTime.fWorkDir = new File(aFolder)).exists()) {
runTime.terminate(-1, "JavaSystemProperty::user.dir not valid");
}
File fDebug = new File(runTime.fUserDir, "SikulixDebug.txt");
if (fDebug.exists()) {
if (Debug.getDebugLevel() == 0) {
Debug.setDebugLevel(3);
}
Debug.setLogFile(fDebug.getAbsolutePath());
if (Type.IDE.equals(typ)) {
System.setProperty("sikuli.console", "false");
}
runTime.logp("auto-debugging with level %d into:\n%s", Debug.getDebugLevel(), fDebug);
}
runTime.fTestFolder = new File(runTime.fUserDir, "SikulixTest");
runTime.fTestFile = new File(runTime.fTestFolder, "SikulixTest.txt");
runTime.loadOptions(typ);
int dl = runTime.getOptionNumber("debug.level");
if (dl > 0 && Debug.getDebugLevel() < 2) {
Debug.setDebugLevel(dl);
}
if (Debug.getDebugLevel() > 1) {
runTime.dumpOptions();
}
if (Type.SETUP.equals(typ)) {
Debug.setDebugLevel(3);
}
Settings.init(); // force Settings initialization
runTime.initSikulixOptions();
runTime.init(typ);
if (Type.IDE.equals(typ)) {
runTime.initIDEbefore();
runTime.initAPI();
runTime.initIDEafter();
} else {
runTime.initAPI();
if (Type.SETUP.equals(typ)) {
runTime.initSetup();
}
}
}
if (testingWinApp && !runTime.runningWindows) {
runTime.terminate(1, "***** for testing winapp: not running on Windows");
}
return runTime;
}
#location 28
#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 static int isUrlUseabel(URL aURL) {
HttpURLConnection conn = null;
try {
// HttpURLConnection.setFollowRedirects(false);
if (getProxy() != null) {
conn = (HttpURLConnection) aURL.openConnection(getProxy());
} else {
conn = (HttpURLConnection) aURL.openConnection();
}
// con.setInstanceFollowRedirects(false);
conn.setRequestMethod("HEAD");
int retval = conn.getResponseCode();
// HttpURLConnection.HTTP_BAD_METHOD 405
// HttpURLConnection.HTTP_NOT_FOUND 404
if (retval == HttpURLConnection.HTTP_OK) {
return 1;
} else if (retval == HttpURLConnection.HTTP_NOT_FOUND) {
return 0;
} else if (retval == HttpURLConnection.HTTP_FORBIDDEN) {
return 0;
} else {
return -1;
}
} catch (Exception ex) {
return -1;
} finally {
if (conn != null) {
conn.disconnect();
}
}
} | #vulnerable code
public static int isUrlUseabel(URL aURL) {
try {
// HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) aURL.openConnection();
// con.setInstanceFollowRedirects(false);
con.setRequestMethod("HEAD");
int retval = con.getResponseCode();
// HttpURLConnection.HTTP_BAD_METHOD 405
// HttpURLConnection.HTTP_NOT_FOUND 404
if (retval == HttpURLConnection.HTTP_OK) {
return 1;
} else if (retval == HttpURLConnection.HTTP_NOT_FOUND) {
return 0;
} else if (retval == HttpURLConnection.HTTP_FORBIDDEN) {
return 0;
} else {
return -1;
}
} catch (Exception ex) {
return -1;
}
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static int checkArgs(String[] args, Type typ) {
int debugLevel = -99;
boolean runningScriptsWithIDE = false;
List<String> options = new ArrayList<String>();
options.addAll(Arrays.asList(args));
for (int n = 0; n < options.size(); n++) {
String opt = options.get(n);
if (!opt.startsWith("-")) {
continue;
}
if (opt.startsWith("-d")) {
debugLevel = -1;
try {
debugLevel = n + 1 == options.size() ? -1 : Integer.decode(options.get(n + 1));
} catch (Exception ex) {
debugLevel = -1;
}
if (debugLevel > -1) {
Debug.on(debugLevel);
}
} else if (opt.startsWith("-r") || opt.startsWith("-t")) {
runningScriptsWithIDE = true;
}
}
if (Type.IDE.equals(typ) && runningScriptsWithIDE) {
return 999;
}
return debugLevel;
} | #vulnerable code
public static int checkArgs(String[] args, Type typ) {
int debugLevel = -99;
List<String> options = new ArrayList<String>();
options.addAll(Arrays.asList(args));
for (int n = 0; n < options.size(); n++) {
String opt = options.get(n);
if (!opt.startsWith("-")) {
continue;
}
if (opt.startsWith("-d")) {
debugLevel = -1;
try {
debugLevel = n + 1 == options.size() ? -1 : Integer.decode(options.get(n + 1));
} catch (Exception ex) {
debugLevel = -1;
}
if (debugLevel > -1) {
Debug.on(debugLevel);
}
}
if (Type.IDE.equals(typ) && debugLevel == -1) {
Debug.on(3);
Debug.log(3, "RunTime: option -d detected --- log goes to SikulixLog.txt");
Debug.setLogFile("");
Settings.LogTime = true;
System.setProperty("sikuli.console", "false");
}
}
return debugLevel;
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void initSikulixOptions() {
SikuliRepo = null;
Properties prop = new Properties();
String svf = "sikulixversion.txt";
try {
InputStream is;
is = clsRef.getClassLoader().getResourceAsStream("Settings/" + svf);
if (is == null) {
terminate(1, "initSikulixOptions: not found on classpath: %s", "Settings/" + svf);
}
prop.load(is);
is.close();
String svt = prop.getProperty("sikulixdev");
SikuliVersionMajor = Integer.decode(prop.getProperty("sikulixvmaj"));
SikuliVersionMinor = Integer.decode(prop.getProperty("sikulixvmin"));
SikuliVersionSub = Integer.decode(prop.getProperty("sikulixvsub"));
SikuliVersionBetaN = Integer.decode(prop.getProperty("sikulixbeta"));
String ssxbeta = "";
if (SikuliVersionBetaN > 0) {
ssxbeta = String.format("-Beta%d", SikuliVersionBetaN);
}
SikuliVersionBuild = prop.getProperty("sikulixbuild");
log(lvl + 1, "%s version from %s: %d.%d.%d%s build: %s", svf,
SikuliVersionMajor, SikuliVersionMinor, SikuliVersionSub, ssxbeta,
SikuliVersionBuild, svt);
sversion = String.format("%d.%d.%d",
SikuliVersionMajor, SikuliVersionMinor, SikuliVersionSub);
bversion = String.format("%d.%d.%d-Beta%d",
SikuliVersionMajor, SikuliVersionMinor, SikuliVersionSub, SikuliVersionBetaN);
SikuliVersionDefault = "SikuliX " + sversion;
SikuliVersionBeta = "Sikuli " + bversion;
SikuliVersionDefaultIDE = "SikulixIDE " + sversion;
SikuliVersionBetaIDE = "SikulixIDE " + bversion;
SikuliVersionDefaultScript = "SikulixScript " + sversion;
SikuliVersionBetaScript = "SikulixScript " + bversion;
if ("release".equals(svt)) {
downloadBaseDirBase = dlProdLink;
downloadBaseDirWeb = downloadBaseDirBase + getVersionShortBasic() + dlProdLink1;
downloadBaseDir = downloadBaseDirWeb + dlProdLink2;
SikuliVersionType = "";
SikuliVersionTypeText = "";
} else {
downloadBaseDirBase = dlDevLink;
downloadBaseDirWeb = dlDevLink;
downloadBaseDir = dlDevLink;
SikuliVersionTypeText = "nightly";
SikuliVersionBuild += SikuliVersionTypeText;
SikuliVersionType = svt;
}
if (SikuliVersionBetaN > 0) {
SikuliVersion = SikuliVersionBeta;
SikuliVersionIDE = SikuliVersionBetaIDE;
SikuliVersionScript = SikuliVersionBetaScript;
SikuliVersionLong = bversion + "(" + SikuliVersionBuild + ")";
} else {
SikuliVersion = SikuliVersionDefault;
SikuliVersionIDE = SikuliVersionDefaultIDE;
SikuliVersionScript = SikuliVersionDefaultScript;
SikuliVersionLong = sversion + "(" + SikuliVersionBuild + ")";
}
SikuliProjectVersionUsed = prop.getProperty("sikulixvused");
SikuliProjectVersion = prop.getProperty("sikulixvproject");
String osn = "UnKnown";
String os = System.getProperty("os.name").toLowerCase();
if (os.startsWith("mac")) {
osn = "Mac";
} else if (os.startsWith("windows")) {
osn = "Windows";
} else if (os.startsWith("linux")) {
osn = "Linux";
}
SikuliLocalRepo = FileManager.slashify(prop.getProperty("sikulixlocalrepo"), true);
SikuliJythonVersion = prop.getProperty("sikulixvjython");
SikuliJythonMaven = "org/python/jython-standalone/"
+ SikuliJythonVersion + "/jython-standalone-" + SikuliJythonVersion + ".jar";
SikuliJythonMaven25 = "org/python/jython-standalone/"
+ SikuliJythonVersion25 + "/jython-standalone-" + SikuliJythonVersion25 + ".jar";
SikuliJython = SikuliLocalRepo + SikuliJythonMaven;
SikuliJRubyVersion = prop.getProperty("sikulixvjruby");
SikuliJRubyMaven = "org/jruby/jruby-complete/"
+ SikuliJRubyVersion + "/jruby-complete-" + SikuliJRubyVersion + ".jar";
SikuliJRuby = SikuliLocalRepo + SikuliJRubyMaven;
SikuliSystemVersion = osn + System.getProperty("os.version");
SikuliJavaVersion = "Java" + javaVersion + "(" + javaArch + ")" + jreVersion;
//TODO this should be in RunSetup only
//TODO debug version: where to do in sikulixapi.jar
//TODO need a function: reveal all environment and system information
// log(lvl, "%s version: downloading from %s", svt, downloadBaseDir);
} catch (Exception e) {
Debug.error("Settings: load version file %s did not work", svf);
Sikulix.terminate(999);
}
tessData.put("eng", "http://tesseract-ocr.googlecode.com/files/tesseract-ocr-3.02.eng.tar.gz");
Env.setSikuliVersion(SikuliVersion);
} | #vulnerable code
private void initSikulixOptions() {
SikuliRepo = null;
Properties prop = new Properties();
String svf = "sikulixversion.txt";
try {
InputStream is;
is = clsRef.getClassLoader().getResourceAsStream("Settings/" + svf);
if (is == null) {
terminate(1, "initSikulixOptions: not found on classpath: %s", "Settings/" + svf);
}
prop.load(is);
is.close();
String svt = prop.getProperty("sikulixdev");
SikuliVersionMajor = Integer.decode(prop.getProperty("sikulixvmaj"));
SikuliVersionMinor = Integer.decode(prop.getProperty("sikulixvmin"));
SikuliVersionSub = Integer.decode(prop.getProperty("sikulixvsub"));
SikuliVersionBetaN = Integer.decode(prop.getProperty("sikulixbeta"));
String ssxbeta = "";
if (SikuliVersionBetaN > 0) {
ssxbeta = String.format("-Beta%d", SikuliVersionBetaN);
}
SikuliVersionBuild = prop.getProperty("sikulixbuild");
log(lvl + 1, "%s version from %s: %d.%d.%d%s build: %s", svf,
SikuliVersionMajor, SikuliVersionMinor, SikuliVersionSub, ssxbeta,
SikuliVersionBuild, svt);
sversion = String.format("%d.%d.%d",
SikuliVersionMajor, SikuliVersionMinor, SikuliVersionSub);
bversion = String.format("%d.%d.%d-Beta%d",
SikuliVersionMajor, SikuliVersionMinor, SikuliVersionSub, SikuliVersionBetaN);
SikuliVersionDefault = "SikuliX " + sversion;
SikuliVersionBeta = "Sikuli " + bversion;
SikuliVersionDefaultIDE = "SikulixIDE " + sversion;
SikuliVersionBetaIDE = "SikulixIDE " + bversion;
SikuliVersionDefaultScript = "SikulixScript " + sversion;
SikuliVersionBetaScript = "SikulixScript " + bversion;
if ("release".equals(svt)) {
downloadBaseDirBase = dlProdLink;
downloadBaseDirWeb = downloadBaseDirBase + getVersionShortBasic() + dlProdLink1;
downloadBaseDir = downloadBaseDirWeb + dlProdLink2;
SikuliVersionType = "";
SikuliVersionTypeText = "";
} else {
downloadBaseDirBase = dlDevLink;
downloadBaseDirWeb = dlDevLink;
downloadBaseDir = dlDevLink;
SikuliVersionTypeText = "nightly";
SikuliVersionBuild += SikuliVersionTypeText;
SikuliVersionType = svt;
}
if (SikuliVersionBetaN > 0) {
SikuliVersion = SikuliVersionBeta;
SikuliVersionIDE = SikuliVersionBetaIDE;
SikuliVersionScript = SikuliVersionBetaScript;
SikuliVersionLong = bversion + "(" + SikuliVersionBuild + ")";
} else {
SikuliVersion = SikuliVersionDefault;
SikuliVersionIDE = SikuliVersionDefaultIDE;
SikuliVersionScript = SikuliVersionDefaultScript;
SikuliVersionLong = sversion + "(" + SikuliVersionBuild + ")";
}
SikuliProjectVersionUsed = prop.getProperty("sikulixvused");
SikuliProjectVersion = prop.getProperty("sikulixvproject");
String osn = "UnKnown";
String os = System.getProperty("os.name").toLowerCase();
if (os.startsWith("mac")) {
osn = "Mac";
} else if (os.startsWith("windows")) {
osn = "Windows";
} else if (os.startsWith("linux")) {
osn = "Linux";
}
SikuliLocalRepo = FileManager.slashify(prop.getProperty("sikulixlocalrepo"), true);
SikuliJythonVersion = prop.getProperty("sikulixvjython");
SikuliJythonMaven = "org/python/jython-standalone/" +
SikuliJythonVersion + "/jython-standalone-" + SikuliJythonVersion + ".jar";
SikuliJythonMaven25 = "org/python/jython-standalone/" +
SikuliJythonVersion25 + "/jython-standalone-" + SikuliJythonVersion25 + ".jar";
SikuliJython = SikuliLocalRepo + SikuliJythonMaven;
SikuliJRubyVersion = prop.getProperty("sikulixvjruby");
SikuliJRubyMaven = "org/jruby/jruby-complete/" +
SikuliJRubyVersion + "/jruby-complete-" + SikuliJRubyVersion + ".jar";
SikuliJRuby = SikuliLocalRepo + SikuliJRubyMaven;
SikuliSystemVersion = osn + System.getProperty("os.version");
SikuliJavaVersion = "Java" + javaVersion + "(" + javaArch + ")" + jreVersion;
//TODO this should be in RunSetup only
//TODO debug version: where to do in sikulixapi.jar
//TODO need a function: reveal all environment and system information
// log(lvl, "%s version: downloading from %s", svt, downloadBaseDir);
} catch (Exception e) {
Debug.error("Settings: load version file %s did not work", svf);
Sikulix.terminate(999);
}
tessData.put("eng", "http://tesseract-ocr.googlecode.com/files/tesseract-ocr-3.02.eng.tar.gz");
Env.setSikuliVersion(SikuliVersion);
}
#location 65
#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
private void drawScreenFrame(Graphics2D g2d, int scrId) {
g2d.setColor(screenFrameColor);
g2d.setStroke(strokeScreenFrame);
if (screenFrame == null) {
screenFrame = Screen.getBounds(scrId);
Rectangle ubound = scrOCP.getBounds();
screenFrame.x -= ubound.x;
screenFrame.y -= ubound.y;
int sw = (int) (strokeScreenFrame.getLineWidth() / 2);
screenFrame.x += sw;
screenFrame.y += sw;
screenFrame.width -= sw * 2;
screenFrame.height -= sw * 2;
}
g2d.draw(screenFrame);
} | #vulnerable code
private void drawScreenFrame(Graphics2D g2d, int scrId) {
Rectangle rect = Screen.getBounds(scrId);
Rectangle ubound = (new ScreenUnion()).getBounds();
g2d.setColor(screenFrameColor);
g2d.setStroke(strokeScreenFrame);
rect.x -= ubound.x;
rect.y -= ubound.y;
int sw = (int) (strokeScreenFrame.getLineWidth() / 2);
rect.x += sw;
rect.y += sw;
rect.width -= sw * 2;
rect.height -= sw * 2;
g2d.draw(rect);
}
#location 6
#vulnerability type NULL_DEREFERENCE | 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
@Deprecated
public static boolean removeHotkey(char key, int modifiers) {
return Key.removeHotkey(key, modifiers);
} | #vulnerable code
@Deprecated
public static boolean removeHotkey(char 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 <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) 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 {
uTest = new URL(imgLink);
URL uImage = FileManager.makeURL(uTest, imgHttp);
log(0, "URL: %s", uTest);
// BufferedImage bImg = ImageIO.read(uTest);
// log(0, "Image: %s", bImg);
// Image img = new Image(bImg);
// Screen scr = new Screen();
// scr.find(img).highlight(2);
// scr.find(img).highlight(2);
} 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;
Settings.OcrTextSearch = true;
Region eWin = App.start(App.Type.EDITOR);
eWin.write("\n Jump\n\n Jump and Run\n\nRun and Jump\n");
Region reg = eWin;
while (true) {
Match ms = reg.exists("Jump", 0);
if (ms == null) {
break;
}
ms.highlight(2);
ms.x = eWin.x;
ms.w = eWin.w;
reg = eWin.intersection(ms.below());
}
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 32
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if (getWidth() > 0 && getHeight() > 0) {
if (_match != null) {
zoomToMatch();
paintSubScreen(g2d);
paintMatch(g2d);
} else {
paintPatternOnly(g2d);
}
// paintRulers(g2d);
paintTarget(g2d);
synchronized (this) {
if (_finding) {
paintLoading(g2d);
}
}
}
} | #vulnerable code
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if (getWidth() > 0 && getHeight() > 0) {
if (_match != null) {
zoomToMatch();
paintSubScreen(g2d);
paintMatch(g2d);
} else {
paintPatternOnly(g2d);
}
paintRulers(g2d);
paintTarget(g2d);
synchronized (this) {
if (_finding) {
paintLoading(g2d);
}
}
}
}
#location 12
#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;
RepeatableFindAll rf = new RepeatableFindAll(target, null);
Image img = rf._image;
String targetStr = img.getName();
Boolean response = true;
if (!img.isValid() && img.hasIOException()) {
response = handleImageMissing(img, false);
}
if (null != response && response) {
log(lvl, "findAll: waiting %.1f secs for (multiple) %s to appear in %s",
autoWaitTimeout, targetStr, this.toStringShort());
if (autoWaitTimeout > 0) {
rf.repeat(autoWaitTimeout);
lastMatches = rf.getMatches();
} else {
lastMatches = doFindAll(target, null);
}
if (lastMatches != null) {
log(lvl, "findAll: %s has appeared", targetStr);
} else {
log(lvl, "findAll: %s did not appear", targetStr);
}
}
return lastMatches;
} | #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(target, img, false)) {
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 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 void initBeforeLoad(String scriptType, boolean reInit) {
String scrType = null;
boolean paneIsEmpty = false;
log(lvl, "initBeforeLoad: %s", scriptType);
if (scriptType == null) {
scriptType = Settings.EDEFAULT;
paneIsEmpty = true;
}
if (Settings.EPYTHON.equals(scriptType)) {
scrType = Settings.CPYTHON;
_indentationLogic = SikuliIDE.getIDESupport(scriptType).getIndentationLogic();
_indentationLogic.setTabWidth(pref.getTabWidth());
} else if (Settings.ERUBY.equals(scriptType)) {
scrType = Settings.CRUBY;
_indentationLogic = null;
}
//TODO should know, that scripttype not changed here to avoid unnecessary new setups
if (scrType != null) {
sikuliContentType = scrType;
editorKit = new SikuliEditorKit();
editorViewFactory = (EditorViewFactory) editorKit.getViewFactory();
setEditorKit(editorKit);
setContentType(scrType);
if (_indentationLogic != null) {
pref.addPreferenceChangeListener(new PreferenceChangeListener() {
@Override
public void preferenceChange(PreferenceChangeEvent event) {
if (event.getKey().equals("TAB_WIDTH")) {
_indentationLogic.setTabWidth(Integer.parseInt(event.getNewValue()));
}
}
});
}
}
if (transferHandler == null) {
transferHandler = new MyTransferHandler();
}
setTransferHandler(transferHandler);
if (_highlighter == null) {
_highlighter = new EditorCurrentLineHighlighter(this);
addCaretListener(_highlighter);
initKeyMap();
addKeyListener(this);
addCaretListener(this);
}
setFont(new Font(pref.getFontName(), Font.PLAIN, pref.getFontSize()));
setMargin(new Insets(3, 3, 3, 3));
setBackground(Color.WHITE);
if (!Settings.isMac()) {
setSelectionColor(new Color(170, 200, 255));
}
updateDocumentListeners("initBeforeLoad");
popMenuImage = new SikuliIDEPopUpMenu("POP_IMAGE", this);
if (!popMenuImage.isValidMenu()) {
popMenuImage = null;
}
if (paneIsEmpty || reInit) {
// this.setText(String.format(Settings.TypeCommentDefault, getSikuliContentType()));
this.setText("");
}
SikuliIDE.getStatusbar().setCurrentContentType(getSikuliContentType());
log(lvl, "InitTab: (%s)", getSikuliContentType());
if (!Settings.hasTypeRunner(getSikuliContentType())) {
SikuliX.popup("No installed runner supports (" + getSikuliContentType() + ")\n"
+ "Trying to run the script will crash IDE!", "... serious problem detected!");
}
} | #vulnerable code
public void initBeforeLoad(String scriptType, boolean reInit) {
String scrType = null;
boolean paneIsEmpty = false;
if (scriptType == null) {
scriptType = Settings.EDEFAULT;
paneIsEmpty = true;
}
if (Settings.EPYTHON.equals(scriptType)) {
scrType = Settings.CPYTHON;
_indentationLogic = SikuliIDE.getIDESupport(scriptType).getIndentationLogic();
_indentationLogic.setTabWidth(pref.getTabWidth());
} else if (Settings.ERUBY.equals(scriptType)) {
scrType = Settings.CRUBY;
_indentationLogic = null;
}
if (scrType != null) {
sikuliContentType = scrType;
editorKit = new SikuliEditorKit();
editorViewFactory = (EditorViewFactory) editorKit.getViewFactory();
setEditorKit(editorKit);
setContentType(scrType);
if (_indentationLogic != null) {
pref.addPreferenceChangeListener(new PreferenceChangeListener() {
@Override
public void preferenceChange(PreferenceChangeEvent event) {
if (event.getKey().equals("TAB_WIDTH")) {
_indentationLogic.setTabWidth(Integer.parseInt(event.getNewValue()));
}
}
});
}
}
initKeyMap();
if (transferHandler == null) {
transferHandler = new MyTransferHandler();
}
setTransferHandler(transferHandler);
_highlighter = new EditorCurrentLineHighlighter(this);
addCaretListener(_highlighter);
setFont(new Font(pref.getFontName(), Font.PLAIN, pref.getFontSize()));
setMargin(new Insets(3, 3, 3, 3));
setBackground(Color.WHITE);
if (!Settings.isMac()) {
setSelectionColor(new Color(170, 200, 255));
}
updateDocumentListeners();
addKeyListener(this);
addCaretListener(this);
popMenuImage = new SikuliIDEPopUpMenu("POP_IMAGE", this);
if (!popMenuImage.isValidMenu()) {
popMenuImage = null;
}
if (paneIsEmpty || reInit) {
// this.setText(String.format(Settings.TypeCommentDefault, getSikuliContentType()));
this.setText("");
}
SikuliIDE.getStatusbar().setCurrentContentType(getSikuliContentType());
Debug.log(3, "InitTab: (%s)", getSikuliContentType());
if (!Settings.hasTypeRunner(getSikuliContentType())) {
SikuliX.popup("No installed runner supports (" + getSikuliContentType() + ")\n"
+ "Trying to run the script will crash IDE!", "... serious problem detected!");
}
}
#location 68
#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 40
#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, false)) {
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(target, 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 int checkArgs(String[] args, Type typ) {
int debugLevel = -99;
boolean runningScriptsWithIDE = false;
List<String> options = new ArrayList<String>();
options.addAll(Arrays.asList(args));
for (int n = 0; n < options.size(); n++) {
String opt = options.get(n);
if (!opt.startsWith("-")) {
continue;
}
if (opt.startsWith("-d")) {
debugLevel = -1;
try {
debugLevel = n + 1 == options.size() ? -1 : Integer.decode(options.get(n + 1));
} catch (Exception ex) {
debugLevel = -1;
}
if (debugLevel > -1) {
Debug.on(debugLevel);
}
} else if (opt.startsWith("-r") || opt.startsWith("-t")) {
runningScriptsWithIDE = true;
}
}
if (Type.IDE.equals(typ) && runningScriptsWithIDE) {
return 999;
}
return debugLevel;
} | #vulnerable code
public static int checkArgs(String[] args, Type typ) {
int debugLevel = -99;
List<String> options = new ArrayList<String>();
options.addAll(Arrays.asList(args));
for (int n = 0; n < options.size(); n++) {
String opt = options.get(n);
if (!opt.startsWith("-")) {
continue;
}
if (opt.startsWith("-d")) {
debugLevel = -1;
try {
debugLevel = n + 1 == options.size() ? -1 : Integer.decode(options.get(n + 1));
} catch (Exception ex) {
debugLevel = -1;
}
if (debugLevel > -1) {
Debug.on(debugLevel);
}
}
if (Type.IDE.equals(typ) && debugLevel == -1) {
Debug.on(3);
Debug.log(3, "RunTime: option -d detected --- log goes to SikulixLog.txt");
Debug.setLogFile("");
Settings.LogTime = true;
System.setProperty("sikuli.console", "false");
}
}
return debugLevel;
}
#location 24
#vulnerability type THREAD_SAFETY_VIOLATION | 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
public static String getFilenameFromImage(BufferedImage img){
TextRecognizer tr = TextRecognizer.getInstance();
if (! PreferencesUser.getInstance().getPrefMoreTextOCR() || tr == null) {
return "";
}
String text = tr.recognize(img);
text = text.replaceAll("\\W","");
if( text.length() > MAX_OCR_TEXT_LENGTH ) {
return text.substring(0, MAX_OCR_TEXT_LENGTH);
}
return text;
} | #vulnerable code
public static String getFilenameFromImage(BufferedImage img){
if (! PreferencesUser.getInstance().getPrefMoreTextOCR()) {
return "";
}
TextRecognizer tr = TextRecognizer.getInstance();
String text = tr.recognize(img);
text = text.replaceAll("\\W","");
if( text.length() > MAX_OCR_TEXT_LENGTH ) {
return text.substring(0, MAX_OCR_TEXT_LENGTH);
}
return text;
}
#location 6
#vulnerability type NULL_DEREFERENCE | 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
protected static int move(Location loc, Region region) {
if (get().device.isSuspended()) {
return 0;
}
if (loc != null) {
IRobot r = null;
r = loc.getScreen().getRobot();
if (r == null) {
return 0;
}
if (!r.isRemote()) {
get().device.use(region);
}
r.smoothMove(loc);
r.waitForIdle();
if (!r.isRemote()) {
get().device.let(region);
}
return 1;
}
return 0;
} | #vulnerable code
protected static int move(Location loc, Region region) {
if (get().device.isSuspended()) {
return 0;
}
if (loc != null) {
IRobot r = null;
r = Screen.getMouseRobot();
if (r == null) {
return 0;
}
if (!r.isRemote()) {
get().device.use(region);
}
r.smoothMove(loc);
r.waitForIdle();
if (!r.isRemote()) {
get().device.let(region);
}
return 1;
}
return 0;
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void update(EventSubject es) {
OverlayCapturePrompt ocp = (OverlayCapturePrompt) es;
ScreenImage simg = ocp.getSelection();
Screen.closePrompt();
if (simg != null) {
try {
Thread.sleep(300);
} catch (InterruptedException ie) {
}
Rectangle roi = simg.getROI();
_x = (int) roi.getX();
_y = (int) roi.getY();
_w = (int) roi.getWidth();
_h = (int) roi.getHeight();
BufferedImage img = getRegionImage(_x, _y, _w, _h);
setIcon(new ImageIcon(img));
setToolTipText(this.toString());
}
Screen.resetPrompt(ocp);
SikuliIDE.showAgain();
} | #vulnerable code
@Override
public void update(EventSubject es) {
OverlayCapturePrompt cp = null;
ScreenImage simg = cp.getSelection();
Screen.closePrompt();
if (simg != null) {
try {
Thread.sleep(300);
} catch (InterruptedException ie) {
}
Rectangle roi = simg.getROI();
_x = (int) roi.getX();
_y = (int) roi.getY();
_w = (int) roi.getWidth();
_h = (int) roi.getHeight();
BufferedImage img = getRegionImage(_x, _y, _w, _h);
setIcon(new ImageIcon(img));
setToolTipText(this.toString());
}
Screen.resetPrompt(cp);
SikuliIDE.getInstance().setVisible(true);
}
#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 update(EventSubject es) {
OverlayCapturePrompt ocp = (OverlayCapturePrompt) es;
ScreenImage simg = ocp.getSelection();
Screen.closePrompt();
if (simg != null) {
try {
Thread.sleep(300);
} catch (InterruptedException ie) {
}
Rectangle roi = simg.getROI();
pyText = String.format("%d,%d,%d,%d",
(int) roi.x, (int) roi.y, (int) roi.width, (int) roi.height);
setText(pyText);
pyText = "Region(" + pyText + ")";
}
Screen.resetPrompt(ocp);
SikuliIDE.showAgain();
} | #vulnerable code
@Override
public void update(EventSubject es) {
OverlayCapturePrompt cp = null;
ScreenImage simg = cp.getSelection();
Screen.closePrompt();
if (simg != null) {
try {
Thread.sleep(300);
} catch (InterruptedException ie) {
}
Rectangle roi = simg.getROI();
pyText = String.format("%d,%d,%d,%d",
(int) roi.x, (int) roi.y, (int) roi.width, (int) roi.height);
setText(pyText);
pyText = "Region(" + pyText + ")";
}
Screen.resetPrompt(cp);
SikuliIDE.getInstance().setVisible(true);
}
#location 4
#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;
}
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();
// File fJarLibsLux = new File(rt.fSikulixDownloadsBuild, "sikulixlibslux-1.1.0.jar");
// String fpJarLibsLux = fJarLibsLux.getAbsolutePath();
// boolean shouldBuild = LinuxSupport.processLibs(fpJarLibsLux);
// boolean buildOK = LinuxSupport.buildVision(fpJarLibsLux);
// RunnerClient runner = new RunnerClient("192.168.2.114", "50000");
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);
String runSomeJS = inputText("enter some JavaScript (know what you do - may silently die ;-)"
+ "\nexample: run(\"git*\") will run the JavaScript showcase from GitHub",
"API::JavaScriptRunner " + version, 10, 60);
if (runSomeJS.isEmpty()) {
popup("Nothing to do!", version);
} else {
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();
Debug.on(3);
Settings.InfoLogs = false;
Settings.ActionLogs = false;
String f = new File(rt.tessData.get("eng")).getName();
// Screen s = new Screen();
// File fJarLibsLux = new File(rt.fSikulixDownloadsBuild, "sikulixlibslux-1.1.0.jar");
// String fpJarLibsLux = fJarLibsLux.getAbsolutePath();
// boolean shouldBuild = LinuxSupport.processLibs(fpJarLibsLux);
// boolean buildOK = LinuxSupport.buildVision(fpJarLibsLux);
// RunnerClient runner = new RunnerClient("192.168.2.114", "50000");
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 runSomeJS = inputText("enter some JavaScript (know what you do - may silently die ;-)"
+ "\nexample: run(\"git*\") will run the JavaScript showcase from GitHub", "API:Runner", 10, 60);
if (runSomeJS.isEmpty()) {
popup("Nothing to do!", "API:Runner");
} else {
Runner.runjs(null, null, runSomeJS, null);
}
}
}
#location 47
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String saveCapture(String name, Region reg) {
ScreenImage img;
if (reg == null) {
img = userCapture("Capture for image " + name);
} else {
img = capture(reg);
}
if (img == null) {
return null;
} else {
return img.saveInBundle(name);
}
} | #vulnerable code
public String saveCapture(String name, Region reg) {
ScreenImage img;
if (reg == null) {
img = userCapture("Capture for image " + name);
} else {
img = capture(reg);
}
img.saveInBundle(name);
return name;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Deprecated
public static boolean addHotkey(char key, int modifiers, HotkeyListener listener) {
return Key.addHotkey(key, modifiers, listener);
} | #vulnerable code
@Deprecated
public static boolean addHotkey(char key, int modifiers, HotkeyListener listener) {
return HotkeyManager.getInstance().addHotkey(key, modifiers, listener);
}
#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) {
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
@Override
public Stream<IdObject<U, List<I>>> get() {
try (BufferedReader candidatesReader = new BufferedReader(new FileReader(candidatesPath))) {
return candidatesReader.lines().parallel().map(line -> {
CharSequence[] tokens = split(line, '\t', 3);
final U user = uParser.parse(tokens[0]);
final List<I> candidates = new ArrayList<>();
for (CharSequence candidate : split(tokens[1], ',')) {
candidates.add(iParser.parse(candidate));
}
testData.getUserPreferences(user).forEach(iv -> candidates.add(iv.id));
return new IdObject<>(user, candidates);
});
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
} | #vulnerable code
@Override
public Stream<IdObject<U, List<I>>> get() {
BufferedReader candidatesReader;
try {
candidatesReader = new BufferedReader(new FileReader(candidatesPath));
} catch (FileNotFoundException ex) {
throw new UncheckedIOException(ex);
}
return candidatesReader.lines().parallel().map(line -> {
CharSequence[] tokens = split(line, '\t', 3);
final U user = uParser.parse(tokens[0]);
final List<I> candidates = new ArrayList<>();
for (CharSequence candidate : split(tokens[1], ',')) {
candidates.add(iParser.parse(candidate));
}
testData.getUserPreferences(user).forEach(iv -> candidates.add(iv.id));
return new IdObject<>(user, candidates);
});
}
#location 10
#vulnerability type RESOURCE_LEAK | 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 List<Object[]> queryGenericObjectArrayListSQL(String poolName, String sql, Object[] params) {
List<Object[]> returnList = null;
try {
ArrayListHandler resultSetHandler = new ArrayListHandler();
// returnList = new QueryRunner().query(con, sql, resultSetHandler, params);
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 List<Object[]> queryGenericObjectArrayListSQL(String poolName, String sql, Object[] params) {
List<Object[]> returnList = null;
Connection con = null;
try {
con = DB_CONNECTION_MANAGER.getConnection(poolName);
if (con == null) {
throw new ConnectionException(poolName);
}
con.setAutoCommit(false);
ArrayListHandler resultSetHandler = new ArrayListHandler();
returnList = new QueryRunner().query(con, sql, resultSetHandler, params);
con.commit();
} catch (Exception e) {
logger.error(QUERY_EXCEPTION_MESSAGE, e);
try {
con.rollback();
} catch (SQLException e1) {
logger.error(ROLLBACK_EXCEPTION_MESSAGE, e1);
}
} finally {
DB_CONNECTION_MANAGER.freeConnection(con);
}
return returnList;
}
#location 23
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static int[] executeBatchSQL(String poolName, String sql, Object[][] params) {
int[] returnIntArray = null;
try {
returnIntArray = new QueryRunner(DB_CONNECTION_MANAGER.getDataSource(poolName)).batch(sql, params);
} catch (Exception e) {
logger.error(QUERY_EXCEPTION_MESSAGE, e);
}
return returnIntArray;
} | #vulnerable code
public static int[] executeBatchSQL(String poolName, String sql, Object[][] params) {
int[] returnIntArray = null;
Connection con = null;
try {
con = DB_CONNECTION_MANAGER.getConnection(poolName);
if (con == null) {
throw new ConnectionException(poolName);
}
con.setAutoCommit(false);
returnIntArray = new QueryRunner().batch(con, sql, params);
con.commit();
} catch (Exception e) {
logger.error(QUERY_EXCEPTION_MESSAGE, e);
try {
con.rollback();
} catch (SQLException e1) {
logger.error(ROLLBACK_EXCEPTION_MESSAGE, e1);
}
} finally {
DB_CONNECTION_MANAGER.freeConnection(con);
}
return returnIntArray;
}
#location 22
#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 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 23
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean connect(final Endpoint endpoint) {
final RpcClient rc = this.rpcClient;
if (rc == null) {
throw new IllegalStateException("Client service is uninitialized.");
}
if (isConnected(rc, endpoint)) {
return true;
}
try {
final PingRequest req = PingRequest.newBuilder() //
.setSendTimestamp(System.currentTimeMillis()) //
.build();
final ErrorResponse resp = (ErrorResponse) rc.invokeSync(endpoint.toString(), req, this.defaultInvokeCtx,
this.rpcOptions.getRpcConnectTimeoutMs());
return resp.getErrorCode() == 0;
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} catch (final RemotingException e) {
LOG.error("Fail to connect {}, remoting exception: {}.", endpoint, e.getMessage());
return false;
}
} | #vulnerable code
@Override
public boolean connect(final Endpoint endpoint) {
if (this.rpcClient == null) {
throw new IllegalStateException("Client service is not inited.");
}
if (isConnected(endpoint)) {
return true;
}
try {
final PingRequest req = PingRequest.newBuilder() //
.setSendTimestamp(System.currentTimeMillis()) //
.build();
final ErrorResponse resp = (ErrorResponse) this.rpcClient.invokeSync(endpoint.toString(), req,
this.defaultInvokeCtx, this.rpcOptions.getRpcConnectTimeoutMs());
return resp.getErrorCode() == 0;
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} catch (final RemotingException e) {
LOG.error("Fail to connect {}, remoting exception: {}.", endpoint, e.getMessage());
return false;
}
}
#location 3
#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
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 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void cancel() {
this.lock.lock();
try {
if (this.finished) {
return;
}
if (this.timer != null) {
this.timer.cancel(true);
}
if (this.rpcCall != null) {
this.rpcCall.cancel(true);
}
if (this.st.isOk()) {
this.st.setError(RaftError.ECANCELED, RaftError.ECANCELED.name());
}
this.onFinished();
} finally {
this.lock.unlock();
}
} | #vulnerable code
@Override
public void cancel() {
lock.lock();
try {
if (this.finished) {
return;
}
if (this.timer != null) {
this.timer.cancel(true);
}
if (this.rpcCall != null) {
this.rpcCall.cancel(true);
}
if (st.isOk()) {
st.setError(RaftError.ECANCELED, RaftError.ECANCELED.name());
}
this.onFinished();
} finally {
lock.unlock();
}
}
#location 9
#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 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
@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
@Override
public boolean isConnected(final Endpoint endpoint) {
final RpcClient rc = this.rpcClient;
return rc != null && isConnected(rc, endpoint);
} | #vulnerable code
@Override
public boolean isConnected(final Endpoint endpoint) {
return this.rpcClient.checkConnection(endpoint.toString());
}
#location 3
#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 4
#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
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
@Override
public void addLeaderStateListener(final long regionId, final LeaderStateListener listener) {
addStateListener(regionId, listener);
} | #vulnerable code
@Override
public void addLeaderStateListener(final long regionId, final LeaderStateListener 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().addLeaderStateListener(listener);
}
#location 7
#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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.