output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
public void testHttpPostsWithExpectationVerification() throws Exception {
Job[] jobs = new Job[3];
jobs[0] = new Job("AAAAA", 10);
jobs[1] = new Job("AAAAA", 10);
jobs[2] = new Job("BBBBB", 20);
Queue<Job> queue = new ConcurrentLinkedQueue<Job>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() {
public void verify(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException {
String s = request.getRequestLine().getUri();
if (!s.equals("AAAAAx10")) {
response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED);
NByteArrayEntity outgoing = new NByteArrayEntity(
EncodingUtils.getAsciiBytes("Expectation failed"));
response.setEntity(outgoing);
}
}
};
HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(Job testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
return r;
}
};
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new RequestHandler()));
serviceHandler.setExpectationVerifier(
expectationVerifier);
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < 2; i++) {
Job testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
Job failedExpectation = jobs[2];
failedExpectation.waitFor();
assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode());
} | #vulnerable code
public void testHttpPostsWithExpectationVerification() throws Exception {
TestJob[] jobs = new TestJob[3];
jobs[0] = new TestJob("AAAAA", 10);
jobs[1] = new TestJob("AAAAA", 10);
jobs[2] = new TestJob("BBBBB", 20);
Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() {
public void verify(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException {
String s = request.getRequestLine().getUri();
if (!s.equals("AAAAAx10")) {
response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED);
NByteArrayEntity outgoing = new NByteArrayEntity(
EncodingUtils.getAsciiBytes("Expectation failed"));
response.setEntity(outgoing);
}
}
};
HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(TestJob testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
return r;
}
};
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new TestRequestHandler()));
serviceHandler.setExpectationVerifier(
expectationVerifier);
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < 2; i++) {
TestJob testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
TestJob failedExpectation = jobs[2];
failedExpectation.waitFor();
assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode());
}
#location 84
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void run() {
HttpResponse response = null;
BenchmarkConnection conn = new BenchmarkConnection(this.stats);
String scheme = targetHost.getSchemeName();
String hostname = targetHost.getHostName();
int port = targetHost.getPort();
if (port == -1) {
if (scheme.equalsIgnoreCase("https")) {
port = 443;
} else {
port = 80;
}
}
// Populate the execution context
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost);
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request);
stats.start();
for (int i = 0; i < count; i++) {
try {
resetHeader(request);
if (!conn.isOpen()) {
Socket socket;
if (socketFactory != null) {
socket = socketFactory.createSocket();
} else {
socket = new Socket();
}
HttpParams params = request.getParams();
int connTimeout = params.getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0);
int soTimeout = params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0);
socket.setSoTimeout(soTimeout);
socket.connect(new InetSocketAddress(hostname, port), connTimeout);
conn.bind(socket, params);
}
try {
// Prepare request
this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context);
// Execute request and get a response
response = this.httpexecutor.execute(this.request, conn, this.context);
// Finalize response
this.httpexecutor.postProcess(response, this.httpProcessor, this.context);
} catch (HttpException e) {
stats.incWriteErrors();
if (this.verbosity >= 2) {
System.err.println("Failed HTTP request : " + e.getMessage());
}
continue;
}
verboseOutput(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
stats.incSuccessCount();
} else {
stats.incFailureCount();
continue;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
ContentType ct = ContentType.get(entity);
Charset charset = ct.getCharset();
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
long contentlen = 0;
InputStream instream = entity.getContent();
int l = 0;
while ((l = instream.read(this.buffer)) != -1) {
contentlen += l;
if (this.verbosity >= 4) {
String s = new String(this.buffer, 0, l, charset.name());
System.out.print(s);
}
}
instream.close();
stats.setContentLength(contentlen);
}
if (this.verbosity >= 4) {
System.out.println();
System.out.println();
}
if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) {
conn.close();
} else {
stats.incKeepAliveCount();
}
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
} catch (Exception ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("Generic error: " + ex.getMessage());
}
}
}
stats.finish();
if (response != null) {
Header header = response.getFirstHeader("Server");
if (header != null) {
stats.setServerName(header.getValue());
}
}
try {
conn.close();
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
}
} | #vulnerable code
public void run() {
HttpResponse response = null;
BenchmarkConnection conn = new BenchmarkConnection(this.stats);
String scheme = targetHost.getSchemeName();
String hostname = targetHost.getHostName();
int port = targetHost.getPort();
if (port == -1) {
if (scheme.equalsIgnoreCase("https")) {
port = 443;
} else {
port = 80;
}
}
// Populate the execution context
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost);
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request);
stats.start();
for (int i = 0; i < count; i++) {
try {
resetHeader(request);
if (!conn.isOpen()) {
Socket socket;
if (socketFactory != null) {
socket = socketFactory.createSocket();
} else {
socket = new Socket();
}
HttpParams params = request.getParams();
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
socket.setSoTimeout(soTimeout);
socket.connect(new InetSocketAddress(hostname, port), connTimeout);
conn.bind(socket, params);
}
try {
// Prepare request
this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context);
// Execute request and get a response
response = this.httpexecutor.execute(this.request, conn, this.context);
// Finalize response
this.httpexecutor.postProcess(response, this.httpProcessor, this.context);
} catch (HttpException e) {
stats.incWriteErrors();
if (this.verbosity >= 2) {
System.err.println("Failed HTTP request : " + e.getMessage());
}
continue;
}
verboseOutput(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
stats.incSuccessCount();
} else {
stats.incFailureCount();
continue;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
ContentType ct = ContentType.get(entity);
Charset charset = ct.getCharset();
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
long contentlen = 0;
InputStream instream = entity.getContent();
int l = 0;
while ((l = instream.read(this.buffer)) != -1) {
contentlen += l;
if (this.verbosity >= 4) {
String s = new String(this.buffer, 0, l, charset.name());
System.out.print(s);
}
}
instream.close();
stats.setContentLength(contentlen);
}
if (this.verbosity >= 4) {
System.out.println();
System.out.println();
}
if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) {
conn.close();
} else {
stats.incKeepAliveCount();
}
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
} catch (Exception ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("Generic error: " + ex.getMessage());
}
}
}
stats.finish();
if (response != null) {
Header header = response.getFirstHeader("Server");
if (header != null) {
stats.setServerName(header.getValue());
}
}
try {
conn.close();
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
}
}
#location 103
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testInputThrottling() throws Exception {
HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() {
public void initalizeContext(final HttpContext context, final Object attachment) {
context.setAttribute("queue", attachment);
}
public HttpRequest submitRequest(final HttpContext context) {
@SuppressWarnings("unchecked")
Queue<Job> queue = (Queue<Job>) context.getAttribute("queue");
if (queue == null) {
throw new IllegalStateException("Queue is null");
}
Job testjob = queue.poll();
context.setAttribute("job", testjob);
if (testjob != null) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
StringEntity entity = null;
try {
entity = new StringEntity(testjob.getExpected(), "US-ASCII");
entity.setChunked(testjob.getCount() % 2 == 0);
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
return r;
} else {
return null;
}
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
Job testjob = (Job) context.removeAttribute("job");
if (testjob == null) {
throw new IllegalStateException("TestJob is null");
}
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
// Simulate slow response handling in order to cause the
// internal content buffer to fill up, forcing the
// protocol handler to throttle input rate
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
InputStream instream = entity.getContent();
byte[] tmp = new byte[2048];
int l;
while((l = instream.read(tmp)) != -1) {
Thread.sleep(1);
outstream.write(tmp, 0, l);
}
content = new String(outstream.toByteArray(),
EntityUtils.getContentCharSet(entity));
} catch (InterruptedException ex) {
content = "Interrupted: " + ex.getMessage();
} catch (IOException ex) {
content = "I/O exception: " + ex.getMessage();
}
}
testjob.setResult(statusCode, content);
}
public void finalizeContext(final HttpContext context) {
Job testjob = (Job) context.removeAttribute("job");
if (testjob != null) {
testjob.fail("Request failed");
}
}
};
int connNo = 3;
int reqNo = 20;
Job[] jobs = new Job[connNo * reqNo];
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new Job(10000);
}
Queue<Job> queue = new ConcurrentLinkedQueue<Job>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new RequestHandler()));
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>();
for (int i = 0; i < connNo; i++) {
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
connRequests.add(sessionRequest);
}
while (!connRequests.isEmpty()) {
SessionRequest sessionRequest = connRequests.remove();
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
}
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < jobs.length; i++) {
Job testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(HttpStatus.SC_OK, testjob.getStatusCode());
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
} | #vulnerable code
public void testInputThrottling() throws Exception {
HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() {
public void initalizeContext(final HttpContext context, final Object attachment) {
context.setAttribute("queue", attachment);
}
public HttpRequest submitRequest(final HttpContext context) {
@SuppressWarnings("unchecked")
Queue<TestJob> queue = (Queue<TestJob>) context.getAttribute("queue");
if (queue == null) {
throw new IllegalStateException("Queue is null");
}
TestJob testjob = queue.poll();
context.setAttribute("job", testjob);
if (testjob != null) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
StringEntity entity = null;
try {
entity = new StringEntity(testjob.getExpected(), "US-ASCII");
entity.setChunked(testjob.getCount() % 2 == 0);
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
return r;
} else {
return null;
}
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
TestJob testjob = (TestJob) context.removeAttribute("job");
if (testjob == null) {
throw new IllegalStateException("TestJob is null");
}
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
// Simulate slow response handling in order to cause the
// internal content buffer to fill up, forcing the
// protocol handler to throttle input rate
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
InputStream instream = entity.getContent();
byte[] tmp = new byte[2048];
int l;
while((l = instream.read(tmp)) != -1) {
Thread.sleep(1);
outstream.write(tmp, 0, l);
}
content = new String(outstream.toByteArray(),
EntityUtils.getContentCharSet(entity));
} catch (InterruptedException ex) {
content = "Interrupted: " + ex.getMessage();
} catch (IOException ex) {
content = "I/O exception: " + ex.getMessage();
}
}
testjob.setResult(statusCode, content);
}
public void finalizeContext(final HttpContext context) {
TestJob testjob = (TestJob) context.removeAttribute("job");
if (testjob != null) {
testjob.fail("Request failed");
}
}
};
int connNo = 3;
int reqNo = 20;
TestJob[] jobs = new TestJob[connNo * reqNo];
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new TestJob(10000);
}
Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new TestRequestHandler()));
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>();
for (int i = 0; i < connNo; i++) {
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
connRequests.add(sessionRequest);
}
while (!connRequests.isEmpty()) {
SessionRequest sessionRequest = connRequests.remove();
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
}
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < jobs.length; i++) {
TestJob testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(HttpStatus.SC_OK, testjob.getStatusCode());
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
}
#location 124
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testEntityWithMultipleContentLength() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "1");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
} | #vulnerable code
@Test
public void testEntityWithMultipleContentLength() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "1");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testTooLongChunkHeader() throws IOException {
final String input = "5; and some very looooong commend\r\n12345\r\n0\r\n";
final InputStream in1 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.DEFAULT, Consts.ISO_8859_1));
final byte[] buffer = new byte[300];
Assert.assertEquals(5, in1.read(buffer));
in1.close();
final InputStream in2 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.lineLen(10), Consts.ISO_8859_1));
try {
in2.read(buffer);
Assert.fail("MessageConstraintException expected");
} catch (MessageConstraintException ex) {
} finally {
in2.close();
}
} | #vulnerable code
@Test
public void testTooLongChunkHeader() throws IOException {
final String input = "5; and some very looooong commend\r\n12345\r\n0\r\n";
final InputStream in1 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.DEFAULT, Consts.ISO_8859_1));
final byte[] buffer = new byte[300];
Assert.assertEquals(5, in1.read(buffer));
final InputStream in2 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.lineLen(10), Consts.ISO_8859_1));
try {
in2.read(buffer);
Assert.fail("MessageConstraintException expected");
} catch (MessageConstraintException ex) {
}
}
#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 testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 1);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
Assert.assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
Assert.fail("expected IOException");
} catch(IOException iox) {}
testfile.close();
deleteWithCheck(fileHandle);
} | #vulnerable code
@Test
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 1);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
Assert.assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
Assert.fail("expected IOException");
} catch(IOException iox) {}
testfile.close();
deleteWithCheck(fileHandle);
}
#location 19
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 1);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
fail("expected IOException");
} catch(IOException iox) {}
testfile.close();
deleteWithCheck(fileHandle);
} | #vulnerable code
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 1);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
fail("expected IOException");
} catch(IOException iox) {}
deleteWithCheck(fileHandle);
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void validate(final Set keys) {
long currentTime = System.currentTimeMillis();
if( (currentTime - this.lastTimeoutCheck) >= this.timeoutCheckInterval) {
this.lastTimeoutCheck = currentTime;
if (keys != null) {
for (Iterator it = keys.iterator(); it.hasNext();) {
SelectionKey key = (SelectionKey) it.next();
timeoutCheck(key, currentTime);
}
}
}
if (!this.bufferingSessions.isEmpty()) {
for (Iterator it = this.bufferingSessions.iterator(); it.hasNext(); ) {
IOSession session = (IOSession) it.next();
SessionBufferStatus bufStatus = session.getBufferStatus();
if (bufStatus != null) {
if (!bufStatus.hasBufferedInput()) {
it.remove();
continue;
}
}
try {
int ops = session.getEventMask();
if ((ops & EventMask.READ) > 0) {
this.eventDispatch.inputReady(session);
if (bufStatus != null) {
if (!bufStatus.hasBufferedInput()) {
it.remove();
}
}
}
} catch (CancelledKeyException ex) {
it.remove();
}
}
}
} | #vulnerable code
protected void validate(final Set keys) {
long currentTime = System.currentTimeMillis();
if( (currentTime - this.lastTimeoutCheck) >= this.timeoutCheckInterval) {
this.lastTimeoutCheck = currentTime;
if (keys != null) {
for (Iterator it = keys.iterator(); it.hasNext();) {
SelectionKey key = (SelectionKey) it.next();
timeoutCheck(key, currentTime);
}
}
}
synchronized (this.bufferingSessions) {
if (!this.bufferingSessions.isEmpty()) {
for (Iterator it = this.bufferingSessions.iterator(); it.hasNext(); ) {
IOSession session = (IOSession) it.next();
SessionBufferStatus bufStatus = session.getBufferStatus();
if (bufStatus != null) {
if (!bufStatus.hasBufferedInput()) {
it.remove();
continue;
}
}
try {
int ops = session.getEventMask();
if ((ops & EventMask.READ) > 0) {
this.eventDispatch.inputReady(session);
if (bufStatus != null) {
if (!bufStatus.hasBufferedInput()) {
it.remove();
}
}
}
} catch (CancelledKeyException ex) {
it.remove();
}
}
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public HttpClientConnection create(final HttpHost host) throws IOException {
final String scheme = host.getSchemeName();
Socket socket = null;
if ("http".equalsIgnoreCase(scheme)) {
socket = this.plainfactory != null ? this.plainfactory.createSocket() :
new Socket();
} if ("https".equalsIgnoreCase(scheme)) {
socket = (this.sslfactory != null ? this.sslfactory :
SSLSocketFactory.getDefault()).createSocket();
}
if (socket == null) {
throw new IOException(scheme + " scheme is not supported");
}
final String hostname = host.getHostName();
int port = host.getPort();
if (port == -1) {
if (host.getSchemeName().equalsIgnoreCase("http")) {
port = 80;
} else if (host.getSchemeName().equalsIgnoreCase("https")) {
port = 443;
}
}
socket.setSoTimeout(this.sconfig.getSoTimeout());
socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout);
socket.setTcpNoDelay(this.sconfig.isTcpNoDelay());
final int linger = this.sconfig.getSoLinger();
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
return this.connFactory.createConnection(socket);
} | #vulnerable code
public HttpClientConnection create(final HttpHost host) throws IOException {
final String scheme = host.getSchemeName();
Socket socket = null;
if ("http".equalsIgnoreCase(scheme)) {
socket = this.plainfactory != null ? this.plainfactory.createSocket() :
new Socket();
} if ("https".equalsIgnoreCase(scheme)) {
if (this.sslfactory != null) {
socket = this.sslfactory.createSocket();
}
}
if (socket == null) {
throw new IOException(scheme + " scheme is not supported");
}
final String hostname = host.getHostName();
int port = host.getPort();
if (port == -1) {
if (host.getSchemeName().equalsIgnoreCase("http")) {
port = 80;
} else if (host.getSchemeName().equalsIgnoreCase("https")) {
port = 443;
}
}
socket.setSoTimeout(this.sconfig.getSoTimeout());
socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout);
socket.setTcpNoDelay(this.sconfig.isTcpNoDelay());
final int linger = this.sconfig.getSoLinger();
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
return this.connFactory.createConnection(socket);
}
#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 testEntityWithMultipleContentLengthSomeWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "1");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
} | #vulnerable code
@Test
public void testEntityWithMultipleContentLengthSomeWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "1");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void doShutdown() throws InterruptedIOException {
synchronized (this.statusLock) {
if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
}
try {
cancelRequests();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
this.selector.wakeup();
// Close out all channels
if (this.selector.isOpen()) {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
try {
SelectionKey key = it.next();
Channel channel = key.channel();
if (channel != null) {
channel.close();
}
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Stop dispatching I/O events
try {
this.selector.close();
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Attempt to shut down I/O dispatchers gracefully
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
dispatcher.gracefulShutdown();
}
long gracePeriod = NIOReactorParams.getGracePeriod(this.params);
try {
// Force shut down I/O dispatchers if they fail to terminate
// in time
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) {
dispatcher.awaitShutdown(gracePeriod);
}
if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) {
try {
dispatcher.hardShutdown();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
}
}
// Join worker threads
for (int i = 0; i < this.workerCount; i++) {
Thread t = this.threads[i];
if (t != null) {
t.join(gracePeriod);
}
}
} catch (InterruptedException ex) {
throw new InterruptedIOException(ex.getMessage());
}
} | #vulnerable code
protected void doShutdown() throws InterruptedIOException {
if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
try {
cancelRequests();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
this.selector.wakeup();
// Close out all channels
if (this.selector.isOpen()) {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
try {
SelectionKey key = it.next();
Channel channel = key.channel();
if (channel != null) {
channel.close();
}
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Stop dispatching I/O events
try {
this.selector.close();
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Attempt to shut down I/O dispatchers gracefully
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
dispatcher.gracefulShutdown();
}
long gracePeriod = NIOReactorParams.getGracePeriod(this.params);
try {
// Force shut down I/O dispatchers if they fail to terminate
// in time
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) {
dispatcher.awaitShutdown(gracePeriod);
}
if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) {
try {
dispatcher.hardShutdown();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
}
}
// Join worker threads
for (int i = 0; i < this.workerCount; i++) {
Thread t = this.threads[i];
if (t != null) {
t.join(gracePeriod);
}
}
} catch (InterruptedException ex) {
throw new InterruptedIOException(ex.getMessage());
}
}
#location 65
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testHttpPostsWithExpectationVerification() throws Exception {
Job[] jobs = new Job[3];
jobs[0] = new Job("AAAAA", 10);
jobs[1] = new Job("AAAAA", 10);
jobs[2] = new Job("BBBBB", 20);
Queue<Job> queue = new ConcurrentLinkedQueue<Job>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() {
public void verify(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException {
String s = request.getRequestLine().getUri();
if (!s.equals("AAAAAx10")) {
response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED);
NByteArrayEntity outgoing = new NByteArrayEntity(
EncodingUtils.getAsciiBytes("Expectation failed"));
response.setEntity(outgoing);
}
}
};
HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(Job testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
return r;
}
};
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new RequestHandler()));
serviceHandler.setExpectationVerifier(
expectationVerifier);
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < 2; i++) {
Job testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
Job failedExpectation = jobs[2];
failedExpectation.waitFor();
assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode());
} | #vulnerable code
public void testHttpPostsWithExpectationVerification() throws Exception {
TestJob[] jobs = new TestJob[3];
jobs[0] = new TestJob("AAAAA", 10);
jobs[1] = new TestJob("AAAAA", 10);
jobs[2] = new TestJob("BBBBB", 20);
Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() {
public void verify(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException {
String s = request.getRequestLine().getUri();
if (!s.equals("AAAAAx10")) {
response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED);
NByteArrayEntity outgoing = new NByteArrayEntity(
EncodingUtils.getAsciiBytes("Expectation failed"));
response.setEntity(outgoing);
}
}
};
HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(TestJob testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
return r;
}
};
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new TestRequestHandler()));
serviceHandler.setExpectationVerifier(
expectationVerifier);
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < 2; i++) {
TestJob testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
TestJob failedExpectation = jobs[2];
failedExpectation.waitFor();
assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode());
}
#location 87
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testEntityWithMultipleContentLengthAllWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertFalse(instream instanceof ContentLengthInputStream);
Assert.assertTrue(instream instanceof IdentityInputStream);
} | #vulnerable code
@Test
public void testEntityWithMultipleContentLengthAllWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertFalse(instream instanceof ContentLengthInputStream);
Assert.assertTrue(instream instanceof IdentityInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testEntityWithMultipleContentLength() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "1");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
} | #vulnerable code
@Test
public void testEntityWithMultipleContentLength() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "1");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testResponseContentOverwriteHeaders() throws Exception {
ResponseContent interceptor = new ResponseContent(true);
HttpContext context = new BasicHttpContext(null);
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, "10"));
response.addHeader(new BasicHeader(HTTP.TRANSFER_ENCODING, "whatever"));
interceptor.process(response, context);
Assert.assertEquals("0", response.getFirstHeader(HTTP.CONTENT_LEN).getValue());
} | #vulnerable code
@Test
public void testResponseContentOverwriteHeaders() throws Exception {
ResponseContent interceptor = new ResponseContent(true);
HttpContext context = new BasicHttpContext(null);
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, "10"));
response.addHeader(new BasicHeader(HTTP.TRANSFER_ENCODING, "whatever"));
interceptor.process(response, context);
Assert.assertEquals("0", response.getFirstHeader(HTTP.CONTENT_LEN).getValue());
Assert.assertEquals("whatever", response.getFirstHeader(HTTP.TRANSFER_ENCODING).getValue());
}
#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 testLoadReleaseConfigDefaultConfigsAndOverrideApp() {
long appId = 6666;
long versionId = 100;
long releaseId = 11111;
VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId);
ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[1];
someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, ConfigConsts.DEFAULT_CLUSTER_NAME,
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\", \"5555.bar\":\"demo2\", \"22.bar\":\"demo2\"}");
when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion);
when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots);
AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId);
assertEquals(appConfigVO.getAppId(), appId);
assertEquals(appConfigVO.getVersionId(), versionId);
assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2);
assertEquals(2, appConfigVO.getOverrideAppConfigs().size());
assertEquals(appConfigVO.getOverrideClusterConfigs().size(), 0);
} | #vulnerable code
@Test
public void testLoadReleaseConfigDefaultConfigsAndOverrideApp() {
long appId = 6666;
long versionId = 100;
long releaseId = 11111;
VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId);
ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[1];
someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, Constants.DEFAULT_CLUSTER_NAME,
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\", \"5555.bar\":\"demo2\", \"22.bar\":\"demo2\"}");
when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion);
when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots);
AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId);
assertEquals(appConfigVO.getAppId(), appId);
assertEquals(appConfigVO.getVersionId(), versionId);
assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2);
assertEquals(2, appConfigVO.getOverrideAppConfigs().size());
assertEquals(appConfigVO.getOverrideClusterConfigs().size(), 0);
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean isServiceUndeployed(int environmentId, int serviceId){
Date latestDeploymentDate = getLatestDeploymentDateByServiceIdInEnvironment(environmentId, serviceId);
Date latestUpdatedDate = getLatestDeployableVersionDateByServiceId(serviceId);
if(latestDeploymentDate != null) {
long diffBetweenDatesInDays = getTimeDiffInDays(latestDeploymentDate, latestUpdatedDate);
return diffBetweenDatesInDays > MAX_DAYS_OF_UNDEPLOYED_SERVICES ? true : false;
}
if(latestUpdatedDate != null) {
Date maxDateSinceLatestUpdate = getMaxDateSinceLatestUpdate();
if(latestUpdatedDate.compareTo(maxDateSinceLatestUpdate) < 0) {
return true;
}
}
return false;
} | #vulnerable code
private boolean isServiceUndeployed(int environmentId, int serviceId){
Date latestDeploymentDate = getLatestDeploymentDateByServiceIdInEnvironment(environmentId, serviceId);
Date latestUpdatedDate = getLatestDeployableVersionDateByServiceId(serviceId);
if(latestDeploymentDate != null) {
long diffBetweenDatesInDays = TimeUnit.DAYS.convert(Math.abs(latestDeploymentDate.getTime() - latestUpdatedDate.getTime()), TimeUnit.MILLISECONDS);
return diffBetweenDatesInDays > MIN_DAYS_OF_UNDEPLOYED_SERVICES ? true : false;
}
if(latestUpdatedDate != null) {
Date durationSinceLatestUpdate = Date.from(LocalDate.now().minusDays((long) MIN_DAYS_OF_UNDEPLOYED_SERVICES).atStartOfDay(ZoneId.systemDefault()).toInstant());
if(latestUpdatedDate.compareTo(durationSinceLatestUpdate) < 0) {
return true;
}
}
return false;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testLoadReleaseConfigDefaultConfigsAndOverrideCluster() {
long appId = 6666;
long versionId = 100;
long releaseId = 11111;
VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId);
ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[2];
someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, ConfigConsts.DEFAULT_CLUSTER_NAME,
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}");
someReleaseSnapShots[1] = assembleReleaseSnapShot(11112, "cluster1",
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}");
when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion);
when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots);
AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId);
assertEquals(appConfigVO.getAppId(), appId);
assertEquals(appConfigVO.getVersionId(), versionId);
assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2);
assertEquals(0, appConfigVO.getOverrideAppConfigs().size());
assertEquals(1, appConfigVO.getOverrideClusterConfigs().size());
} | #vulnerable code
@Test
public void testLoadReleaseConfigDefaultConfigsAndOverrideCluster() {
long appId = 6666;
long versionId = 100;
long releaseId = 11111;
VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId);
ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[2];
someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, Constants.DEFAULT_CLUSTER_NAME,
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}");
someReleaseSnapShots[1] = assembleReleaseSnapShot(11112, "cluster1",
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}");
when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion);
when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots);
AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId);
assertEquals(appConfigVO.getAppId(), appId);
assertEquals(appConfigVO.getVersionId(), versionId);
assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2);
assertEquals(0, appConfigVO.getOverrideAppConfigs().size());
assertEquals(1, appConfigVO.getOverrideClusterConfigs().size());
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBlockByAvailabilityOnAllServices() throws Exception {
ApolloTestClient apolloTestClient = Common.signupAndLogin();
ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient();
String availability = "BLOCK-ME-2";
Environment blockedEnvironment = ModelsGenerator.createAndSubmitEnvironment(availability, apolloTestClient);
Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient);
Service service = ModelsGenerator.createAndSubmitService(apolloTestClient);
DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service);
ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion);
createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, null, null, availability);
assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, blockedEnvironment, service, deployableVersion)).isInstanceOf(Exception.class)
.hasMessageContaining("Deployment is currently blocked");
} | #vulnerable code
@Test
public void testBlockByAvailabilityOnAllServices() throws Exception {
ApolloTestClient apolloTestClient = Common.signupAndLogin();
ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient();
String availability = "BLOCK-ME-2";
Environment environment = ModelsGenerator.createAndSubmitEnvironment(availability, apolloTestClient);
Service service = ModelsGenerator.createAndSubmitService(apolloTestClient);
createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, null, null, availability);
DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service);
assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion)).isInstanceOf(Exception.class)
.hasMessageContaining("Deployment is currently blocked");
}
#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 onWhenRequested() throws Exception {
setup("server.port=0", "spring.cloud.config.discovery.enabled=true",
"logging.level.org.springframework.cloud.config.client=DEBUG",
"spring.cloud.consul.discovery.test.enabled:true",
"spring.application.name=discoveryclientconfigservicetest",
"spring.cloud.consul.discovery.port:7001",
"spring.cloud.consul.discovery.hostname:foo",
"spring.cloud.config.discovery.service-id:configserver");
assertEquals( 1, this.context
.getBeanNamesForType(ConsulConfigServerAutoConfiguration.class).length);
ConsulDiscoveryClient client = this.context.getParent().getBean(
ConsulDiscoveryClient.class);
verify(client, atLeast(2)).getInstances("configserver");
ConfigClientProperties locator = this.context
.getBean(ConfigClientProperties.class);
assertEquals("http://foo:7001/", locator.getUri()[0]);
} | #vulnerable code
@Test
public void onWhenRequested() throws Exception {
setup("server.port=7000", "spring.cloud.config.discovery.enabled=true",
"spring.cloud.consul.discovery.port:7001",
"spring.cloud.consul.discovery.hostname:foo",
"spring.cloud.config.discovery.service-id:configserver");
assertEquals( 1, this.context
.getBeanNamesForType(ConsulConfigServerAutoConfiguration.class).length);
ConsulDiscoveryClient client = this.context.getParent().getBean(
ConsulDiscoveryClient.class);
verify(client, atLeast(2)).getInstances("configserver");
ConfigClientProperties locator = this.context
.getBean(ConfigClientProperties.class);
assertEquals("http://foo:7001/", locator.getUri()[0]);
}
#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 propertySourcesFound() throws Exception {
String foo = this.environment.getProperty("foo");
assertThat(foo).as("foo was wrong").isEqualTo("bar-app-dev");
String myBaz = this.environment.getProperty("my.baz");
assertThat(myBaz).as("my.baz was wrong").isEqualTo("bar-app-dev");
MutablePropertySources propertySources = this.environment.getPropertySources();
PropertySource<?> bootstrapProperties = propertySources
.get("bootstrapProperties");
assertThat(bootstrapProperties).as("bootstrapProperties was null").isNotNull();
assertThat(bootstrapProperties).as("bootstrapProperties was wrong type")
.isInstanceOf(CompositePropertySource.class);
Collection<PropertySource<?>> consulSources = ((CompositePropertySource) bootstrapProperties)
.getPropertySources();
assertThat(consulSources).as("consulSources was wrong size").hasSize(1);
PropertySource<?> consulSource = consulSources.iterator().next();
assertThat(consulSource).as("consulSource was wrong type")
.isInstanceOf(CompositePropertySource.class);
Collection<PropertySource<?>> fileSources = ((CompositePropertySource) consulSource)
.getPropertySources();
assertThat(fileSources).as("fileSources was wrong size").hasSize(4);
assertFileSourceNames(fileSources, APP_NAME_DEV_PROPS, APP_NAME_PROPS,
APPLICATION_DEV_YML, APPLICATION_YML);
} | #vulnerable code
@Test
public void propertySourcesFound() throws Exception {
String foo = this.environment.getProperty("foo");
assertThat(foo).as("foo was wrong").isEqualTo("bar-app-dev");
String myBaz = this.environment.getProperty("my.baz");
assertThat(myBaz).as("my.baz was wrong").isEqualTo("bar-app-dev");
MutablePropertySources propertySources = this.environment.getPropertySources();
PropertySource<?> bootstrapProperties = propertySources
.get("bootstrapProperties");
assertThat(bootstrapProperties).as("bootstrapProperties was null").isNotNull();
assertThat(bootstrapProperties.getClass())
.as("bootstrapProperties was wrong type")
.isInstanceOf(CompositePropertySource.class);
Collection<PropertySource<?>> consulSources = ((CompositePropertySource) bootstrapProperties)
.getPropertySources();
assertThat(consulSources).as("consulSources was wrong size").hasSize(1);
PropertySource<?> consulSource = consulSources.iterator().next();
assertThat(consulSource.getClass()).as("consulSource was wrong type")
.isInstanceOf(CompositePropertySource.class);
Collection<PropertySource<?>> fileSources = ((CompositePropertySource) consulSource)
.getPropertySources();
assertThat(fileSources).as("fileSources was wrong size").hasSize(4);
assertFileSourceNames(fileSources, APP_NAME_DEV_PROPS, APP_NAME_PROPS,
APPLICATION_DEV_YML, APPLICATION_YML);
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public <T> T get(Class<? extends T> clazz, long id) throws EntityNotFoundException
{
// The cast gets rid of "no unique maximal instance exists" compiler error
return (T)this.get(new OKey<T>(clazz, id));
} | #vulnerable code
@Override
public <T> T get(Class<? extends T> clazz, long id) throws EntityNotFoundException
{
// The cast gets rid of "no unique maximal instance exists" compiler error
return (T)this.get(this.factory.createKey(clazz, id));
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public <T> T get(Class<? extends T> clazz, String name) throws EntityNotFoundException
{
// The cast gets rid of "no unique maximal instance exists" compiler error
return (T)this.get(new OKey<T>(clazz, name));
} | #vulnerable code
@Override
public <T> T get(Class<? extends T> clazz, String name) throws EntityNotFoundException
{
// The cast gets rid of "no unique maximal instance exists" compiler error
return (T)this.get(this.factory.createKey(clazz, name));
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test public void tooDeeplyNestedObjects() throws IOException {
Object root = Boolean.TRUE;
for (int i = 0; i < MAX_DEPTH + 1; i++) {
root = singletonMap("a", root);
}
JsonReader reader = new JsonValueReader(root);
for (int i = 0; i < MAX_DEPTH; i++) {
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
}
try {
reader.beginObject();
fail();
} catch (JsonDataException expected) {
assertThat(expected).hasMessage("Nesting too deep at $" + repeat(".a", MAX_DEPTH) + ".");
}
} | #vulnerable code
@Test public void tooDeeplyNestedObjects() throws IOException {
Object root = Boolean.TRUE;
for (int i = 0; i < 32; i++) {
root = singletonMap("a", root);
}
JsonReader reader = new JsonValueReader(root);
for (int i = 0; i < 31; i++) {
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
}
try {
reader.beginObject();
fail();
} catch (JsonDataException expected) {
assertThat(expected).hasMessage(
"Nesting too deep at $.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.");
}
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test public void readerNullValue() throws Exception {
JsonReader reader = factory.newReader("{\"null\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.null");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
try {
reader.nextNull();
fail();
} catch (JsonDataException e) {
assertThat(e.getMessage()).isIn(
"Expected NULL but was null, a java.lang.String, at path $.null",
"Expected null but was STRING at path $.null");
}
assertThat(reader.nextString()).isEqualTo("null");
assertThat(reader.getPath()).isEqualTo("$.null");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.null");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | #vulnerable code
@Test public void readerNullValue() throws Exception {
JsonReader reader = newReader("{\"null\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.null");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
try {
reader.nextNull();
fail();
} catch (JsonDataException e) {
assertThat(e).hasMessage("Expected null but was STRING at path $.null");
}
assertThat(reader.nextString()).isEqualTo("null");
assertThat(reader.getPath()).isEqualTo("$.null");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.null");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#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 readingDoesNotBuffer() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{}{}");
JsonReader reader1 = JsonReader.of(buffer);
reader1.beginObject();
reader1.endObject();
assertThat(buffer.size()).isEqualTo(2);
JsonReader reader2 = JsonReader.of(buffer);
reader2.beginObject();
reader2.endObject();
assertThat(buffer.size()).isEqualTo(0);
} | #vulnerable code
@Test public void readingDoesNotBuffer() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{}{}");
JsonReader reader1 = new JsonReader(buffer);
reader1.beginObject();
reader1.endObject();
assertThat(buffer.size()).isEqualTo(2);
JsonReader reader2 = new JsonReader(buffer);
reader2.beginObject();
reader2.endObject();
assertThat(buffer.size()).isEqualTo(0);
}
#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 readObjectSource() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{\"a\": \"android\", \"b\": \"banana\"}");
JsonReader reader = JsonReader.of(buffer);
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextString()).isEqualTo("android");
assertThat(reader.nextName()).isEqualTo("b");
assertThat(reader.nextString()).isEqualTo("banana");
reader.endObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
} | #vulnerable code
@Test public void readObjectSource() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{\"a\": \"android\", \"b\": \"banana\"}");
JsonReader reader = new JsonReader(buffer);
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextString()).isEqualTo("android");
assertThat(reader.nextName()).isEqualTo("b");
assertThat(reader.nextString()).isEqualTo("banana");
reader.endObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
}
#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 readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = newReader("[{},{\"a\":5}]");
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
} | #vulnerable code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = new JsonReader(new Buffer().writeUtf8("[{},{\"a\":5}]"));
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
}
#location 2
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test public void readerLongValue() throws Exception {
JsonReader reader = factory.newReader("{\"5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextLong()).isEqualTo(5L);
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | #vulnerable code
@Test public void readerLongValue() throws Exception {
JsonReader reader = newReader("{\"5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextLong()).isEqualTo(5L);
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#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 readObjectBuffer() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{\"a\": \"android\", \"b\": \"banana\"}");
JsonReader reader = JsonReader.of(buffer);
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextString()).isEqualTo("android");
assertThat(reader.nextName()).isEqualTo("b");
assertThat(reader.nextString()).isEqualTo("banana");
reader.endObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
} | #vulnerable code
@Test public void readObjectBuffer() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{\"a\": \"android\", \"b\": \"banana\"}");
JsonReader reader = new JsonReader(buffer);
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextString()).isEqualTo("android");
assertThat(reader.nextName()).isEqualTo("b");
assertThat(reader.nextString()).isEqualTo("banana");
reader.endObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
}
#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 readerBooleanValue() throws Exception {
JsonReader reader = factory.newReader("{\"true\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
try {
reader.nextBoolean();
fail();
} catch (JsonDataException e) {
assertThat(e.getMessage()).isIn(
"Expected BOOLEAN but was true, a java.lang.String, at path $.true",
"Expected a boolean but was STRING at path $.true");
}
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.nextString()).isEqualTo("true");
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | #vulnerable code
@Test public void readerBooleanValue() throws Exception {
JsonReader reader = newReader("{\"true\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
try {
reader.nextBoolean();
fail();
} catch (JsonDataException e) {
assertThat(e).hasMessage("Expected a boolean but was STRING at path $.true");
}
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.nextString()).isEqualTo("true");
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#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 readerUnquotedDoubleValue() throws Exception {
JsonReader reader = factory.newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextDouble()).isEqualTo(5d);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
} | #vulnerable code
@Test public void readerUnquotedDoubleValue() throws Exception {
JsonReader reader = newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextDouble()).isEqualTo(5d);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
}
#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 readerMultipleValueObject() throws Exception {
JsonReader reader = factory.newReader("{\"a\":1,\"b\":2}");
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextInt()).isEqualTo(1);
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.b");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextString()).isEqualTo("b");
assertThat(reader.getPath()).isEqualTo("$.b");
assertThat(reader.nextInt()).isEqualTo(2);
assertThat(reader.getPath()).isEqualTo("$.b");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | #vulnerable code
@Test public void readerMultipleValueObject() throws Exception {
JsonReader reader = newReader("{\"a\":1,\"b\":2}");
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextInt()).isEqualTo(1);
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.b");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextString()).isEqualTo("b");
assertThat(reader.getPath()).isEqualTo("$.b");
assertThat(reader.nextInt()).isEqualTo(2);
assertThat(reader.getPath()).isEqualTo("$.b");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#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 readerUnquotedIntegerValue() throws Exception {
JsonReader reader = factory.newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextInt()).isEqualTo(5);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
} | #vulnerable code
@Test public void readerUnquotedIntegerValue() throws Exception {
JsonReader reader = newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextInt()).isEqualTo(5);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
}
#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 readerStringValue() throws Exception {
JsonReader reader = factory.newReader("{\"a\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.a");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextString()).isEqualTo("a");
assertThat(reader.getPath()).isEqualTo("$.a");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.a");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | #vulnerable code
@Test public void readerStringValue() throws Exception {
JsonReader reader = newReader("{\"a\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.a");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextString()).isEqualTo("a");
assertThat(reader.getPath()).isEqualTo("$.a");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.a");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static JsonWriter of(BufferedSink sink) {
return new JsonUtf8Writer(sink);
} | #vulnerable code
public static JsonWriter of(BufferedSink sink) {
return new JsonUt8Writer(sink);
}
#location 2
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test public void readerEmptyValueObject() throws Exception {
JsonReader reader = factory.newReader("{}");
reader.beginObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT);
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | #vulnerable code
@Test public void readerEmptyValueObject() throws Exception {
JsonReader reader = newReader("{}");
reader.beginObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT);
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#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 readerUnquotedLongValue() throws Exception {
JsonReader reader = factory.newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextLong()).isEqualTo(5L);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
} | #vulnerable code
@Test public void readerUnquotedLongValue() throws Exception {
JsonReader reader = newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextLong()).isEqualTo(5L);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
}
#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 readerDoubleValue() throws Exception {
JsonReader reader = factory.newReader("{\"5.5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextDouble()).isEqualTo(5.5d);
assertThat(reader.getPath()).isEqualTo("$.5.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | #vulnerable code
@Test public void readerDoubleValue() throws Exception {
JsonReader reader = newReader("{\"5.5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextDouble()).isEqualTo(5.5d);
assertThat(reader.getPath()).isEqualTo("$.5.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override void promoteNameToValue() throws IOException {
if (hasNext()) {
String name = nextName();
push(name);
}
} | #vulnerable code
@Override void promoteNameToValue() throws IOException {
Map.Entry<?, ?> peeked = require(Map.Entry.class, Token.NAME);
push(peeked.getKey());
stack[stackSize - 2] = peeked.getValue();
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = factory.newReader("[{},{\"a\":5}]");
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
} | #vulnerable code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = newReader("[{},{\"a\":5}]");
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
}
#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 readerIntegerValue() throws Exception {
JsonReader reader = factory.newReader("{\"5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextInt()).isEqualTo(5);
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | #vulnerable code
@Test public void readerIntegerValue() throws Exception {
JsonReader reader = newReader("{\"5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextInt()).isEqualTo(5);
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static JsonReader of(BufferedSource source) {
return new JsonUtf8Reader(source);
} | #vulnerable code
public static JsonReader of(BufferedSource source) {
return new BufferedSourceJsonReader(source);
}
#location 2
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = newReader("[{},{\"a\":5}]");
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
} | #vulnerable code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = new JsonReader(new Buffer().writeUtf8("[{},{\"a\":5}]"));
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean addOrReplace(byte[] key, V old, V value)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(value);
byte[] oldData = value(old);
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, false, oldData);
} | #vulnerable code
public boolean addOrReplace(byte[] key, V old, V value)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(value);
byte[] oldData = value(old);
if (maxEntrySize > 0L && CheckSegment.sizeOf(keyBuffer, data) > maxEntrySize)
{
remove(key);
putFailCount++;
return false;
}
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, false, oldData);
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
long getWriteOffset() {
return writeOffset;
} | #vulnerable code
FileChannel getWriteChannel() {
return writeChannel;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testDeleteAndMerge() throws Exception {
String directory = "/tmp/HaloDBDeletionTest/testDeleteAndMerge";
HaloDBOptions options = new HaloDBOptions();
options.maxFileSize = 10 * 1024;
options.mergeThresholdPerFile = 0.10;
HaloDB db = getTestDB(directory, options);
int noOfRecords = 10_000;
List<Record> records = TestUtils.insertRandomRecords(db, noOfRecords);
// delete records
Random random = new Random();
Set<Integer> deleted = new HashSet<>();
List<byte[]> newRecords = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
int index = random.nextInt(records.size());
db.delete(records.get(index).getKey());
deleted.add(index);
// also throw in some new records into to mix.
// size is 40 so that we create keys distinct from
// what we used before.
byte[] key = TestUtils.generateRandomByteArray(40);
db.put(key, TestUtils.generateRandomByteArray());
newRecords.add(key);
}
// update the new records to make sure the the files containing tombstones
// will be compacted.
for (byte[] key : newRecords) {
db.put(key, TestUtils.generateRandomByteArray());
}
TestUtils.waitForMergeToComplete(db);
db.close();
db = getTestDBWithoutDeletingFiles(directory, options);
for (int i = 0; i < records.size(); i++) {
byte[] actual = db.get(records.get(i).getKey());
if (deleted.contains(i)) {
Assert.assertNull(actual);
}
else {
Assert.assertEquals(records.get(i).getValue(), actual);
}
}
} | #vulnerable code
@Test
public void testDeleteAndMerge() throws Exception {
String directory = "/tmp/HaloDBDeletionTest/testDeleteAndMerge";
HaloDBOptions options = new HaloDBOptions();
options.mergeJobIntervalInSeconds = 1;
options.maxFileSize = 10 * 1024;
options.mergeThresholdPerFile = 0.10;
HaloDB db = getTestDB(directory, options);
int noOfRecords = 10_000;
List<Record> records = TestUtils.insertRandomRecords(db, noOfRecords);
// delete records
Random random = new Random();
Set<Integer> deleted = new HashSet<>();
List<byte[]> newRecords = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
int index = random.nextInt(records.size());
db.delete(records.get(index).getKey());
deleted.add(index);
// also throw in some new records into to mix.
// size is 40 so that we create keys distinct from
// what we used before.
byte[] key = TestUtils.generateRandomByteArray(40);
db.put(key, TestUtils.generateRandomByteArray());
newRecords.add(key);
}
// update the new records to make sure the the files containing tombstones
// will be compacted.
for (byte[] key : newRecords) {
db.put(key, TestUtils.generateRandomByteArray());
}
TestUtils.waitForMergeToComplete(db);
db.close();
db = getTestDBWithoutDeletingFiles(directory, options);
for (int i = 0; i < records.size(); i++) {
byte[] actual = db.get(records.get(i).getKey());
if (deleted.contains(i)) {
Assert.assertNull(actual);
}
else {
Assert.assertEquals(records.get(i).getValue(), actual);
}
}
}
#location 41
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMerge() throws Exception {
File directory = new File("/tmp/HaloDBTestWithMerge/testMerge");
TestUtils.deleteDirectory(directory);
HaloDBOptions options = new HaloDBOptions();
options.maxFileSize = recordsPerFile * recordSize;
options.mergeThresholdPerFile = 0.5;
options.mergeThresholdFileNumber = 4;
options.isMergeDisabled = false;
options.mergeJobIntervalInSeconds = 2;
options.flushDataSizeBytes = 2048;
HaloDB db = HaloDB.open(directory, options);
Record[] records = insertAndUpdateRecords(numberOfRecords, db);
// wait for the merge jobs to complete.
Thread.sleep(10000);
Map<Long, List<Path>> map = Files.list(directory.toPath())
.filter(path -> HaloDBInternal.DATA_FILE_PATTERN.matcher(path.getFileName().toString()).matches())
.collect(Collectors.groupingBy(path -> path.toFile().length()));
// 4 data files of size 10K.
Assert.assertEquals(map.get(10 * 1024l).size(), 4);
//2 merged data files of size 20K.
Assert.assertEquals(map.get(20 * 1024l).size(), 2);
int sizeOfIndexEntry = IndexFileEntry.INDEX_FILE_HEADER_SIZE + 8;
Map<Long, List<Path>> indexFileSizemap = Files.list(directory.toPath())
.filter(path -> HaloDBInternal.INDEX_FILE_PATTERN.matcher(path.getFileName().toString()).matches())
.collect(Collectors.groupingBy(path -> path.toFile().length()));
// 4 index files of size 220 bytes.
Assert.assertEquals(indexFileSizemap.get(sizeOfIndexEntry * 10l).size(), 4);
// 2 index files of size 440 bytes.
Assert.assertEquals(indexFileSizemap.get(sizeOfIndexEntry * 20l).size(), 2);
for (Record r : records) {
byte[] actual = db.get(r.getKey());
Assert.assertArrayEquals("key -> " + Utils.bytesToLong(r.getKey()), actual, r.getValue());
}
db.close();
TestUtils.deleteDirectory(directory);
} | #vulnerable code
@Test
public void testMerge() throws Exception {
File directory = new File("/tmp/HaloDBTestWithMerge/testMerge");
TestUtils.deleteDirectory(directory);
HaloDBOptions options = new HaloDBOptions();
options.maxFileSize = recordsPerFile * recordSize;
options.mergeThresholdPerFile = 0.5;
options.mergeThresholdFileNumber = 4;
options.isMergeDisabled = false;
options.mergeJobIntervalInSeconds = 2;
options.flushDataSizeBytes = 2048;
HaloDB db = HaloDB.open(directory, options);
Record[] records = insertAndUpdateRecords(numberOfRecords, db);
// wait for the merge jobs to complete.
Thread.sleep(10000);
Map<Long, List<Path>> map = Files.list(directory.toPath())
.filter(path -> HaloDBInternal.DATA_FILE_PATTERN.matcher(path.getFileName().toString()).matches())
.collect(Collectors.groupingBy(path -> path.toFile().length()));
// 4 data files of size 10K.
Assert.assertEquals(map.get(10 * 1024l).size(), 4);
//2 merged data files of size 20K.
Assert.assertEquals(map.get(20 * 1024l).size(), 2);
int sizeOfIndexEntry = IndexFileEntry.INDEX_FILE_HEADER_SIZE + 8;
Map<Long, List<Path>> indexFileSizemap = Files.list(directory.toPath())
.filter(path -> HaloDBInternal.INDEX_FILE_PATTERN.matcher(path.getFileName().toString()).matches())
.collect(Collectors.groupingBy(path -> path.toFile().length()));
// 4 index files of size 220 bytes.
Assert.assertEquals(indexFileSizemap.get(sizeOfIndexEntry * 10l).size(), 4);
// 2 index files of size 440 bytes.
Assert.assertEquals(indexFileSizemap.get(sizeOfIndexEntry * 20l).size(), 2);
for (Record r : records) {
byte[] actual = db.get(r.getKey());
Assert.assertArrayEquals(actual, r.getValue());
}
db.close();
TestUtils.deleteDirectory(directory);
}
#location 45
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean put(byte[] key, V value)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(value);
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, false, null);
} | #vulnerable code
public boolean put(byte[] key, V value)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(value);
if (maxEntrySize > 0L && CheckSegment.sizeOf(keyBuffer, data) > maxEntrySize)
{
remove(key);
putFailCount++;
return false;
}
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, false, null);
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testDeleteInsertCloseAndOpen() throws IOException {
String directory = "/tmp/HaloDBTest/testDeleteInsertCloseAndOpen";
HaloDBOptions options = new HaloDBOptions();
options.isMergeDisabled = true;
options.maxFileSize = 10*1024;
HaloDB db = getTestDB(directory, options);
int noOfRecords = 10_000;
List<Record> records = TestUtils.insertRandomRecords(db, noOfRecords);
List<Record> deleted = new ArrayList<>();
for (int i = 0; i < noOfRecords; i++) {
if (i % 10 == 0) deleted.add(records.get(i));
}
TestUtils.deleteRecords(db, deleted);
// inserting deleted records again.
List<Record> deleteAndInsert = new ArrayList<>();
deleted.forEach(r -> {
try {
byte[] value = TestUtils.generateRandomByteArray();
db.put(r.getKey(), value);
deleteAndInsert.add(new Record(r.getKey(), value));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
db.close();
HaloDB openAgainDB = getTestDBWithoutDeletingFiles(directory, options);
List<Record> remaining = new ArrayList<>();
openAgainDB.newIterator().forEachRemaining(remaining::add);
Assert.assertTrue(remaining.size() == noOfRecords);
// make sure that records that were earlier deleted shows up now, since they were put back later.
deleteAndInsert.forEach(r -> {
try {
Assert.assertEquals(r.getValue(), openAgainDB.get(r.getKey()));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
} | #vulnerable code
@Test
public void testDeleteInsertCloseAndOpen() throws IOException {
String directory = "/tmp/HaloDBTest/testDeleteInsertCloseAndOpen";
HaloDBOptions options = new HaloDBOptions();
options.isMergeDisabled = true;
options.maxFileSize = 10*1024;
HaloDB db = getTestDB(directory, options);
int noOfRecords = 10_000;
List<Record> records = TestUtils.insertRandomRecords(db, noOfRecords);
List<Record> deleted = new ArrayList<>();
for (int i = 0; i < noOfRecords; i++) {
if (i % 10 == 0) deleted.add(records.get(i));
}
TestUtils.deleteRecords(db, deleted);
List<Record> deleteAndInsert = new ArrayList<>();
deleted.forEach(r -> {
try {
byte[] value = TestUtils.generateRandomByteArray();
db.put(r.getKey(), value);
deleteAndInsert.add(new Record(r.getKey(), value));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
HaloDB openAgainDB = HaloDB.open(new File(directory), options);
List<Record> remaining = new ArrayList<>();
openAgainDB.newIterator().forEachRemaining(remaining::add);
Assert.assertTrue(remaining.size() == noOfRecords);
deleteAndInsert.forEach(r -> {
try {
Assert.assertEquals(r.getValue(), db.get(r.getKey()));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
#location 36
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void close() throws IOException {
writeLock.lock();
try {
isClosing = true;
try {
if(!compactionManager.stopCompactionThread())
setIOErrorFlag();
} catch (IOException e) {
logger.error("Error while stopping compaction thread. Setting IOError flag", e);
setIOErrorFlag();
}
if (options.isCleanUpInMemoryIndexOnClose())
inMemoryIndex.close();
if (currentWriteFile != null) {
currentWriteFile.flushToDisk();
currentWriteFile.getIndexFile().flushToDisk();
currentWriteFile.close();
}
if (currentTombstoneFile != null) {
currentTombstoneFile.flushToDisk();
currentTombstoneFile.close();
}
for (HaloDBFile file : readFileMap.values()) {
file.close();
}
DBMetaData metaData = new DBMetaData(dbDirectory);
metaData.loadFromFileIfExists();
metaData.setOpen(false);
metaData.storeToFile();
dbDirectory.close();
if (dbLock != null) {
dbLock.close();
}
} finally {
writeLock.unlock();
}
} | #vulnerable code
void close() throws IOException {
isClosing = true;
try {
if(!compactionManager.stopCompactionThread())
setIOErrorFlag();
} catch (IOException e) {
logger.error("Error while stopping compaction thread. Setting IOError flag", e);
setIOErrorFlag();
}
if (options.isCleanUpInMemoryIndexOnClose())
inMemoryIndex.close();
if (currentWriteFile != null) {
currentWriteFile.flushToDisk();
currentWriteFile.getIndexFile().flushToDisk();
currentWriteFile.close();
}
if (currentTombstoneFile != null) {
currentTombstoneFile.flushToDisk();
currentTombstoneFile.close();
}
for (HaloDBFile file : readFileMap.values()) {
file.close();
}
DBMetaData metaData = new DBMetaData(dbDirectory);
metaData.loadFromFileIfExists();
metaData.setOpen(false);
metaData.storeToFile();
dbDirectory.close();
if (dbLock != null) {
dbLock.close();
}
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean putIfAbsent(byte[] key, V v)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(v);
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, true, null);
} | #vulnerable code
public boolean putIfAbsent(byte[] key, V v)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(v);
if (maxEntrySize > 0L && CheckSegment.sizeOf(keyBuffer, data) > maxEntrySize)
{
remove(key);
putFailCount++;
return false;
}
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, true, null);
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void close() throws IOException {
writeLock.lock();
try {
if (isClosing) {
// instance already closed.
return;
}
isClosing = true;
try {
if(!compactionManager.stopCompactionThread(true))
setIOErrorFlag();
} catch (IOException e) {
logger.error("Error while stopping compaction thread. Setting IOError flag", e);
setIOErrorFlag();
}
if (options.isCleanUpInMemoryIndexOnClose())
inMemoryIndex.close();
if (currentWriteFile != null) {
currentWriteFile.flushToDisk();
currentWriteFile.getIndexFile().flushToDisk();
currentWriteFile.close();
}
if (currentTombstoneFile != null) {
currentTombstoneFile.flushToDisk();
currentTombstoneFile.close();
}
for (HaloDBFile file : readFileMap.values()) {
file.close();
}
DBMetaData metaData = new DBMetaData(dbDirectory);
metaData.loadFromFileIfExists();
metaData.setOpen(false);
metaData.storeToFile();
dbDirectory.close();
if (dbLock != null) {
dbLock.close();
}
} finally {
writeLock.unlock();
}
} | #vulnerable code
void delete(byte[] key) throws IOException {
writeLock.lock();
try {
InMemoryIndexMetaData metaData = inMemoryIndex.get(key);
if (metaData != null) {
//TODO: implement a getAndRemove method in InMemoryIndex.
inMemoryIndex.remove(key);
TombstoneEntry entry =
new TombstoneEntry(key, getNextSequenceNumber(), -1, Versions.CURRENT_TOMBSTONE_FILE_VERSION);
currentTombstoneFile = rollOverTombstoneFile(entry, currentTombstoneFile);
currentTombstoneFile.write(entry);
markPreviousVersionAsStale(key, metaData);
}
} finally {
writeLock.unlock();
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
DBMetaData(String dbDirectory) {
this.dbDirectory = dbDirectory;
} | #vulnerable code
long getSequenceNumber() {
return sequenceNumber;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
CompactionManager(HaloDBInternal dbInternal) {
this.dbInternal = dbInternal;
this.compactionRateLimiter = RateLimiter.create(dbInternal.options.getCompactionJobRate());
this.compactionQueue = new LinkedBlockingQueue<>();
} | #vulnerable code
boolean stopCompactionThread() throws IOException {
isRunning = false;
if (compactionThread != null) {
try {
// We don't want to call interrupt on compaction thread as it
// may interrupt IO operations and leave files in an inconsistent state.
// instead we use -10101 as a stop signal.
compactionQueue.put(STOP_SIGNAL);
compactionThread.join();
if (currentWriteFile != null) {
currentWriteFile.flushToDisk();
currentWriteFile.getIndexFile().flushToDisk();
currentWriteFile.close();
}
} catch (InterruptedException e) {
logger.error("Error while waiting for compaction thread to stop", e);
return false;
}
}
return true;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void close() throws IOException {
writeLock.lock();
try {
if (isClosing) {
// instance already closed.
return;
}
isClosing = true;
try {
if(!compactionManager.stopCompactionThread(true))
setIOErrorFlag();
} catch (IOException e) {
logger.error("Error while stopping compaction thread. Setting IOError flag", e);
setIOErrorFlag();
}
if (options.isCleanUpInMemoryIndexOnClose())
inMemoryIndex.close();
if (currentWriteFile != null) {
currentWriteFile.flushToDisk();
currentWriteFile.getIndexFile().flushToDisk();
currentWriteFile.close();
}
if (currentTombstoneFile != null) {
currentTombstoneFile.flushToDisk();
currentTombstoneFile.close();
}
for (HaloDBFile file : readFileMap.values()) {
file.close();
}
DBMetaData metaData = new DBMetaData(dbDirectory);
metaData.loadFromFileIfExists();
metaData.setOpen(false);
metaData.storeToFile();
dbDirectory.close();
if (dbLock != null) {
dbLock.close();
}
} finally {
writeLock.unlock();
}
} | #vulnerable code
void mergeTombstoneFiles() throws IOException {
if (!options.isCleanUpTombstonesDuringOpen()) {
logger.info("CleanUpTombstonesDuringOpen is not enabled, returning");
return;
}
File[] tombStoneFiles = dbDirectory.listTombstoneFiles();
logger.info("About to merge {} tombstone files ...", tombStoneFiles.length);
TombstoneFile mergedTombstoneFile = null;
// Use compaction job rate as write rate limiter to avoid IO impact
final RateLimiter rateLimiter = RateLimiter.create(options.getCompactionJobRate());
for (File file : tombStoneFiles) {
TombstoneFile tombstoneFile = new TombstoneFile(file, options, dbDirectory);
if (currentTombstoneFile != null && tombstoneFile.getName().equals(currentTombstoneFile.getName())) {
continue; // not touch current tombstone file
}
tombstoneFile.open();
TombstoneFile.TombstoneFileIterator iterator = tombstoneFile.newIterator();
long count = 0;
while (iterator.hasNext()) {
TombstoneEntry entry = iterator.next();
rateLimiter.acquire(entry.size());
count++;
mergedTombstoneFile = rollOverTombstoneFile(entry, mergedTombstoneFile);
mergedTombstoneFile.write(entry);
}
if (count > 0) {
logger.debug("Merged {} tombstones from {} to {}",
count, tombstoneFile.getName(), mergedTombstoneFile.getName());
}
tombstoneFile.close();
tombstoneFile.delete();
}
logger.info("Tombstone files count, before merge:{}, after merge:{}",
tombStoneFiles.length, dbDirectory.listTombstoneFiles().length);
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testReOpenDBAfterMerge() throws IOException, InterruptedException {
String directory = "/tmp/HaloDBTestWithMerge/testReOpenDBAfterMerge";
HaloDBOptions options = new HaloDBOptions();
options.maxFileSize = recordsPerFile * recordSize;
options.mergeThresholdPerFile = 0.5;
options.isMergeDisabled = false;
HaloDB db = getTestDB(directory, options);
Record[] records = insertAndUpdateRecords(numberOfRecords, db);
TestUtils.waitForMergeToComplete(db);
db.close();
db = getTestDBWithoutDeletingFiles(directory, options);
for (Record r : records) {
byte[] actual = db.get(r.getKey());
Assert.assertEquals(actual, r.getValue());
}
} | #vulnerable code
@Test
public void testReOpenDBAfterMerge() throws IOException, InterruptedException {
String directory = "/tmp/HaloDBTestWithMerge/testReOpenDBAfterMerge";
HaloDBOptions options = new HaloDBOptions();
options.maxFileSize = recordsPerFile * recordSize;
options.mergeThresholdPerFile = 0.5;
options.isMergeDisabled = false;
options.mergeJobIntervalInSeconds = 2;
HaloDB db = getTestDB(directory, options);
Record[] records = insertAndUpdateRecords(numberOfRecords, db);
TestUtils.waitForMergeToComplete(db);
db.close();
db = getTestDBWithoutDeletingFiles(directory, options);
for (Record r : records) {
byte[] actual = db.get(r.getKey());
Assert.assertEquals(actual, r.getValue());
}
}
#location 19
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testRepairDB() throws IOException {
String directory = Paths.get("tmp", "DBRepairTest", "testRepairDB").toString();
HaloDBOptions options = new HaloDBOptions();
options.maxFileSize = 1024 * 1024;
HaloDB db = getTestDB(directory, options);
int noOfRecords = 5 * 1024 + 512; // 5 files with 1024 records and 1 with 512 records.
List<Record> records = TestUtils.insertRandomRecordsOfSize(db, noOfRecords, 1024-Record.Header.HEADER_SIZE);
File latestDataFile = TestUtils.getLatestDataFile(directory);
db.close();
// trick the db to think that there was an unclean shutdown.
DBMetaData dbMetaData = new DBMetaData(directory);
dbMetaData.setOpen(true);
dbMetaData.storeToFile();
db = getTestDBWithoutDeletingFiles(directory, options);
// latest file should have been repaired and deleted.
Assert.assertFalse(latestDataFile.exists());
Assert.assertEquals(db.size(), noOfRecords);
for (Record r : records) {
Assert.assertEquals(db.get(r.getKey()), r.getValue());
}
} | #vulnerable code
@Test
public void testRepairDB() throws IOException {
String directory = Paths.get("tmp", "DBRepairTest", "testRepairDB").toString();
HaloDBOptions options = new HaloDBOptions();
options.maxFileSize = 1024 * 1024;
HaloDB db = getTestDB(directory, options);
int noOfRecords = 5 * 1024 + 512;
List<Record> records = TestUtils.insertRandomRecordsOfSize(db, noOfRecords, 1024-Record.Header.HEADER_SIZE);
File latestDataFile = TestUtils.getLatestDataFile(directory);
db.close();
// trick the db to think that there was an unclean shutdown.
DBMetaData dbMetaData = new DBMetaData(directory);
dbMetaData.setOpen(true);
dbMetaData.storeToFile();
db = getTestDBWithoutDeletingFiles(directory, options);
// latest file should have been repaired and deleted.
Assert.assertFalse(latestDataFile.exists());
Assert.assertEquals(db.size(), noOfRecords);
for (Record r : records) {
Assert.assertEquals(db.get(r.getKey()), r.getValue());
}
}
#location 22
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
long getWriteOffset() {
return writeOffset;
} | #vulnerable code
RecordMetaDataForCache writeRecord(Record record) throws IOException {
long start = System.nanoTime();
writeToChannel(record.serialize(), writeChannel);
int recordSize = record.getRecordSize();
long recordOffset = writeOffset;
writeOffset += recordSize;
IndexFileEntry indexFileEntry = new IndexFileEntry(record.getKey(), recordSize, recordOffset, record.getSequenceNumber(), record.getFlags());
indexFile.write(indexFileEntry);
HaloDB.recordWriteLatency(System.nanoTime() - start);
return new RecordMetaDataForCache(fileId, recordOffset, recordSize, record.getSequenceNumber());
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
Parser(Parser p, String text) {
this.logger = p.logger;
this.properties = p.properties;
this.infoMap = p.infoMap;
this.tokens = new TokenIndexer(infoMap, new Tokenizer(text).tokenize());
this.lineSeparator = p.lineSeparator;
} | #vulnerable code
String translate(String text) {
int namespace = text.lastIndexOf("::");
if (namespace >= 0) {
Info info2 = infoMap.getFirst(text.substring(0, namespace));
text = text.substring(namespace + 2);
if (info2.pointerTypes != null) {
text = info2.pointerTypes[0] + "." + text;
}
}
return text;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public BytePointer putString(String s) {
byte[] bytes = s.getBytes();
return put(bytes).put(bytes.length, (byte)0);
} | #vulnerable code
public BytePointer putString(String s) {
byte[] bytes = s.getBytes();
//capacity(bytes.length+1);
asBuffer().put(bytes).put((byte)0);
return this;
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean generate(Class<?> ... classes) throws FileNotFoundException {
// first pass using a null writer to fill up the LinkedListRegister objects
out = new PrintWriter(new Writer() {
@Override public void close() { }
@Override public void flush() { }
@Override public void write(char[] cbuf, int off, int len) { }
});
functionDefinitions = new LinkedListRegister<String>();
functionPointers = new LinkedListRegister<String>();
deallocators = new LinkedListRegister<Class>();
arrayDeallocators = new LinkedListRegister<Class>();
jclasses = new LinkedListRegister<Class>();
jclassesInit = new LinkedListRegister<Class>();
members = new HashMap<Class,LinkedList<String>>();
mayThrowExceptions = false;
usesAdapters = false;
if (doClasses(true, true, classes)) {
// second pass with the real writer
out = writer != null ? writer : new PrintWriter(file);
doClasses(mayThrowExceptions, usesAdapters, classes);
return true;
}
return false;
} | #vulnerable code
public boolean generate(Class<?> ... classes) throws FileNotFoundException {
// first pass using a null writer to fill up the LinkedListRegister objects
out = new PrintWriter(new Writer() {
@Override public void close() { }
@Override public void flush() { }
@Override public void write(char[] cbuf, int off, int len) { }
});
functionDefinitions = new LinkedListRegister<String>();
functionPointers = new LinkedListRegister<String>();
deallocators = new LinkedListRegister<Class>();
arrayDeallocators = new LinkedListRegister<Class>();
jclasses = new LinkedListRegister<Class>();
jclassesInit = new LinkedListRegister<Class>();
members = new HashMap<Class,LinkedList<String>>();
mayThrowExceptions = false;
if (doClasses(true, classes)) {
// second pass with the real writer
out = writer != null ? writer : new PrintWriter(file);
doClasses(mayThrowExceptions, classes);
return true;
}
return false;
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws Exception {
Main main = new Main();
for (int i = 0; i < args.length; i++) {
if ("-help".equals(args[i]) || "--help".equals(args[i])) {
printHelp();
System.exit(0);
} else if ("-classpath".equals(args[i]) || "-cp".equals(args[i]) || "-lib".equals(args[i])) {
main.classPaths(args[++i]);
} else if ("-d".equals(args[i])) {
main.outputDirectory(args[++i]);
} else if ("-o".equals(args[i])) {
main.outputName(args[++i]);
} else if ("-cpp".equals(args[i]) || "-nocompile".equals(args[i])) {
main.compile(false);
} else if ("-jarprefix".equals(args[i])) {
main.jarPrefix(args[++i]);
} else if ("-properties".equals(args[i])) {
main.properties(args[++i]);
} else if ("-propertyfile".equals(args[i])) {
main.propertyFile(args[++i]);
} else if (args[i].startsWith("-D")) {
main.property(args[i]);
} else if (args[i].startsWith("-")) {
System.err.println("Error: Invalid option \"" + args[i] + "\"");
printHelp();
System.exit(1);
} else {
main.classesOrPackages(args[i]);
}
}
main.build();
} | #vulnerable code
public static void main(String[] args) throws Exception {
Main main = new Main();
for (int i = 0; i < args.length; i++) {
if ("-help".equals(args[i]) || "--help".equals(args[i])) {
printHelp();
System.exit(0);
} else if ("-classpath".equals(args[i]) || "-cp".equals(args[i]) || "-lib".equals(args[i])) {
main.setClassPaths(args[++i]);
} else if ("-d".equals(args[i])) {
main.setOutputDirectory(args[++i]);
} else if ("-o".equals(args[i])) {
main.setOutputName(args[++i]);
} else if ("-cpp".equals(args[i]) || "-nocompile".equals(args[i])) {
main.setCompile(false);
} else if ("-jarprefix".equals(args[i])) {
main.setJarPrefix(args[++i]);
} else if ("-properties".equals(args[i])) {
main.setProperties(args[++i]);
} else if ("-propertyfile".equals(args[i])) {
main.setPropertyFile(args[++i]);
} else if (args[i].startsWith("-D")) {
main.setProperty(args[i]);
} else if (args[i].startsWith("-")) {
System.err.println("Error: Invalid option \"" + args[i] + "\"");
printHelp();
System.exit(1);
} else {
main.setClassesOrPackages(args[i]);
}
}
main.build();
}
#location 31
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
Parser(Parser p, String text) {
this.logger = p.logger;
this.properties = p.properties;
this.infoMap = p.infoMap;
this.tokens = new TokenIndexer(infoMap, new Tokenizer(text).tokenize());
this.lineSeparator = p.lineSeparator;
} | #vulnerable code
void parse(File outputFile, Context context, String[] includePath, String ... includes) throws IOException, ParserException {
ArrayList<Token> tokenList = new ArrayList<Token>();
for (String include : includes) {
File file = null;
String filename = include;
if (filename.startsWith("<") && filename.endsWith(">")) {
filename = filename.substring(1, filename.length() - 1);
} else {
File f = new File(filename);
if (f.exists()) {
file = f;
}
}
if (file == null && includePath != null) {
for (String path : includePath) {
File f = new File(path, filename);
if (f.exists()) {
file = f;
break;
}
}
}
if (file == null) {
file = new File(filename);
}
Info info = infoMap.getFirst(file.getName());
if (info != null && info.skip) {
continue;
} else if (!file.exists()) {
throw new FileNotFoundException("Could not parse \"" + file + "\": File does not exist");
}
logger.info("Parsing " + file);
Token token = new Token();
token.type = Token.COMMENT;
token.value = "\n// Parsed from " + include + "\n\n";
tokenList.add(token);
Tokenizer tokenizer = new Tokenizer(file);
while (!(token = tokenizer.nextToken()).isEmpty()) {
if (token.type == -1) {
token.type = Token.COMMENT;
}
tokenList.add(token);
}
if (lineSeparator == null) {
lineSeparator = tokenizer.lineSeparator;
}
tokenizer.close();
token = new Token();
token.type = Token.COMMENT;
token.spacing = "\n";
tokenList.add(token);
}
tokens = new TokenIndexer(infoMap, tokenList.toArray(new Token[tokenList.size()]));
final String newline = lineSeparator != null ? lineSeparator : "\n";
Writer out = outputFile != null ? new FileWriter(outputFile) {
@Override public Writer append(CharSequence text) throws IOException {
return super.append(((String)text).replace("\n", newline).replace("\\u", "\\u005Cu"));
}} : new Writer() {
@Override public void write(char[] cbuf, int off, int len) { }
@Override public void flush() { }
@Override public void close() { }
};
LinkedList<Info> infoList = leafInfoMap.get(null);
for (Info info : infoList) {
if (info.javaText != null && !info.javaText.startsWith("import")) {
out.append(info.javaText + "\n");
}
}
out.append(" static { Loader.load(); }\n");
DeclarationList declList = new DeclarationList();
containers(context, declList);
declarations(context, declList);
for (Declaration d : declList) {
out.append(d.text);
}
out.append("\n}\n").close();
}
#location 78
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean generate(Class<?> ... classes) throws FileNotFoundException {
// first pass using a null writer to fill up the LinkedListRegister objects
out = new PrintWriter(new Writer() {
@Override public void close() { }
@Override public void flush() { }
@Override public void write(char[] cbuf, int off, int len) { }
});
functionDefinitions = new LinkedListRegister<String>();
functionPointers = new LinkedListRegister<String>();
deallocators = new LinkedListRegister<Class>();
arrayDeallocators = new LinkedListRegister<Class>();
jclasses = new LinkedListRegister<Class>();
jclassesInit = new LinkedListRegister<Class>();
members = new HashMap<Class,LinkedList<String>>();
mayThrowExceptions = false;
if (doClasses(true, classes)) {
// second pass with the real writer
out = writer != null ? writer : new PrintWriter(file);
doClasses(mayThrowExceptions, classes);
return true;
}
return false;
} | #vulnerable code
public boolean generate(Class<?> ... classes) throws FileNotFoundException {
// first pass using a null writer to fill up the LinkedListRegister objects
out = new PrintWriter(new Writer() {
@Override public void close() { }
@Override public void flush() { }
@Override public void write(char[] cbuf, int off, int len) { }
});
functionDefinitions = new LinkedListRegister<String>();
functionPointers = new LinkedListRegister<String>();
deallocators = new LinkedListRegister<Class>();
arrayDeallocators = new LinkedListRegister<Class>();
jclasses = new LinkedListRegister<Class>();
jclassesInit = new LinkedListRegister<Class>();
members = new HashMap<Class,LinkedList<String>>();
if (doClasses(classes)) {
// second pass with the real writer
out = writer != null ? writer : new PrintWriter(file);
doClasses(classes);
return true;
}
return false;
}
#location 17
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
Parser(Parser p, String text) {
this.logger = p.logger;
this.properties = p.properties;
this.infoMap = p.infoMap;
this.tokens = new TokenIndexer(infoMap, new Tokenizer(text).tokenize());
this.lineSeparator = p.lineSeparator;
} | #vulnerable code
void parse(File outputFile, Context context, String[] includePath, String ... includes) throws IOException, ParserException {
ArrayList<Token> tokenList = new ArrayList<Token>();
for (String include : includes) {
File file = null;
String filename = include;
if (filename.startsWith("<") && filename.endsWith(">")) {
filename = filename.substring(1, filename.length() - 1);
} else {
File f = new File(filename);
if (f.exists()) {
file = f;
}
}
if (file == null && includePath != null) {
for (String path : includePath) {
File f = new File(path, filename);
if (f.exists()) {
file = f;
break;
}
}
}
if (file == null) {
file = new File(filename);
}
Info info = infoMap.getFirst(file.getName());
if (info != null && info.skip) {
continue;
} else if (!file.exists()) {
throw new FileNotFoundException("Could not parse \"" + file + "\": File does not exist");
}
logger.info("Parsing " + file);
Token token = new Token();
token.type = Token.COMMENT;
token.value = "\n// Parsed from " + include + "\n\n";
tokenList.add(token);
Tokenizer tokenizer = new Tokenizer(file);
while (!(token = tokenizer.nextToken()).isEmpty()) {
if (token.type == -1) {
token.type = Token.COMMENT;
}
tokenList.add(token);
}
if (lineSeparator == null) {
lineSeparator = tokenizer.lineSeparator;
}
tokenizer.close();
token = new Token();
token.type = Token.COMMENT;
token.spacing = "\n";
tokenList.add(token);
}
tokens = new TokenIndexer(infoMap, tokenList.toArray(new Token[tokenList.size()]));
final String newline = lineSeparator != null ? lineSeparator : "\n";
Writer out = outputFile != null ? new FileWriter(outputFile) {
@Override public Writer append(CharSequence text) throws IOException {
return super.append(((String)text).replace("\n", newline).replace("\\u", "\\u005Cu"));
}} : new Writer() {
@Override public void write(char[] cbuf, int off, int len) { }
@Override public void flush() { }
@Override public void close() { }
};
LinkedList<Info> infoList = leafInfoMap.get(null);
for (Info info : infoList) {
if (info.javaText != null && !info.javaText.startsWith("import")) {
out.append(info.javaText + "\n");
}
}
out.append(" static { Loader.load(); }\n");
DeclarationList declList = new DeclarationList();
containers(context, declList);
declarations(context, declList);
for (Declaration d : declList) {
out.append(d.text);
}
out.append("\n}\n").close();
}
#location 78
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String load(Class cls, Properties properties, boolean pathsFirst) {
if (!isLoadLibraries() || cls == null) {
return null;
}
// Find the top enclosing class, to match the library filename
cls = getEnclosingClass(cls);
ClassProperties p = loadProperties(cls, properties, true);
// Force initialization of all the target classes in case they need it
List<String> targets = p.get("target");
if (targets.isEmpty()) {
if (p.getInheritedClasses() != null) {
for (Class c : p.getInheritedClasses()) {
targets.add(c.getName());
}
}
targets.add(cls.getName());
}
for (String s : targets) {
try {
if (logger.isDebugEnabled()) {
logger.debug("Loading class " + s);
}
Class.forName(s, true, cls.getClassLoader());
} catch (ClassNotFoundException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to load class " + s + ": " + ex);
}
Error e = new NoClassDefFoundError(ex.toString());
e.initCause(ex);
throw e;
}
}
String cacheDir = null;
try {
cacheDir = getCacheDir().getCanonicalPath();
} catch (IOException e) {
// no cache dir, no worries
}
// Preload native libraries desired by our class
List<String> preloads = new ArrayList<String>();
preloads.addAll(p.get("platform.preload"));
preloads.addAll(p.get("platform.link"));
UnsatisfiedLinkError preloadError = null;
for (String preload : preloads) {
try {
URL[] urls = findLibrary(cls, p, preload, pathsFirst);
String filename = loadLibrary(urls, preload);
if (cacheDir != null && filename != null && filename.startsWith(cacheDir)) {
createLibraryLink(filename, p, preload);
}
} catch (UnsatisfiedLinkError e) {
preloadError = e;
}
}
try {
String library = p.getProperty("platform.library");
URL[] urls = findLibrary(cls, p, library, pathsFirst);
String filename = loadLibrary(urls, library);
if (cacheDir != null && filename != null && filename.startsWith(cacheDir)) {
createLibraryLink(filename, p, library);
}
return filename;
} catch (UnsatisfiedLinkError e) {
if (preloadError != null && e.getCause() == null) {
e.initCause(preloadError);
}
throw e;
}
} | #vulnerable code
public static String load(Class cls, Properties properties, boolean pathsFirst) {
if (!isLoadLibraries() || cls == null) {
return null;
}
// Find the top enclosing class, to match the library filename
cls = getEnclosingClass(cls);
ClassProperties p = loadProperties(cls, properties, true);
// Force initialization of all the target classes in case they need it
List<String> targets = p.get("target");
if (targets.isEmpty()) {
if (p.getInheritedClasses() != null) {
for (Class c : p.getInheritedClasses()) {
targets.add(c.getName());
}
}
targets.add(cls.getName());
}
for (String s : targets) {
try {
if (logger.isDebugEnabled()) {
logger.debug("Loading class " + s);
}
Class.forName(s, true, cls.getClassLoader());
} catch (ClassNotFoundException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to load class " + s + ": " + ex);
}
Error e = new NoClassDefFoundError(ex.toString());
e.initCause(ex);
throw e;
}
}
String cacheDir = null;
try {
cacheDir = getCacheDir().getCanonicalPath();
} catch (IOException e) {
// no cache dir, no worries
}
// Preload native libraries desired by our class
List<String> preloads = new ArrayList<String>();
preloads.addAll(p.get("platform.preload"));
preloads.addAll(p.get("platform.link"));
UnsatisfiedLinkError preloadError = null;
for (String preload : preloads) {
try {
URL[] urls = findLibrary(cls, p, preload, pathsFirst);
String filename = loadLibrary(urls, preload);
if (cacheDir != null && filename.startsWith(cacheDir)) {
createLibraryLink(filename, p, preload);
}
} catch (UnsatisfiedLinkError e) {
preloadError = e;
}
}
try {
String library = p.getProperty("platform.library");
URL[] urls = findLibrary(cls, p, library, pathsFirst);
String filename = loadLibrary(urls, library);
if (cacheDir != null && filename.startsWith(cacheDir)) {
createLibraryLink(filename, p, library);
}
return filename;
} catch (UnsatisfiedLinkError e) {
if (preloadError != null && e.getCause() == null) {
e.initCause(preloadError);
}
throw e;
}
}
#location 52
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void init(long allocatedAddress, int allocatedCapacity, long ownerAddress, long deallocatorAddress) {
address = allocatedAddress;
position = 0;
limit = allocatedCapacity;
capacity = allocatedCapacity;
deallocator(new NativeDeallocator(this, ownerAddress, deallocatorAddress));
} | #vulnerable code
void init(long allocatedAddress, int allocatedCapacity, long deallocatorAddress) {
address = allocatedAddress;
position = 0;
limit = allocatedCapacity;
capacity = allocatedCapacity;
deallocator(new NativeDeallocator(this, deallocatorAddress));
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean generate(String sourceFilename, String headerFilename, String loadSuffix,
String baseLoadSuffix, String classPath, Class<?> ... classes) throws IOException {
try {
// first pass using a null writer to fill up the IndexedSet objects
out = new PrintWriter(new Writer() {
@Override public void write(char[] cbuf, int off, int len) { }
@Override public void flush() { }
@Override public void close() { }
});
out2 = null;
callbacks = new IndexedSet<String>();
functions = new IndexedSet<Class>();
deallocators = new IndexedSet<Class>();
arrayDeallocators = new IndexedSet<Class>();
jclasses = new IndexedSet<Class>();
members = new HashMap<Class,Set<String>>();
virtualFunctions = new HashMap<Class,Set<String>>();
virtualMembers = new HashMap<Class,Set<String>>();
annotationCache = new HashMap<Method,MethodInformation>();
mayThrowExceptions = false;
usesAdapters = false;
passesStrings = false;
if (baseLoadSuffix == null || baseLoadSuffix.isEmpty()) {
for (Class<?> cls : baseClasses) {
jclasses.index(cls);
}
}
if (classes(true, true, true, true, loadSuffix, baseLoadSuffix, classPath, classes)) {
// second pass with a real writer
File sourceFile = new File(sourceFilename);
File sourceDir = sourceFile.getParentFile();
if (sourceDir != null) {
sourceDir.mkdirs();
}
out = encoding != null ? new PrintWriter(sourceFile, encoding) : new PrintWriter(sourceFile);
if (headerFilename != null) {
logger.info("Generating " + headerFilename);
File headerFile = new File(headerFilename);
File headerDir = headerFile.getParentFile();
if (headerDir != null) {
headerDir.mkdirs();
}
out2 = encoding != null ? new PrintWriter(headerFile, encoding) : new PrintWriter(headerFile);
}
return classes(mayThrowExceptions, usesAdapters, passesStrings, accessesEnums, loadSuffix, baseLoadSuffix, classPath, classes);
} else {
return false;
}
} finally {
if (out != null) {
out.close();
}
if (out2 != null) {
out2.close();
}
}
} | #vulnerable code
public boolean generate(String sourceFilename, String headerFilename, String loadSuffix,
String baseLoadSuffix, String classPath, Class<?> ... classes) throws IOException {
try {
// first pass using a null writer to fill up the IndexedSet objects
out = new PrintWriter(new Writer() {
@Override public void write(char[] cbuf, int off, int len) { }
@Override public void flush() { }
@Override public void close() { }
});
out2 = null;
callbacks = new IndexedSet<String>();
functions = new IndexedSet<Class>();
deallocators = new IndexedSet<Class>();
arrayDeallocators = new IndexedSet<Class>();
jclasses = new IndexedSet<Class>();
members = new HashMap<Class,Set<String>>();
virtualFunctions = new HashMap<Class,Set<String>>();
virtualMembers = new HashMap<Class,Set<String>>();
annotationCache = new HashMap<Method,MethodInformation>();
mayThrowExceptions = false;
usesAdapters = false;
passesStrings = false;
if (baseLoadSuffix == null || baseLoadSuffix.isEmpty()) {
for (Class<?> cls : baseClasses) {
jclasses.index(cls);
}
}
if (classes(true, true, true, loadSuffix, baseLoadSuffix, classPath, classes)) {
// second pass with a real writer
File sourceFile = new File(sourceFilename);
File sourceDir = sourceFile.getParentFile();
if (sourceDir != null) {
sourceDir.mkdirs();
}
out = encoding != null ? new PrintWriter(sourceFile, encoding) : new PrintWriter(sourceFile);
if (headerFilename != null) {
logger.info("Generating " + headerFilename);
File headerFile = new File(headerFilename);
File headerDir = headerFile.getParentFile();
if (headerDir != null) {
headerDir.mkdirs();
}
out2 = encoding != null ? new PrintWriter(headerFile, encoding) : new PrintWriter(headerFile);
}
return classes(mayThrowExceptions, usesAdapters, passesStrings, loadSuffix, baseLoadSuffix, classPath, classes);
} else {
return false;
}
} finally {
if (out != null) {
out.close();
}
if (out2 != null) {
out2.close();
}
}
}
#location 35
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
TokenIndexer(InfoMap infoMap, Token[] array, boolean isCFile) {
this.infoMap = infoMap;
this.array = array;
this.isCFile = isCFile;
} | #vulnerable code
Token[] expand(Token[] array, int index) {
if (index < array.length && infoMap.containsKey(array[index].value)) {
// if we hit a token whose info.cppText starts with #define (a macro), expand it
int startIndex = index;
Info info = infoMap.getFirst(array[index].value);
if (info != null && info.cppText != null) {
try {
Tokenizer tokenizer = new Tokenizer(info.cppText, array[index].file, array[index].lineNumber);
if (!tokenizer.nextToken().match('#')
|| !tokenizer.nextToken().match(Token.DEFINE)
|| !tokenizer.nextToken().match(info.cppNames[0])) {
return array;
}
// copy the array of tokens up to this point
List<Token> tokens = new ArrayList<Token>();
for (int i = 0; i < index; i++) {
tokens.add(array[i]);
}
List<String> params = new ArrayList<String>();
List<Token>[] args = null;
Token token = tokenizer.nextToken();
if (info.cppNames[0].equals("__COUNTER__")) {
token.value = Integer.toString(counter++);
}
// pick up the parameters and arguments of the macro if it has any
String name = array[index].value;
if (token.match('(')) {
token = tokenizer.nextToken();
while (!token.isEmpty()) {
if (token.match(Token.IDENTIFIER)) {
params.add(token.value);
} else if (token.match(')')) {
token = tokenizer.nextToken();
break;
}
token = tokenizer.nextToken();
}
index++;
if (params.size() > 0 && (index >= array.length || !array[index].match('('))) {
return array;
}
name += array[index].spacing + array[index];
args = new List[params.size()];
int count = 0, count2 = 0;
for (index++; index < array.length; index++) {
Token token2 = array[index];
name += token2.spacing + token2;
if (count2 == 0 && token2.match(')')) {
break;
} else if (count2 == 0 && token2.match(',')) {
count++;
continue;
} else if (token2.match('(','[','{')) {
count2++;
} else if (token2.match(')',']','}')) {
count2--;
}
if (count < args.length) {
if (args[count] == null) {
args[count] = new ArrayList<Token>();
}
args[count].add(token2);
}
}
// expand the arguments of the macros as well
for (int i = 0; i < args.length; i++) {
if (infoMap.containsKey(args[i].get(0).value)) {
args[i] = Arrays.asList(expand(args[i].toArray(new Token[args[i].size()]), 0));
}
}
}
int startToken = tokens.size();
// expand the token in question, unless we should skip it
info = infoMap.getFirst(name);
while ((info == null || !info.skip) && !token.isEmpty()) {
boolean foundArg = false;
for (int i = 0; i < params.size(); i++) {
if (params.get(i).equals(token.value)) {
String s = token.spacing;
for (Token arg : args[i]) {
// clone tokens here to avoid potential problems with concatenation below
Token t = new Token(arg);
if (s != null) {
t.spacing += s;
}
tokens.add(t);
s = null;
}
foundArg = true;
break;
}
}
if (!foundArg) {
if (token.type == -1) {
token.type = Token.COMMENT;
}
tokens.add(token);
}
token = tokenizer.nextToken();
}
// concatenate tokens as required
for (int i = startToken; i < tokens.size(); i++) {
if (tokens.get(i).match("##") && i > 0 && i + 1 < tokens.size()) {
tokens.get(i - 1).value += tokens.get(i + 1).value;
tokens.remove(i);
tokens.remove(i);
i--;
}
}
// copy the rest of the tokens from this point on
for (index++; index < array.length; index++) {
tokens.add(array[index]);
}
if ((info == null || !info.skip) && startToken < tokens.size()) {
tokens.get(startToken).spacing = array[startIndex].spacing;
}
array = tokens.toArray(new Token[tokens.size()]);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
return array;
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static File cacheResource(URL resourceURL, String target) throws IOException {
// Find appropriate subdirectory in cache for the resource ...
File urlFile = new File(resourceURL.getPath());
String name = urlFile.getName();
long size, timestamp;
File cacheSubdir = getCacheDir().getCanonicalFile();
URLConnection urlConnection = resourceURL.openConnection();
if (urlConnection instanceof JarURLConnection) {
JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile();
JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry();
File jarFileFile = new File(jarFile.getName());
File jarEntryFile = new File(jarEntry.getName());
size = jarEntry.getSize();
timestamp = jarEntry.getTime();
cacheSubdir = new File(cacheSubdir, jarFileFile.getName() + File.separator + jarEntryFile.getParent());
} else {
size = urlFile.length();
timestamp = urlFile.lastModified();
cacheSubdir = new File(cacheSubdir, name);
}
if (resourceURL.getRef() != null) {
// ... get the URL fragment to let users rename library files ...
name = resourceURL.getRef();
}
// ... then check if it has not already been extracted, and if not ...
File file = new File(cacheSubdir, name);
if (target != null && target.length() > 0) {
// ... create symbolic link to already extracted library or ...
Path path = file.toPath(), targetPath = Paths.get(target);
try {
if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath))
&& targetPath.isAbsolute() && !targetPath.equals(path)) {
if (logger.isDebugEnabled()) {
logger.debug("Creating symbolic link " + path);
}
file.delete();
Files.createSymbolicLink(path, targetPath);
}
} catch (IOException | UnsupportedOperationException e) {
// ... (probably an unsupported operation on Windows, but DLLs never need links) ...
if (logger.isDebugEnabled()) {
logger.debug("Failed to create symbolic link " + path + ": " + e);
}
return null;
}
} else if (!file.exists() || file.length() != size || file.lastModified() != timestamp
|| !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) {
// ... then extract it from our resources ...
if (logger.isDebugEnabled()) {
logger.debug("Extracting " + resourceURL);
}
file.delete();
extractResource(resourceURL, file, null, null);
file.setLastModified(timestamp);
} else while (System.currentTimeMillis() - file.lastModified() >= 0
&& System.currentTimeMillis() - file.lastModified() < 1000) {
// ... else wait until the file is at least 1 second old ...
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
// ... and reset interrupt to be nice.
Thread.currentThread().interrupt();
}
}
return file;
} | #vulnerable code
public static File cacheResource(URL resourceURL, String target) throws IOException {
// Find appropriate subdirectory in cache for the resource ...
File urlFile = new File(resourceURL.getPath());
String name = urlFile.getName();
long size, timestamp;
File cacheSubdir = getCacheDir().getCanonicalFile();
URLConnection urlConnection = resourceURL.openConnection();
if (urlConnection instanceof JarURLConnection) {
JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile();
JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry();
File jarFileFile = new File(jarFile.getName());
File jarEntryFile = new File(jarEntry.getName());
size = jarEntry.getSize();
timestamp = jarEntry.getTime();
cacheSubdir = new File(cacheSubdir, jarFileFile.getName() + File.separator + jarEntryFile.getParent());
} else {
size = urlFile.length();
timestamp = urlFile.lastModified();
cacheSubdir = new File(cacheSubdir, name);
}
if (resourceURL.getRef() != null) {
// ... get the URL fragment to let users rename library files ...
name = resourceURL.getRef();
}
// ... then check if it has not already been extracted, and if not ...
File file = new File(cacheSubdir, name);
if (target != null && target.length() > 0) {
// ... create symbolic link to already extracted library or ...
try {
if (logger.isDebugEnabled()) {
logger.debug("Creating symbolic link to " + target);
}
Path path = file.toPath(), targetPath = Paths.get(target);
if ((!file.exists() || !Files.isSymbolicLink(path))
&& targetPath.isAbsolute() && !targetPath.equals(path)) {
file.delete();
Files.createSymbolicLink(path, targetPath);
}
} catch (IOException e) {
// ... (probably an unsupported operation on Windows, but DLLs never need links) ...
return null;
}
} else if (!file.exists() || file.length() != size || file.lastModified() != timestamp
|| !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) {
// ... then extract it from our resources ...
if (logger.isDebugEnabled()) {
logger.debug("Extracting " + resourceURL);
}
file.delete();
extractResource(resourceURL, file, null, null);
file.setLastModified(timestamp);
} else while (System.currentTimeMillis() - file.lastModified() >= 0
&& System.currentTimeMillis() - file.lastModified() < 1000) {
// ... else wait until the file is at least 1 second old ...
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
// ... and reset interrupt to be nice.
Thread.currentThread().interrupt();
}
}
return file;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public File parse(File outputDirectory, String[] classPath, Class cls) throws IOException, Exception {
Loader.ClassProperties allProperties = Loader.loadProperties(cls, properties, true);
Loader.ClassProperties clsProperties = Loader.loadProperties(cls, properties, false);
LinkedList<String> clsIncludes = new LinkedList<String>();
clsIncludes.addAll(clsProperties.get("platform.include"));
clsIncludes.addAll(clsProperties.get("platform.cinclude"));
LinkedList<String> allIncludes = new LinkedList<String>();
allIncludes.addAll(allProperties.get("platform.include"));
allIncludes.addAll(allProperties.get("platform.cinclude"));
LinkedList<File> allFiles = findHeaderFiles(allProperties, allIncludes);
LinkedList<File> clsFiles = findHeaderFiles(allProperties, clsIncludes);
LinkedList<String> allTargets = allProperties.get("target");
LinkedList<String> clsTargets = clsProperties.get("target");
LinkedList<String> clsHelpers = clsProperties.get("helper");
String target = clsTargets.getFirst(); // there can only be one
LinkedList<Class> allInherited = allProperties.getInheritedClasses();
infoMap = new Parser.InfoMap();
for (Class c : allInherited) {
try {
((InfoMapper)c.newInstance()).map(infoMap);
} catch (ClassCastException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
// fail silently as if the interface wasn't implemented
}
}
leafInfoMap = new Parser.InfoMap();
try {
((InfoMapper)cls.newInstance()).map(leafInfoMap);
} catch (ClassCastException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
// fail silently as if the interface wasn't implemented
}
infoMap.putAll(leafInfoMap);
String version = Generator.class.getPackage().getImplementationVersion();
if (version == null) {
version = "unknown";
}
String text = "// Targeted by JavaCPP version " + version + "\n\n";
int n = target.lastIndexOf('.');
if (n >= 0) {
text += "package " + target.substring(0, n) + ";\n\n";
}
LinkedList<Info> infoList = leafInfoMap.get(null);
for (Info info : infoList) {
if (info.javaText != null && info.javaText.startsWith("import")) {
text += info.javaText + "\n";
}
}
text += "import com.googlecode.javacpp.*;\n" +
"import com.googlecode.javacpp.annotation.*;\n" +
"import java.nio.*;\n\n";
for (String s : allTargets) {
if (!target.equals(s)) {
text += "import static " + s + ".*;\n";
}
}
if (allTargets.size() > 1) {
text += "\n";
}
text += "public class " + target.substring(n + 1) + " extends "
+ (clsHelpers.size() > 0 ? clsHelpers.getFirst() : cls.getCanonicalName()) + " {";
leafInfoMap.putFirst(new Info().javaText(text));
String targetPath = target.replace('.', File.separatorChar);
File targetFile = new File(outputDirectory, targetPath + ".java");
logger.info("Targeting " + targetFile);
Context context = new Context();
String[] includePath = classPath;
n = targetPath.lastIndexOf(File.separatorChar);
if (n >= 0) {
includePath = classPath.clone();
for (int i = 0; i < includePath.length; i++) {
includePath[i] += File.separator + targetPath.substring(0, n);
}
}
for (File f : allFiles) {
if (!clsFiles.contains(f)) {
parse(null, context, includePath, f);
}
}
parse(targetFile, context, includePath, clsFiles.toArray(new File[clsFiles.size()]));
return targetFile;
} | #vulnerable code
public File parse(File outputDirectory, String[] classPath, Class cls) throws IOException, Exception {
Loader.ClassProperties allProperties = Loader.loadProperties(cls, properties, true);
Loader.ClassProperties clsProperties = Loader.loadProperties(cls, properties, false);
LinkedList<File> allFiles = allProperties.getHeaderFiles();
LinkedList<File> clsFiles = clsProperties.getHeaderFiles();
LinkedList<String> allTargets = allProperties.get("target");
LinkedList<String> clsTargets = clsProperties.get("target");
LinkedList<String> clsHelpers = clsProperties.get("helper");
String target = clsTargets.getFirst(); // there can only be one
LinkedList<Class> allInherited = allProperties.getInheritedClasses();
infoMap = new Parser.InfoMap();
for (Class c : allInherited) {
try {
((InfoMapper)c.newInstance()).map(infoMap);
} catch (ClassCastException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
// fail silently as if the interface wasn't implemented
}
}
leafInfoMap = new Parser.InfoMap();
try {
((InfoMapper)cls.newInstance()).map(leafInfoMap);
} catch (ClassCastException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
// fail silently as if the interface wasn't implemented
}
infoMap.putAll(leafInfoMap);
String version = Generator.class.getPackage().getImplementationVersion();
if (version == null) {
version = "unknown";
}
String text = "// Targeted by JavaCPP version " + version + "\n\n";
int n = target.lastIndexOf('.');
if (n >= 0) {
text += "package " + target.substring(0, n) + ";\n\n";
}
LinkedList<Info> infoList = leafInfoMap.get(null);
for (Info info : infoList) {
if (info.javaText != null && info.javaText.startsWith("import")) {
text += info.javaText + "\n";
}
}
text += "import com.googlecode.javacpp.*;\n" +
"import com.googlecode.javacpp.annotation.*;\n" +
"import java.nio.*;\n\n";
for (String s : allTargets) {
if (!target.equals(s)) {
text += "import static " + s + ".*;\n";
}
}
if (allTargets.size() > 1) {
text += "\n";
}
text += "public class " + target.substring(n + 1) + " extends "
+ (clsHelpers.size() > 0 ? clsHelpers.getFirst() : cls.getCanonicalName()) + " {";
leafInfoMap.putFirst(new Info().javaText(text));
String targetPath = target.replace('.', File.separatorChar);
File targetFile = new File(outputDirectory, targetPath + ".java");
logger.info("Targeting " + targetFile);
Context context = new Context();
String[] includePath = classPath;
n = targetPath.lastIndexOf(File.separatorChar);
if (n >= 0) {
includePath = classPath.clone();
for (int i = 0; i < includePath.length; i++) {
includePath[i] += File.separator + targetPath.substring(0, n);
}
}
for (File f : allFiles) {
if (!clsFiles.contains(f)) {
parse(null, context, includePath, f);
}
}
parse(targetFile, context, includePath, clsFiles.toArray(new File[clsFiles.size()]));
return targetFile;
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static int offsetof(Class<? extends Pointer> type, String member) {
// Should we synchronize that?
HashMap<String,Integer> offsets = memberOffsets.get(type);
while (offsets == null && type.getSuperclass() != null) {
type = type.getSuperclass().asSubclass(Pointer.class);
offsets = memberOffsets.get(type);
}
return offsets.get(member);
} | #vulnerable code
public static int offsetof(Class<? extends Pointer> type, String member) {
// Should we synchronize that?
return memberOffsets.get(type).get(member);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static File extractResource(URL resourceURL, File directory,
String prefix, String suffix) throws IOException {
InputStream is = resourceURL != null ? resourceURL.openStream() : null;
OutputStream os = null;
if (is == null) {
return null;
}
File file = null;
boolean fileExisted = false;
try {
if (prefix == null && suffix == null) {
if (directory == null) {
directory = new File(System.getProperty("java.io.tmpdir"));
}
file = new File(directory, new File(resourceURL.getPath()).getName());
fileExisted = file.exists();
} else {
file = File.createTempFile(prefix, suffix, directory);
}
os = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
is.close();
os.close();
} catch (IOException e) {
if (file != null && !fileExisted) {
file.delete();
}
throw e;
} finally {
is.close();
if (os != null) {
os.close();
}
}
return file;
} | #vulnerable code
public static File extractResource(URL resourceURL, File directory,
String prefix, String suffix) throws IOException {
InputStream is = resourceURL != null ? resourceURL.openStream() : null;
if (is == null) {
return null;
}
File file = null;
boolean fileExisted = false;
try {
if (prefix == null && suffix == null) {
if (directory == null) {
directory = new File(System.getProperty("java.io.tmpdir"));
}
file = new File(directory, new File(resourceURL.getPath()).getName());
fileExisted = file.exists();
} else {
file = File.createTempFile(prefix, suffix, directory);
}
FileOutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
is.close();
os.close();
} catch (IOException e) {
if (file != null && !fileExisted) {
file.delete();
}
throw e;
}
return file;
}
#location 27
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ByteBuffer asByteBuffer() {
if (isNull()) {
return null;
}
if (limit > 0 && limit < position) {
throw new IllegalArgumentException("limit < position: (" + limit + " < " + position + ")");
}
int size = sizeof();
Pointer p = new Pointer();
p.address = address;
return p.position(size * position)
.limit(size * (limit <= 0 ? position + 1 : limit))
.asDirectBuffer().order(ByteOrder.nativeOrder());
} | #vulnerable code
public ByteBuffer asByteBuffer() {
if (isNull()) {
return null;
}
if (limit > 0 && limit < position) {
throw new IllegalArgumentException("limit < position: (" + limit + " < " + position + ")");
}
int valueSize = sizeof();
long arrayPosition = position;
long arrayLimit = limit;
position = valueSize * arrayPosition;
limit = valueSize * (arrayLimit <= 0 ? arrayPosition + 1 : arrayLimit);
ByteBuffer b = asDirectBuffer().order(ByteOrder.nativeOrder());
position = arrayPosition;
limit = arrayLimit;
return b;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static File cacheResource(URL resourceURL, String target) throws IOException {
// Find appropriate subdirectory in cache for the resource ...
File urlFile;
try {
urlFile = new File(new URI(resourceURL.toString().split("#")[0]));
} catch (IllegalArgumentException | URISyntaxException e) {
urlFile = new File(resourceURL.getPath());
}
String name = urlFile.getName();
boolean reference = false;
long size, timestamp;
File cacheDir = getCacheDir();
File cacheSubdir = cacheDir.getCanonicalFile();
String s = System.getProperty("org.bytedeco.javacpp.cachedir.nosubdir", "false").toLowerCase();
boolean noSubdir = s.equals("true") || s.equals("t") || s.equals("");
URLConnection urlConnection = resourceURL.openConnection();
if (urlConnection instanceof JarURLConnection) {
JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile();
JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry();
File jarFileFile = new File(jarFile.getName());
File jarEntryFile = new File(jarEntry.getName());
size = jarEntry.getSize();
timestamp = jarEntry.getTime();
if (!noSubdir) {
String subdirName = jarFileFile.getName();
String parentName = jarEntryFile.getParent();
if (parentName != null) {
subdirName = subdirName + File.separator + parentName;
}
cacheSubdir = new File(cacheSubdir, subdirName);
}
} else if (urlConnection instanceof HttpURLConnection) {
size = urlConnection.getContentLength();
timestamp = urlConnection.getLastModified();
if (!noSubdir) {
String path = resourceURL.getHost() + resourceURL.getPath();
cacheSubdir = new File(cacheSubdir, path.substring(0, path.lastIndexOf('/') + 1));
}
} else {
size = urlFile.length();
timestamp = urlFile.lastModified();
if (!noSubdir) {
cacheSubdir = new File(cacheSubdir, urlFile.getParentFile().getName());
}
}
if (resourceURL.getRef() != null) {
// ... get the URL fragment to let users rename library files ...
String newName = resourceURL.getRef();
// ... but create a symbolic link only if the name does not change ...
reference = newName.equals(name);
name = newName;
}
File file = new File(cacheSubdir, name);
File lockFile = new File(cacheDir, ".lock");
FileChannel lockChannel = null;
FileLock lock = null;
ReentrantLock threadLock = null;
if (target != null && target.length() > 0) {
// ... create symbolic link to already extracted library or ...
try {
Path path = file.toPath(), targetPath = Paths.get(target);
if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath))
&& targetPath.isAbsolute() && !targetPath.equals(path)) {
if (logger.isDebugEnabled()) {
logger.debug("Locking " + cacheDir + " to create symbolic link");
}
threadLock = new ReentrantLock();
threadLock.lock();
lockChannel = new FileOutputStream(lockFile).getChannel();
lock = lockChannel.lock();
if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath))
&& targetPath.isAbsolute() && !targetPath.equals(path)) {
if (logger.isDebugEnabled()) {
logger.debug("Creating symbolic link " + path + " to " + targetPath);
}
try {
file.getParentFile().mkdirs();
Files.createSymbolicLink(path, targetPath);
} catch (java.nio.file.FileAlreadyExistsException e) {
file.delete();
Files.createSymbolicLink(path, targetPath);
}
}
}
} catch (IOException | RuntimeException e) {
// ... (probably an unsupported operation on Windows, but DLLs never need links,
// or other (filesystem?) exception: for example,
// "sun.nio.fs.UnixException: No such file or directory" on File.toPath()) ...
if (logger.isDebugEnabled()) {
logger.debug("Failed to create symbolic link " + file + ": " + e);
}
return null;
} finally {
if (lock != null) {
lock.release();
}
if (lockChannel != null) {
lockChannel.close();
}
if (threadLock != null) {
threadLock.unlock();
}
}
} else {
if (urlFile.exists() && reference) {
// ... try to create a symbolic link to the existing file, if we can, ...
try {
Path path = file.toPath(), urlPath = urlFile.toPath();
if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath))
&& urlPath.isAbsolute() && !urlPath.equals(path)) {
if (logger.isDebugEnabled()) {
logger.debug("Locking " + cacheDir + " to create symbolic link");
}
threadLock = new ReentrantLock();
threadLock.lock();
lockChannel = new FileOutputStream(lockFile).getChannel();
lock = lockChannel.lock();
if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath))
&& urlPath.isAbsolute() && !urlPath.equals(path)) {
if (logger.isDebugEnabled()) {
logger.debug("Creating symbolic link " + path + " to " + urlPath);
}
try {
file.getParentFile().mkdirs();
Files.createSymbolicLink(path, urlPath);
} catch (java.nio.file.FileAlreadyExistsException e) {
file.delete();
Files.createSymbolicLink(path, urlPath);
}
}
}
return file;
} catch (IOException | RuntimeException e) {
// ... (let's try to copy the file instead, such as on Windows) ...
if (logger.isDebugEnabled()) {
logger.debug("Could not create symbolic link " + file + ": " + e);
}
} finally {
if (lock != null) {
lock.release();
}
if (lockChannel != null) {
lockChannel.close();
}
if (threadLock != null) {
threadLock.unlock();
}
}
}
// ... check if it has not already been extracted, and if not ...
if (!file.exists() || file.length() != size || file.lastModified() != timestamp
|| !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) {
// ... add lock to avoid two JVMs access cacheDir simultaneously and ...
try {
if (logger.isDebugEnabled()) {
logger.debug("Locking " + cacheDir + " before extracting");
}
threadLock = new ReentrantLock();
threadLock.lock();
lockChannel = new FileOutputStream(lockFile).getChannel();
lock = lockChannel.lock();
// ... check if other JVM has extracted it before this JVM get the lock ...
if (!file.exists() || file.length() != size || file.lastModified() != timestamp
|| !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) {
// ... extract it from our resources ...
if (logger.isDebugEnabled()) {
logger.debug("Extracting " + resourceURL);
}
file.delete();
extractResource(resourceURL, file, null, null);
file.setLastModified(timestamp);
}
} finally {
if (lock != null) {
lock.release();
}
if (lockChannel != null) {
lockChannel.close();
}
if (threadLock != null) {
threadLock.unlock();
}
}
}
}
return file;
} | #vulnerable code
public static File cacheResource(URL resourceURL, String target) throws IOException {
// Find appropriate subdirectory in cache for the resource ...
File urlFile;
try {
urlFile = new File(new URI(resourceURL.toString().split("#")[0]));
} catch (IllegalArgumentException | URISyntaxException e) {
urlFile = new File(resourceURL.getPath());
}
String name = urlFile.getName();
boolean reference = false;
long size, timestamp;
File cacheDir = getCacheDir();
File cacheSubdir = cacheDir.getCanonicalFile();
String s = System.getProperty("org.bytedeco.javacpp.cachedir.nosubdir", "false").toLowerCase();
boolean noSubdir = s.equals("true") || s.equals("t") || s.equals("");
URLConnection urlConnection = resourceURL.openConnection();
if (urlConnection instanceof JarURLConnection) {
JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile();
JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry();
File jarFileFile = new File(jarFile.getName());
File jarEntryFile = new File(jarEntry.getName());
size = jarEntry.getSize();
timestamp = jarEntry.getTime();
if (!noSubdir) {
String subdirName = jarFileFile.getName();
String parentName = jarEntryFile.getParent();
if (parentName != null) {
subdirName = subdirName + File.separator + parentName;
}
cacheSubdir = new File(cacheSubdir, subdirName);
}
} else {
size = urlFile.length();
timestamp = urlFile.lastModified();
if (!noSubdir) {
cacheSubdir = new File(cacheSubdir, urlFile.getParentFile().getName());
}
}
if (resourceURL.getRef() != null) {
// ... get the URL fragment to let users rename library files ...
String newName = resourceURL.getRef();
// ... but create a symbolic link only if the name does not change ...
reference = newName.equals(name);
name = newName;
}
File file = new File(cacheSubdir, name);
File lockFile = new File(cacheDir, ".lock");
FileChannel lockChannel = null;
FileLock lock = null;
ReentrantLock threadLock = null;
if (target != null && target.length() > 0) {
// ... create symbolic link to already extracted library or ...
try {
Path path = file.toPath(), targetPath = Paths.get(target);
if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath))
&& targetPath.isAbsolute() && !targetPath.equals(path)) {
if (logger.isDebugEnabled()) {
logger.debug("Locking " + cacheDir + " to create symbolic link");
}
threadLock = new ReentrantLock();
threadLock.lock();
lockChannel = new FileOutputStream(lockFile).getChannel();
lock = lockChannel.lock();
if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath))
&& targetPath.isAbsolute() && !targetPath.equals(path)) {
if (logger.isDebugEnabled()) {
logger.debug("Creating symbolic link " + path + " to " + targetPath);
}
try {
file.getParentFile().mkdirs();
Files.createSymbolicLink(path, targetPath);
} catch (java.nio.file.FileAlreadyExistsException e) {
file.delete();
Files.createSymbolicLink(path, targetPath);
}
}
}
} catch (IOException | RuntimeException e) {
// ... (probably an unsupported operation on Windows, but DLLs never need links,
// or other (filesystem?) exception: for example,
// "sun.nio.fs.UnixException: No such file or directory" on File.toPath()) ...
if (logger.isDebugEnabled()) {
logger.debug("Failed to create symbolic link " + file + ": " + e);
}
return null;
} finally {
if (lock != null) {
lock.release();
}
if (lockChannel != null) {
lockChannel.close();
}
if (threadLock != null) {
threadLock.unlock();
}
}
} else {
if (urlFile.exists() && reference) {
// ... try to create a symbolic link to the existing file, if we can, ...
try {
Path path = file.toPath(), urlPath = urlFile.toPath();
if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath))
&& urlPath.isAbsolute() && !urlPath.equals(path)) {
if (logger.isDebugEnabled()) {
logger.debug("Locking " + cacheDir + " to create symbolic link");
}
threadLock = new ReentrantLock();
threadLock.lock();
lockChannel = new FileOutputStream(lockFile).getChannel();
lock = lockChannel.lock();
if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath))
&& urlPath.isAbsolute() && !urlPath.equals(path)) {
if (logger.isDebugEnabled()) {
logger.debug("Creating symbolic link " + path + " to " + urlPath);
}
try {
file.getParentFile().mkdirs();
Files.createSymbolicLink(path, urlPath);
} catch (java.nio.file.FileAlreadyExistsException e) {
file.delete();
Files.createSymbolicLink(path, urlPath);
}
}
}
return file;
} catch (IOException | RuntimeException e) {
// ... (let's try to copy the file instead, such as on Windows) ...
if (logger.isDebugEnabled()) {
logger.debug("Could not create symbolic link " + file + ": " + e);
}
} finally {
if (lock != null) {
lock.release();
}
if (lockChannel != null) {
lockChannel.close();
}
if (threadLock != null) {
threadLock.unlock();
}
}
}
// ... check if it has not already been extracted, and if not ...
if (!file.exists() || file.length() != size || file.lastModified() != timestamp
|| !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) {
// ... add lock to avoid two JVMs access cacheDir simultaneously and ...
try {
if (logger.isDebugEnabled()) {
logger.debug("Locking " + cacheDir + " before extracting");
}
threadLock = new ReentrantLock();
threadLock.lock();
lockChannel = new FileOutputStream(lockFile).getChannel();
lock = lockChannel.lock();
// ... check if other JVM has extracted it before this JVM get the lock ...
if (!file.exists() || file.length() != size || file.lastModified() != timestamp
|| !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) {
// ... extract it from our resources ...
if (logger.isDebugEnabled()) {
logger.debug("Extracting " + resourceURL);
}
file.delete();
extractResource(resourceURL, file, null, null);
file.setLastModified(timestamp);
}
} finally {
if (lock != null) {
lock.release();
}
if (lockChannel != null) {
lockChannel.close();
}
if (threadLock != null) {
threadLock.unlock();
}
}
}
}
return file;
}
#location 33
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String load(Class cls) {
if (!loadLibraries || cls == null) {
return null;
}
// Find the top enclosing class, to match the library filename
Properties p = (Properties)getProperties().clone();
String pathSeparator = p.getProperty("path.separator");
String platformRoot = p.getProperty("platform.root");
if (platformRoot != null && !platformRoot.endsWith(File.separator)) {
platformRoot += File.separator;
}
cls = appendProperties(p, cls);
appendProperty(p, "loader.preloadpath", pathSeparator, p.getProperty("compiler.linkpath"));
appendProperty(p, "loader.preload", pathSeparator, p.getProperty("compiler.link"));
// Force initialization of the class in case it needs it
try {
cls = Class.forName(cls.getName(), true, cls.getClassLoader());
} catch (ClassNotFoundException ex) {
Error e = new NoClassDefFoundError(ex.toString());
e.initCause(ex);
throw e;
}
// Preload native libraries desired by our class
String preloadPath = p.getProperty("loader.preloadpath");
String preload = p.getProperty("loader.preload");
String[] preloadPaths = preloadPath == null ? null : preloadPath.split(pathSeparator);
String[] preloads = preload == null ? null : preload .split(pathSeparator);
UnsatisfiedLinkError preloadError = null;
for (int i = 0; preloadPaths != null && platformRoot != null && i < preloadPaths.length; i++) {
if (!new File(preloadPaths[i]).isAbsolute()) {
preloadPaths[i] = platformRoot + preloadPaths[i];
}
}
for (int i = 0; preloads != null && i < preloads.length; i++) {
try {
loadLibrary(cls, preloadPaths, preloads[i]);
} catch (UnsatisfiedLinkError e) {
preloadError = e;
}
}
try {
return loadLibrary(cls, null, p.getProperty("loader.library"));
} catch (UnsatisfiedLinkError e) {
if (preloadError != null) {
e.initCause(preloadError);
}
throw e;
}
} | #vulnerable code
public static String load(Class cls) {
if (!loadLibraries || cls == null) {
return null;
}
// Find the top enclosing class, to match the library filename
Properties p = (Properties)getProperties().clone();
cls = appendProperties(p, cls);
// Force initialization of the class in case it needs it
try {
cls = Class.forName(cls.getName(), true, cls.getClassLoader());
} catch (ClassNotFoundException ex) {
Error e = new NoClassDefFoundError(ex.toString());
e.initCause(ex);
throw e;
}
// Preload native libraries desired by our class
String pathSeparator = p.getProperty("path.separator");
String platformRoot = p.getProperty("platform.root");
if (platformRoot != null && !platformRoot.endsWith(File.separator)) {
platformRoot += File.separator;
}
String preloadPath = p.getProperty("loader.preloadpath");
String preloadLibraries = p.getProperty("loader.preload");
UnsatisfiedLinkError preloadError = null;
if (preloadLibraries != null) {
String[] preloadPaths = preloadPath == null ? null : preloadPath.split(pathSeparator);
if (preloadPaths != null && platformRoot != null) {
for (int i = 0; i < preloadPaths.length; i++) {
if (!new File(preloadPaths[i]).isAbsolute()) {
preloadPaths[i] = platformRoot + preloadPaths[i];
}
}
}
String[] libnames = preloadLibraries.split(pathSeparator);
for (int i = 0; i < libnames.length; i++) {
try {
loadLibrary(cls, preloadPaths, libnames[i]);
} catch (UnsatisfiedLinkError e) {
preloadError = e;
}
}
}
try {
return loadLibrary(cls, null, p.getProperty("loader.library"));
} catch (UnsatisfiedLinkError e) {
if (preloadError != null) {
e.initCause(preloadError);
}
throw e;
}
}
#location 38
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
boolean classes(boolean handleExceptions, boolean defineAdapters, boolean convertStrings,
String loadSuffix, String baseLoadSuffix, String classPath, Class<?> ... classes) {
String version = Generator.class.getPackage().getImplementationVersion();
if (version == null) {
version = "unknown";
}
String warning = "// Generated by JavaCPP version " + version + ": DO NOT EDIT THIS FILE";
out.println(warning);
out.println();
if (out2 != null) {
out2.println(warning);
out2.println();
}
ClassProperties clsProperties = Loader.loadProperties(classes, properties, true);
for (String s : clsProperties.get("platform.pragma")) {
out.println("#pragma " + s);
}
for (String s : clsProperties.get("platform.define")) {
out.println("#define " + s);
}
out.println();
out.println("#ifdef _WIN32");
out.println(" #define _JAVASOFT_JNI_MD_H_");
out.println();
out.println(" #define JNIEXPORT __declspec(dllexport)");
out.println(" #define JNIIMPORT __declspec(dllimport)");
out.println(" #define JNICALL __stdcall");
out.println();
out.println(" typedef int jint;");
out.println(" typedef long long jlong;");
out.println(" typedef signed char jbyte;");
out.println("#elif defined(__GNUC__) && !defined(__ANDROID__)");
out.println(" #define _JAVASOFT_JNI_MD_H_");
out.println();
out.println(" #define JNIEXPORT __attribute__((visibility(\"default\")))");
out.println(" #define JNIIMPORT");
out.println(" #define JNICALL");
out.println();
out.println(" typedef int jint;");
out.println(" typedef long long jlong;");
out.println(" typedef signed char jbyte;");
out.println("#endif");
out.println();
out.println("#include <jni.h>");
if (out2 != null) {
out2.println("#include <jni.h>");
}
out.println();
out.println("#ifdef __ANDROID__");
out.println(" #include <android/log.h>");
out.println("#elif defined(__APPLE__) && defined(__OBJC__)");
out.println(" #include <TargetConditionals.h>");
out.println(" #include <Foundation/Foundation.h>");
out.println("#endif");
out.println();
out.println("#ifdef __linux__");
out.println(" #include <malloc.h>");
out.println(" #include <sys/types.h>");
out.println(" #include <sys/stat.h>");
out.println(" #include <sys/sysinfo.h>");
out.println(" #include <fcntl.h>");
out.println(" #include <unistd.h>");
out.println(" #include <dlfcn.h>");
out.println("#elif defined(__APPLE__)");
out.println(" #include <sys/types.h>");
out.println(" #include <sys/sysctl.h>");
out.println(" #include <mach/mach_init.h>");
out.println(" #include <mach/mach_host.h>");
out.println(" #include <mach/task.h>");
out.println(" #include <unistd.h>");
out.println(" #include <dlfcn.h>");
out.println("#elif defined(_WIN32)");
out.println(" #define NOMINMAX");
out.println(" #include <windows.h>");
out.println(" #include <psapi.h>");
out.println("#endif");
out.println();
out.println("#if defined(__ANDROID__) || TARGET_OS_IPHONE");
out.println(" #define NewWeakGlobalRef(obj) NewGlobalRef(obj)");
out.println(" #define DeleteWeakGlobalRef(obj) DeleteGlobalRef(obj)");
out.println("#endif");
out.println();
out.println("#include <limits.h>");
out.println("#include <stddef.h>");
out.println("#ifndef _WIN32");
out.println(" #include <stdint.h>");
out.println("#endif");
out.println("#include <stdio.h>");
out.println("#include <stdlib.h>");
out.println("#include <string.h>");
out.println("#include <exception>");
out.println("#include <memory>");
out.println("#include <new>");
if (baseLoadSuffix == null || baseLoadSuffix.isEmpty()) {
out.println();
out.println("#if defined(NATIVE_ALLOCATOR) && defined(NATIVE_DEALLOCATOR)");
out.println(" void* operator new(std::size_t size, const std::nothrow_t&) throw() {");
out.println(" return NATIVE_ALLOCATOR(size);");
out.println(" }");
out.println(" void* operator new[](std::size_t size, const std::nothrow_t&) throw() {");
out.println(" return NATIVE_ALLOCATOR(size);");
out.println(" }");
out.println(" void* operator new(std::size_t size) throw(std::bad_alloc) {");
out.println(" return NATIVE_ALLOCATOR(size);");
out.println(" }");
out.println(" void* operator new[](std::size_t size) throw(std::bad_alloc) {");
out.println(" return NATIVE_ALLOCATOR(size);");
out.println(" }");
out.println(" void operator delete(void* ptr) throw() {");
out.println(" NATIVE_DEALLOCATOR(ptr);");
out.println(" }");
out.println(" void operator delete[](void* ptr) throw() {");
out.println(" NATIVE_DEALLOCATOR(ptr);");
out.println(" }");
out.println("#endif");
}
out.println();
out.println("#define jlong_to_ptr(a) ((void*)(uintptr_t)(a))");
out.println("#define ptr_to_jlong(a) ((jlong)(uintptr_t)(a))");
out.println();
out.println("#if defined(_MSC_VER)");
out.println(" #define JavaCPP_noinline __declspec(noinline)");
out.println(" #define JavaCPP_hidden /* hidden by default */");
out.println("#elif defined(__GNUC__)");
out.println(" #define JavaCPP_noinline __attribute__((noinline)) __attribute__ ((unused))");
out.println(" #define JavaCPP_hidden __attribute__((visibility(\"hidden\"))) __attribute__ ((unused))");
out.println("#else");
out.println(" #define JavaCPP_noinline");
out.println(" #define JavaCPP_hidden");
out.println("#endif");
out.println();
if (loadSuffix == null) {
loadSuffix = "";
String p = clsProperties.getProperty("platform.library.static", "false").toLowerCase();
if (p.equals("true") || p.equals("t") || p.equals("")) {
loadSuffix = "_" + clsProperties.getProperty("platform.library");
}
}
if (classes != null) {
List exclude = clsProperties.get("platform.exclude");
List[] include = { clsProperties.get("platform.include"),
clsProperties.get("platform.cinclude") };
for (int i = 0; i < include.length; i++) {
if (include[i] != null && include[i].size() > 0) {
if (i == 1) {
out.println("extern \"C\" {");
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("extern \"C\" {");
out2.println("#endif");
}
}
for (String s : (List<String>)include[i]) {
if (exclude.contains(s)) {
continue;
}
String line = "#include ";
if (!s.startsWith("<") && !s.startsWith("\"")) {
line += '"';
}
line += s;
if (!s.endsWith(">") && !s.endsWith("\"")) {
line += '"';
}
out.println(line);
if (out2 != null) {
out2.println(line);
}
}
if (i == 1) {
out.println("}");
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("}");
out2.println("#endif");
}
}
out.println();
}
}
}
out.println("static JavaVM* JavaCPP_vm = NULL;");
out.println("static bool JavaCPP_haveAllocObject = false;");
out.println("static bool JavaCPP_haveNonvirtual = false;");
out.println("static const char* JavaCPP_classNames[" + jclasses.size() + "] = {");
Iterator<Class> classIterator = jclasses.iterator();
int maxMemberSize = 0;
while (classIterator.hasNext()) {
Class c = classIterator.next();
out.print(" \"" + c.getName().replace('.','/') + "\"");
if (classIterator.hasNext()) {
out.println(",");
}
Set<String> m = members.get(c);
if (m != null && m.size() > maxMemberSize) {
maxMemberSize = m.size();
}
}
out.println(" };");
out.println("static jclass JavaCPP_classes[" + jclasses.size() + "] = { NULL };");
out.println("static jfieldID JavaCPP_addressFID = NULL;");
out.println("static jfieldID JavaCPP_positionFID = NULL;");
out.println("static jfieldID JavaCPP_limitFID = NULL;");
out.println("static jfieldID JavaCPP_capacityFID = NULL;");
out.println("static jfieldID JavaCPP_deallocatorFID = NULL;");
out.println("static jfieldID JavaCPP_ownerAddressFID = NULL;");
out.println("static jmethodID JavaCPP_initMID = NULL;");
out.println("static jmethodID JavaCPP_arrayMID = NULL;");
out.println("static jmethodID JavaCPP_stringMID = NULL;");
out.println("static jmethodID JavaCPP_getBytesMID = NULL;");
out.println("static jmethodID JavaCPP_toStringMID = NULL;");
out.println();
out.println("static inline void JavaCPP_log(const char* fmt, ...) {");
out.println(" va_list ap;");
out.println(" va_start(ap, fmt);");
out.println("#ifdef __ANDROID__");
out.println(" __android_log_vprint(ANDROID_LOG_ERROR, \"javacpp\", fmt, ap);");
out.println("#elif defined(__APPLE__) && defined(__OBJC__)");
out.println(" NSLogv([NSString stringWithUTF8String:fmt], ap);");
out.println("#else");
out.println(" vfprintf(stderr, fmt, ap);");
out.println(" fprintf(stderr, \"\\n\");");
out.println("#endif");
out.println(" va_end(ap);");
out.println("}");
out.println();
if (baseLoadSuffix == null || baseLoadSuffix.isEmpty()) {
out.println("static inline jboolean JavaCPP_trimMemory() {");
out.println("#if defined(__linux__) && !defined(__ANDROID__)");
out.println(" return (jboolean)malloc_trim(0);");
out.println("#else");
out.println(" return 0;");
out.println("#endif");
out.println("}");
out.println();
out.println("static inline jlong JavaCPP_physicalBytes() {");
out.println(" jlong size = 0;");
out.println("#ifdef __linux__");
out.println(" static int fd = open(\"/proc/self/statm\", O_RDONLY, 0);");
out.println(" if (fd >= 0) {");
out.println(" char line[256];");
out.println(" char* s;");
out.println(" int n;");
out.println(" lseek(fd, 0, SEEK_SET);");
out.println(" if ((n = read(fd, line, sizeof(line))) > 0 && (s = (char*)memchr(line, ' ', n)) != NULL) {");
out.println(" size = (jlong)(atoll(s + 1) * getpagesize());");
out.println(" }");
out.println(" // no close(fd);");
out.println(" }");
out.println("#elif defined(__APPLE__)");
out.println(" task_basic_info info;");
out.println(" mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;");
out.println(" if (task_info(current_task(), TASK_BASIC_INFO, (task_info_t)&info, &count) == KERN_SUCCESS) {");
out.println(" size = (jlong)info.resident_size;");
out.println(" }");
out.println("#elif defined(_WIN32)");
out.println(" PROCESS_MEMORY_COUNTERS counters;");
out.println(" if (GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters))) {");
out.println(" size = (jlong)counters.WorkingSetSize;");
out.println(" }");
out.println("#endif");
out.println(" return size;");
out.println("}");
out.println();
out.println("static inline jlong JavaCPP_totalPhysicalBytes() {");
out.println(" jlong size = 0;");
out.println("#ifdef __linux__");
out.println(" struct sysinfo info;");
out.println(" if (sysinfo(&info) == 0) {");
out.println(" size = info.totalram;");
out.println(" }");
out.println("#elif defined(__APPLE__)");
out.println(" size_t length = sizeof(size);");
out.println(" sysctlbyname(\"hw.memsize\", &size, &length, NULL, 0);");
out.println("#elif defined(_WIN32)");
out.println(" MEMORYSTATUSEX status;");
out.println(" status.dwLength = sizeof(status);");
out.println(" if (GlobalMemoryStatusEx(&status)) {");
out.println(" size = status.ullTotalPhys;");
out.println(" }");
out.println("#endif");
out.println(" return size;");
out.println("}");
out.println();
out.println("static inline jlong JavaCPP_availablePhysicalBytes() {");
out.println(" jlong size = 0;");
out.println("#ifdef __linux__");
out.println(" int fd = open(\"/proc/meminfo\", O_RDONLY, 0);");
out.println(" if (fd >= 0) {");
out.println(" char temp[4096];");
out.println(" char *s;");
out.println(" int n;");
out.println(" if ((n = read(fd, temp, sizeof(temp))) > 0 && (s = (char*)memmem(temp, n, \"MemAvailable:\", 13)) != NULL) {");
out.println(" size = (jlong)(atoll(s + 13) * 1024);");
out.println(" }");
out.println(" close(fd);");
out.println(" }");
out.println(" if (size == 0) {");
out.println(" struct sysinfo info;");
out.println(" if (sysinfo(&info) == 0) {");
out.println(" size = info.freeram;");
out.println(" }");
out.println(" }");
out.println("#elif defined(__APPLE__)");
out.println(" vm_statistics_data_t info;");
out.println(" mach_msg_type_number_t count = HOST_VM_INFO_COUNT;");
out.println(" if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&info, &count) == KERN_SUCCESS) {");
out.println(" size = (jlong)info.free_count * getpagesize();");
out.println(" }");
out.println("#elif defined(_WIN32)");
out.println(" MEMORYSTATUSEX status;");
out.println(" status.dwLength = sizeof(status);");
out.println(" if (GlobalMemoryStatusEx(&status)) {");
out.println(" size = status.ullAvailPhys;");
out.println(" }");
out.println("#endif");
out.println(" return size;");
out.println("}");
out.println();
out.println("static inline jint JavaCPP_totalProcessors() {");
out.println(" jint total = 0;");
out.println("#ifdef __linux__");
out.println(" total = sysconf(_SC_NPROCESSORS_CONF);");
out.println("#elif defined(__APPLE__)");
out.println(" size_t length = sizeof(total);");
out.println(" sysctlbyname(\"hw.logicalcpu_max\", &total, &length, NULL, 0);");
out.println("#elif defined(_WIN32)");
out.println(" SYSTEM_INFO info;");
out.println(" GetSystemInfo(&info);");
out.println(" total = info.dwNumberOfProcessors;");
out.println("#endif");
out.println(" return total;");
out.println("}");
out.println();
out.println("static inline jint JavaCPP_totalCores() {");
out.println(" jint total = 0;");
out.println("#ifdef __linux__");
out.println(" const int n = sysconf(_SC_NPROCESSORS_CONF);");
out.println(" int pids[n], cids[n];");
out.println(" for (int i = 0; i < n; i++) {");
out.println(" int fd = 0, pid = 0, cid = 0;");
out.println(" char temp[256];");
out.println(" sprintf(temp, \"/sys/devices/system/cpu/cpu%d/topology/physical_package_id\", i);");
out.println(" if ((fd = open(temp, O_RDONLY, 0)) >= 0) {");
out.println(" if (read(fd, temp, sizeof(temp)) > 0) {");
out.println(" pid = atoi(temp);");
out.println(" }");
out.println(" close(fd);");
out.println(" }");
out.println(" sprintf(temp, \"/sys/devices/system/cpu/cpu%d/topology/core_id\", i);");
out.println(" if ((fd = open(temp, O_RDONLY, 0)) >= 0) {");
out.println(" if (read(fd, temp, sizeof(temp)) > 0) {");
out.println(" cid = atoi(temp);");
out.println(" }");
out.println(" close(fd);");
out.println(" }");
out.println(" bool found = false;");
out.println(" for (int j = 0; j < total; j++) {");
out.println(" if (pids[j] == pid && cids[j] == cid) {");
out.println(" found = true;");
out.println(" break;");
out.println(" }");
out.println(" }");
out.println(" if (!found) {");
out.println(" pids[total] = pid;");
out.println(" cids[total] = cid;");
out.println(" total++;");
out.println(" }");
out.println(" }");
out.println("#elif defined(__APPLE__)");
out.println(" size_t length = sizeof(total);");
out.println(" sysctlbyname(\"hw.physicalcpu_max\", &total, &length, NULL, 0);");
out.println("#elif defined(_WIN32)");
out.println(" SYSTEM_LOGICAL_PROCESSOR_INFORMATION *info = NULL;");
out.println(" DWORD length = 0;");
out.println(" BOOL success = GetLogicalProcessorInformation(info, &length);");
out.println(" while (!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {");
out.println(" info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION*)realloc(info, length);");
out.println(" success = GetLogicalProcessorInformation(info, &length);");
out.println(" }");
out.println(" if (success && info != NULL) {");
out.println(" length /= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);");
out.println(" for (DWORD i = 0; i < length; i++) {");
out.println(" if (info[i].Relationship == RelationProcessorCore) {");
out.println(" total++;");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" free(info);");
out.println("#endif");
out.println(" return total;");
out.println("}");
out.println();
out.println("static inline jint JavaCPP_totalChips() {");
out.println(" jint total = 0;");
out.println("#ifdef __linux__");
out.println(" const int n = sysconf(_SC_NPROCESSORS_CONF);");
out.println(" int pids[n];");
out.println(" for (int i = 0; i < n; i++) {");
out.println(" int fd = 0, pid = 0;");
out.println(" char temp[256];");
out.println(" sprintf(temp, \"/sys/devices/system/cpu/cpu%d/topology/physical_package_id\", i);");
out.println(" if ((fd = open(temp, O_RDONLY, 0)) >= 0) {");
out.println(" if (read(fd, temp, sizeof(temp)) > 0) {");
out.println(" pid = atoi(temp);");
out.println(" }");
out.println(" close(fd);");
out.println(" }");
out.println(" bool found = false;");
out.println(" for (int j = 0; j < total; j++) {");
out.println(" if (pids[j] == pid) {");
out.println(" found = true;");
out.println(" break;");
out.println(" }");
out.println(" }");
out.println(" if (!found) {");
out.println(" pids[total] = pid;");
out.println(" total++;");
out.println(" }");
out.println(" }");
out.println("#elif defined(__APPLE__)");
out.println(" size_t length = sizeof(total);");
out.println(" sysctlbyname(\"hw.packages\", &total, &length, NULL, 0);");
out.println("#elif defined(_WIN32)");
out.println(" SYSTEM_LOGICAL_PROCESSOR_INFORMATION *info = NULL;");
out.println(" DWORD length = 0;");
out.println(" BOOL success = GetLogicalProcessorInformation(info, &length);");
out.println(" while (!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {");
out.println(" info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION*)realloc(info, length);");
out.println(" success = GetLogicalProcessorInformation(info, &length);");
out.println(" }");
out.println(" if (success && info != NULL) {");
out.println(" length /= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);");
out.println(" for (DWORD i = 0; i < length; i++) {");
out.println(" if (info[i].Relationship == RelationProcessorPackage) {");
out.println(" total++;");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" free(info);");
out.println("#endif");
out.println(" return total;");
out.println("}");
out.println();
out.println("static inline void* JavaCPP_addressof(const char* name) {");
out.println(" void *address = NULL;");
out.println("#if defined(__linux__) || defined(__APPLE__)");
out.println(" address = dlsym(RTLD_DEFAULT, name);");
out.println("#elif defined(_WIN32)");
out.println(" HANDLE process = GetCurrentProcess();");
out.println(" HMODULE *modules = NULL;");
out.println(" DWORD length = 0, needed = 0;");
out.println(" BOOL success = EnumProcessModules(process, modules, length, &needed);");
out.println(" while (success && needed > length) {");
out.println(" modules = (HMODULE*)realloc(modules, length = needed);");
out.println(" success = EnumProcessModules(process, modules, length, &needed);");
out.println(" }");
out.println(" if (success && modules != NULL) {");
out.println(" length = needed / sizeof(HMODULE);");
out.println(" for (DWORD i = 0; i < length; i++) {");
out.println(" address = (void*)GetProcAddress(modules[i], name);");
out.println(" if (address != NULL) {");
out.println(" break;");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" free(modules);");
out.println("#endif");
out.println(" return address;");
out.println("}");
out.println();
}
out.println("static JavaCPP_noinline jclass JavaCPP_getClass(JNIEnv* env, int i) {");
out.println(" if (JavaCPP_classes[i] == NULL && env->PushLocalFrame(1) == 0) {");
out.println(" jclass cls = env->FindClass(JavaCPP_classNames[i]);");
out.println(" if (cls == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error loading class %s.\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" JavaCPP_classes[i] = (jclass)env->NewWeakGlobalRef(cls);");
out.println(" if (JavaCPP_classes[i] == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error creating global reference of class %s.\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" env->PopLocalFrame(NULL);");
out.println(" }");
out.println(" return JavaCPP_classes[i];");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jfieldID JavaCPP_getFieldID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jfieldID fid = env->GetFieldID(cls, name, sig);");
out.println(" if (fid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting field ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return fid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jmethodID JavaCPP_getMethodID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jmethodID mid = env->GetMethodID(cls, name, sig);");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting method ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return mid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jmethodID JavaCPP_getStaticMethodID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jmethodID mid = env->GetStaticMethodID(cls, name, sig);");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting static method ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return mid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jobject JavaCPP_createPointer(JNIEnv* env, int i, jclass cls = NULL) {");
out.println(" if (cls == NULL && (cls = JavaCPP_getClass(env, i)) == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" if (JavaCPP_haveAllocObject) {");
out.println(" return env->AllocObject(cls);");
out.println(" } else {");
out.println(" jmethodID mid = env->GetMethodID(cls, \"<init>\", \"(Lorg/bytedeco/javacpp/Pointer;)V\");");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting Pointer constructor of %s, while VM does not support AllocObject()\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" return env->NewObject(cls, mid, NULL);");
out.println(" }");
out.println("}");
out.println();
out.println("static JavaCPP_noinline void JavaCPP_initPointer(JNIEnv* env, jobject obj, const void* ptr, jlong size, void* owner, void (*deallocator)(void*)) {");
out.println(" if (deallocator != NULL) {");
out.println(" jvalue args[4];");
out.println(" args[0].j = ptr_to_jlong(ptr);");
out.println(" args[1].j = size;");
out.println(" args[2].j = ptr_to_jlong(owner);");
out.println(" args[3].j = ptr_to_jlong(deallocator);");
out.println(" if (JavaCPP_haveNonvirtual) {");
out.println(" env->CallNonvirtualVoidMethodA(obj, JavaCPP_getClass(env, "
+ jclasses.index(Pointer.class) + "), JavaCPP_initMID, args);");
out.println(" } else {");
out.println(" env->CallVoidMethodA(obj, JavaCPP_initMID, args);");
out.println(" }");
out.println(" } else {");
out.println(" env->SetLongField(obj, JavaCPP_addressFID, ptr_to_jlong(ptr));");
out.println(" env->SetLongField(obj, JavaCPP_limitFID, (jlong)size);");
out.println(" env->SetLongField(obj, JavaCPP_capacityFID, (jlong)size);");
out.println(" }");
out.println("}");
out.println();
if (handleExceptions || convertStrings) {
out.println("static JavaCPP_noinline jstring JavaCPP_createString(JNIEnv* env, const char* ptr) {");
out.println(" if (ptr == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println("#ifdef MODIFIED_UTF8_STRING");
out.println(" return env->NewStringUTF(ptr);");
out.println("#else");
out.println(" size_t length = strlen(ptr);");
out.println(" jbyteArray bytes = env->NewByteArray(length < INT_MAX ? length : INT_MAX);");
out.println(" env->SetByteArrayRegion(bytes, 0, length < INT_MAX ? length : INT_MAX, (signed char*)ptr);");
out.println(" return (jstring)env->NewObject(JavaCPP_getClass(env, " + jclasses.index(String.class) + "), JavaCPP_stringMID, bytes);");
out.println("#endif");
out.println("}");
out.println();
}
if (convertStrings) {
out.println("static JavaCPP_noinline const char* JavaCPP_getStringBytes(JNIEnv* env, jstring str) {");
out.println(" if (str == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println("#ifdef MODIFIED_UTF8_STRING");
out.println(" return env->GetStringUTFChars(str, NULL);");
out.println("#else");
out.println(" jbyteArray bytes = (jbyteArray)env->CallObjectMethod(str, JavaCPP_getBytesMID);");
out.println(" if (bytes == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting bytes from string.\");");
out.println(" return NULL;");
out.println(" }");
out.println(" jsize length = env->GetArrayLength(bytes);");
out.println(" signed char* ptr = new (std::nothrow) signed char[length + 1];");
out.println(" if (ptr != NULL) {");
out.println(" env->GetByteArrayRegion(bytes, 0, length, ptr);");
out.println(" ptr[length] = 0;");
out.println(" }");
out.println(" return (const char*)ptr;");
out.println("#endif");
out.println("}");
out.println();
out.println("static JavaCPP_noinline void JavaCPP_releaseStringBytes(JNIEnv* env, jstring str, const char* ptr) {");
out.println("#ifdef MODIFIED_UTF8_STRING");
out.println(" if (str != NULL) {");
out.println(" env->ReleaseStringUTFChars(str, ptr);");
out.println(" }");
out.println("#else");
out.println(" delete[] ptr;");
out.println("#endif");
out.println("}");
out.println();
}
out.println("class JavaCPP_hidden JavaCPP_exception : public std::exception {");
out.println("public:");
out.println(" JavaCPP_exception(const char* str) throw() {");
out.println(" if (str == NULL) {");
out.println(" strcpy(msg, \"Unknown exception.\");");
out.println(" } else {");
out.println(" strncpy(msg, str, sizeof(msg));");
out.println(" msg[sizeof(msg) - 1] = 0;");
out.println(" }");
out.println(" }");
out.println(" virtual const char* what() const throw() { return msg; }");
out.println(" char msg[1024];");
out.println("};");
out.println();
if (handleExceptions) {
out.println("#ifndef GENERIC_EXCEPTION_CLASS");
out.println("#define GENERIC_EXCEPTION_CLASS std::exception");
out.println("#endif");
out.println("static JavaCPP_noinline jthrowable JavaCPP_handleException(JNIEnv* env, int i) {");
out.println(" jstring str = NULL;");
out.println(" try {");
out.println(" throw;");
out.println(" } catch (GENERIC_EXCEPTION_CLASS& e) {");
out.println(" str = JavaCPP_createString(env, e.what());");
out.println(" } catch (...) {");
out.println(" str = JavaCPP_createString(env, \"Unknown exception.\");");
out.println(" }");
out.println(" jmethodID mid = JavaCPP_getMethodID(env, i, \"<init>\", \"(Ljava/lang/String;)V\");");
out.println(" if (mid == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" return (jthrowable)env->NewObject(JavaCPP_getClass(env, i), mid, str);");
out.println("}");
out.println();
}
Class deallocator, nativeDeallocator;
try {
deallocator = Class.forName(Pointer.class.getName() + "$Deallocator", false, Pointer.class.getClassLoader());
nativeDeallocator = Class.forName(Pointer.class.getName() + "$NativeDeallocator", false, Pointer.class.getClassLoader());
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
}
if (defineAdapters) {
out.println("static JavaCPP_noinline void* JavaCPP_getPointerOwner(JNIEnv* env, jobject obj) {");
out.println(" if (obj != NULL) {");
out.println(" jobject deallocator = env->GetObjectField(obj, JavaCPP_deallocatorFID);");
out.println(" if (deallocator != NULL && env->IsInstanceOf(deallocator, JavaCPP_getClass(env, "
+ jclasses.index(nativeDeallocator) + "))) {");
out.println(" return jlong_to_ptr(env->GetLongField(deallocator, JavaCPP_ownerAddressFID));");
out.println(" }");
out.println(" }");
out.println(" return NULL;");
out.println("}");
out.println();
out.println("#include <vector>");
out.println("template<typename P, typename T = P> class JavaCPP_hidden VectorAdapter {");
out.println("public:");
out.println(" VectorAdapter(const P* ptr, typename std::vector<T>::size_type size, void* owner) : ptr((P*)ptr), size(size), owner(owner),");
out.println(" vec2(ptr ? std::vector<T>((P*)ptr, (P*)ptr + size) : std::vector<T>()), vec(vec2) { }");
out.println(" VectorAdapter(const std::vector<T>& vec) : ptr(0), size(0), owner(0), vec2(vec), vec(vec2) { }");
out.println(" VectorAdapter( std::vector<T>& vec) : ptr(0), size(0), owner(0), vec(vec) { }");
out.println(" VectorAdapter(const std::vector<T>* vec) : ptr(0), size(0), owner(0), vec(*(std::vector<T>*)vec) { }");
out.println(" void assign(P* ptr, typename std::vector<T>::size_type size, void* owner) {");
out.println(" this->ptr = ptr;");
out.println(" this->size = size;");
out.println(" this->owner = owner;");
out.println(" vec.assign(ptr, ptr + size);");
out.println(" }");
out.println(" static void deallocate(void* owner) { operator delete(owner); }");
out.println(" operator P*() {");
out.println(" if (vec.size() > size) {");
out.println(" ptr = (P*)(operator new(sizeof(P) * vec.size(), std::nothrow_t()));");
out.println(" }");
out.println(" if (ptr) {");
out.println(" std::copy(vec.begin(), vec.end(), ptr);");
out.println(" }");
out.println(" size = vec.size();");
out.println(" owner = ptr;");
out.println(" return ptr;");
out.println(" }");
out.println(" operator const P*() { return &vec[0]; }");
out.println(" operator std::vector<T>&() { return vec; }");
out.println(" operator std::vector<T>*() { return ptr ? &vec : 0; }");
out.println(" P* ptr;");
out.println(" typename std::vector<T>::size_type size;");
out.println(" void* owner;");
out.println(" std::vector<T> vec2;");
out.println(" std::vector<T>& vec;");
out.println("};");
out.println();
out.println("#include <string>");
out.println("class JavaCPP_hidden StringAdapter {");
out.println("public:");
out.println(" StringAdapter(const char* ptr, size_t size, void* owner) : ptr((char*)ptr), size(size), owner(owner),");
out.println(" str2(ptr ? (char*)ptr : \"\", ptr ? (size > 0 ? size : strlen((char*)ptr)) : 0), str(str2) { }");
out.println(" StringAdapter(const signed char* ptr, size_t size, void* owner) : ptr((char*)ptr), size(size), owner(owner),");
out.println(" str2(ptr ? (char*)ptr : \"\", ptr ? (size > 0 ? size : strlen((char*)ptr)) : 0), str(str2) { }");
out.println(" StringAdapter(const unsigned char* ptr, size_t size, void* owner) : ptr((char*)ptr), size(size), owner(owner),");
out.println(" str2(ptr ? (char*)ptr : \"\", ptr ? (size > 0 ? size : strlen((char*)ptr)) : 0), str(str2) { }");
out.println(" StringAdapter(const std::string& str) : ptr(0), size(0), owner(0), str2(str), str(str2) { }");
out.println(" StringAdapter( std::string& str) : ptr(0), size(0), owner(0), str(str) { }");
out.println(" StringAdapter(const std::string* str) : ptr(0), size(0), owner(0), str(*(std::string*)str) { }");
out.println(" void assign(char* ptr, size_t size, void* owner) {");
out.println(" this->ptr = ptr;");
out.println(" this->size = size;");
out.println(" this->owner = owner;");
out.println(" str.assign(ptr ? ptr : \"\", ptr ? (size > 0 ? size : strlen((char*)ptr)) : 0);");
out.println(" }");
out.println(" void assign(const char* ptr, size_t size, void* owner) { assign((char*)ptr, size, owner); }");
out.println(" void assign(const signed char* ptr, size_t size, void* owner) { assign((char*)ptr, size, owner); }");
out.println(" void assign(const unsigned char* ptr, size_t size, void* owner) { assign((char*)ptr, size, owner); }");
out.println(" static void deallocate(void* owner) { delete[] (char*)owner; }");
out.println(" operator char*() {");
out.println(" const char* data = str.data();");
out.println(" if (str.size() > size) {");
out.println(" ptr = new (std::nothrow) char[str.size()+1];");
out.println(" if (ptr) memset(ptr, 0, str.size()+1);");
out.println(" }");
out.println(" if (ptr && memcmp(ptr, data, str.size()) != 0) {");
out.println(" memcpy(ptr, data, str.size());");
out.println(" if (size > str.size()) ptr[str.size()] = 0;");
out.println(" }");
out.println(" size = str.size();");
out.println(" owner = ptr;");
out.println(" return ptr;");
out.println(" }");
out.println(" operator signed char*() { return (signed char*)(operator char*)(); }");
out.println(" operator unsigned char*() { return (unsigned char*)(operator char*)(); }");
out.println(" operator const char*() { return str.c_str(); }");
out.println(" operator const signed char*() { return (signed char*)str.c_str(); }");
out.println(" operator const unsigned char*() { return (unsigned char*)str.c_str(); }");
out.println(" operator std::string&() { return str; }");
out.println(" operator std::string*() { return ptr ? &str : 0; }");
out.println(" char* ptr;");
out.println(" size_t size;");
out.println(" void* owner;");
out.println(" std::string str2;");
out.println(" std::string& str;");
out.println("};");
out.println();
out.println("#ifdef SHARED_PTR_NAMESPACE");
out.println("template<class T> class SharedPtrAdapter {");
out.println("public:");
out.println(" typedef SHARED_PTR_NAMESPACE::shared_ptr<T> S;");
out.println(" SharedPtrAdapter(const T* ptr, size_t size, void* owner) : ptr((T*)ptr), size(size), owner(owner),");
out.println(" sharedPtr2(owner != NULL && owner != ptr ? *(S*)owner : S((T*)ptr)), sharedPtr(sharedPtr2) { }");
out.println(" SharedPtrAdapter(const S& sharedPtr) : ptr(0), size(0), owner(0), sharedPtr2(sharedPtr), sharedPtr(sharedPtr2) { }");
out.println(" SharedPtrAdapter( S& sharedPtr) : ptr(0), size(0), owner(0), sharedPtr(sharedPtr) { }");
out.println(" SharedPtrAdapter(const S* sharedPtr) : ptr(0), size(0), owner(0), sharedPtr(*(S*)sharedPtr) { }");
out.println(" void assign(T* ptr, size_t size, S* owner) {");
out.println(" this->ptr = ptr;");
out.println(" this->size = size;");
out.println(" this->owner = owner;");
out.println(" this->sharedPtr = owner != NULL && owner != ptr ? *(S*)owner : S((T*)ptr);");
out.println(" }");
out.println(" static void deallocate(void* owner) { delete (S*)owner; }");
out.println(" operator typename SHARED_PTR_NAMESPACE::remove_const<T>::type*() {");
out.println(" ptr = sharedPtr.get();");
out.println(" if (owner == NULL || owner == ptr) {");
out.println(" owner = new S(sharedPtr);");
out.println(" }");
out.println(" return ptr;");
out.println(" }");
out.println(" operator const T*() { return sharedPtr.get(); }");
out.println(" operator S&() { return sharedPtr; }");
out.println(" operator S*() { return &sharedPtr; }");
out.println(" T* ptr;");
out.println(" size_t size;");
out.println(" void* owner;");
out.println(" S sharedPtr2;");
out.println(" S& sharedPtr;");
out.println("};");
out.println("#endif");
out.println();
out.println("#ifdef UNIQUE_PTR_NAMESPACE");
out.println("template<class T> class UniquePtrAdapter {");
out.println("public:");
out.println(" typedef UNIQUE_PTR_NAMESPACE::unique_ptr<T> U;");
out.println(" UniquePtrAdapter(const T* ptr, size_t size, void* owner) : ptr((T*)ptr), size(size), owner(owner),");
out.println(" uniquePtr2(owner != NULL && owner != ptr ? U() : U((T*)ptr)),");
out.println(" uniquePtr(owner != NULL && owner != ptr ? *(U*)owner : uniquePtr2) { }");
out.println(" UniquePtrAdapter(const U& uniquePtr) : ptr(0), size(0), owner(0), uniquePtr((U&)uniquePtr) { }");
out.println(" UniquePtrAdapter( U& uniquePtr) : ptr(0), size(0), owner(0), uniquePtr(uniquePtr) { }");
out.println(" UniquePtrAdapter(const U* uniquePtr) : ptr(0), size(0), owner(0), uniquePtr(*(U*)uniquePtr) { }");
out.println(" void assign(T* ptr, size_t size, U* owner) {");
out.println(" this->ptr = ptr;");
out.println(" this->size = size;");
out.println(" this->owner = owner;");
out.println(" this->uniquePtr = owner != NULL && owner != ptr ? *(U*)owner : U((T*)ptr);");
out.println(" }");
out.println(" static void deallocate(void* owner) { delete (U*)owner; }");
out.println(" operator typename UNIQUE_PTR_NAMESPACE::remove_const<T>::type*() {");
out.println(" ptr = uniquePtr.get();");
out.println(" if (owner == NULL || owner == ptr) {");
out.println(" owner = new U(UNIQUE_PTR_NAMESPACE::move(uniquePtr));");
out.println(" }");
out.println(" return ptr;");
out.println(" }");
out.println(" operator const T*() { return uniquePtr.get(); }");
out.println(" operator U&() { return uniquePtr; }");
out.println(" operator U*() { return &uniquePtr; }");
out.println(" T* ptr;");
out.println(" size_t size;");
out.println(" void* owner;");
out.println(" U uniquePtr2;");
out.println(" U& uniquePtr;");
out.println("};");
out.println("#endif");
out.println();
}
if (!functions.isEmpty() || !virtualFunctions.isEmpty()) {
out.println("static JavaCPP_noinline void JavaCPP_detach(bool detach) {");
out.println("#ifndef NO_JNI_DETACH_THREAD");
out.println(" if (detach && JavaCPP_vm->DetachCurrentThread() != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not detach the JavaVM from the current thread.\");");
out.println(" }");
out.println("#endif");
out.println("}");
out.println();
if (!loadSuffix.isEmpty()) {
out.println("extern \"C\" {");
out.println("JNIEXPORT jint JNICALL JNI_OnLoad" + loadSuffix + "(JavaVM* vm, void* reserved);");
out.println("}");
}
out.println("static JavaCPP_noinline bool JavaCPP_getEnv(JNIEnv** env) {");
out.println(" bool attached = false;");
out.println(" JavaVM *vm = JavaCPP_vm;");
out.println(" if (vm == NULL) {");
if (out2 != null) {
out.println("#if !defined(__ANDROID__) && !TARGET_OS_IPHONE");
out.println(" int size = 1;");
out.println(" if (JNI_GetCreatedJavaVMs(&vm, 1, &size) != JNI_OK || size == 0) {");
out.println("#endif");
}
out.println(" JavaCPP_log(\"Could not get any created JavaVM.\");");
out.println(" *env = NULL;");
out.println(" return false;");
if (out2 != null) {
out.println("#if !defined(__ANDROID__) && !TARGET_OS_IPHONE");
out.println(" }");
out.println("#endif");
}
out.println(" }");
out.println(" if (vm->GetEnv((void**)env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" struct {");
out.println(" JNIEnv **env;");
out.println(" operator JNIEnv**() { return env; } // Android JNI");
out.println(" operator void**() { return (void**)env; } // standard JNI");
out.println(" } env2 = { env };");
out.println(" if (vm->AttachCurrentThread(env2, NULL) != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not attach the JavaVM to the current thread.\");");
out.println(" *env = NULL;");
out.println(" return false;");
out.println(" }");
out.println(" attached = true;");
out.println(" }");
out.println(" if (JavaCPP_vm == NULL) {");
out.println(" if (JNI_OnLoad" + loadSuffix + "(vm, NULL) < 0) {");
out.println(" JavaCPP_detach(attached);");
out.println(" *env = NULL;");
out.println(" return false;");
out.println(" }");
out.println(" }");
out.println(" return attached;");
out.println("}");
out.println();
}
for (Class c : functions) {
String[] typeName = cppTypeName(c);
String[] returnConvention = typeName[0].split("\\(");
returnConvention[1] = constValueTypeName(returnConvention[1]);
String parameterDeclaration = typeName[1].substring(1);
String instanceTypeName = functionClassName(c);
out.println("struct JavaCPP_hidden " + instanceTypeName + " {");
out.println(" " + instanceTypeName + "() : ptr(NULL), obj(NULL) { }");
if (parameterDeclaration != null && parameterDeclaration.length() > 0) {
out.println(" " + returnConvention[0] + "operator()" + parameterDeclaration + ";");
}
out.println(" " + typeName[0] + "ptr" + typeName[1] + ";");
out.println(" jobject obj; static jmethodID mid;");
out.println("};");
out.println("jmethodID " + instanceTypeName + "::mid = NULL;");
}
out.println();
for (Class c : jclasses) {
Set<String> functionList = virtualFunctions.get(c);
if (functionList == null) {
continue;
}
Set<String> memberList = virtualMembers.get(c);
String[] typeName = cppTypeName(c);
String valueTypeName = valueTypeName(typeName);
String subType = "JavaCPP_" + mangle(valueTypeName);
out.println("class JavaCPP_hidden " + subType + " : public " + valueTypeName + " {");
out.println("public:");
out.println(" jobject obj;");
for (String s : functionList) {
out.println(" static jmethodID " + s + ";");
}
out.println();
for (String s : memberList) {
out.println(s);
}
out.println("};");
for (String s : functionList) {
out.println("jmethodID " + subType + "::" + s + " = NULL;");
}
}
out.println();
for (String s : callbacks) {
out.println(s);
}
out.println();
for (Class c : deallocators) {
String name = "JavaCPP_" + mangle(c.getName());
out.print("static void " + name + "_deallocate(void *p) { ");
if (FunctionPointer.class.isAssignableFrom(c)) {
String typeName = functionClassName(c) + "*";
out.println("JNIEnv *e; bool a = JavaCPP_getEnv(&e); if (e != NULL) e->DeleteWeakGlobalRef((jweak)(("
+ typeName + ")p)->obj); delete (" + typeName + ")p; JavaCPP_detach(a); }");
} else if (virtualFunctions.containsKey(c)) {
String[] typeName = cppTypeName(c);
String valueTypeName = valueTypeName(typeName);
String subType = "JavaCPP_" + mangle(valueTypeName);
out.println("JNIEnv *e; bool a = JavaCPP_getEnv(&e); if (e != NULL) e->DeleteWeakGlobalRef((jweak)(("
+ subType + "*)p)->obj); delete (" + subType + "*)p; JavaCPP_detach(a); }");
} else {
String[] typeName = cppTypeName(c);
out.println("delete (" + typeName[0] + typeName[1] + ")p; }");
}
}
for (Class c : arrayDeallocators) {
String name = "JavaCPP_" + mangle(c.getName());
String[] typeName = cppTypeName(c);
out.println("static void " + name + "_deallocateArray(void* p) { delete[] (" + typeName[0] + typeName[1] + ")p; }");
}
out.println();
out.println("static const char* JavaCPP_members[" + jclasses.size() + "][" + maxMemberSize + 1 + "] = {");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
out.print(" { ");
Set<String> m = members.get(classIterator.next());
Iterator<String> memberIterator = m == null ? null : m.iterator();
if (memberIterator == null || !memberIterator.hasNext()) {
out.print("NULL");
} else while (memberIterator.hasNext()) {
out.print("\"" + memberIterator.next() + "\"");
if (memberIterator.hasNext()) {
out.print(", ");
}
}
out.print(" }");
if (classIterator.hasNext()) {
out.println(",");
}
}
out.println(" };");
out.println("static int JavaCPP_offsets[" + jclasses.size() + "][" + maxMemberSize + 1 + "] = {");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
out.print(" { ");
Class c = classIterator.next();
Set<String> m = members.get(c);
Iterator<String> memberIterator = m == null ? null : m.iterator();
if (memberIterator == null || !memberIterator.hasNext()) {
out.print("-1");
} else while (memberIterator.hasNext()) {
String[] typeName = cppTypeName(c);
String valueTypeName = valueTypeName(typeName);
String memberName = memberIterator.next();
if ("sizeof".equals(memberName)) {
if ("void".equals(valueTypeName)) {
valueTypeName = "void*";
}
out.print("sizeof(" + valueTypeName + ")");
} else {
out.print("offsetof(" + valueTypeName + ", " + memberName + ")");
}
if (memberIterator.hasNext()) {
out.print(", ");
}
}
out.print(" }");
if (classIterator.hasNext()) {
out.println(",");
}
}
out.println(" };");
out.print("static int JavaCPP_memberOffsetSizes[" + jclasses.size() + "] = { ");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
Set<String> m = members.get(classIterator.next());
out.print(m == null ? 1 : m.size());
if (classIterator.hasNext()) {
out.print(", ");
}
}
out.println(" };");
out.println();
out.println("extern \"C\" {");
if (out2 != null) {
out2.println();
out2.println("#ifdef __cplusplus");
out2.println("extern \"C\" {");
out2.println("#endif");
out2.println("JNIIMPORT int JavaCPP_init" + loadSuffix + "(int argc, const char *argv[]);");
out.println();
out.println("JNIEXPORT int JavaCPP_init" + loadSuffix + "(int argc, const char *argv[]) {");
out.println("#if defined(__ANDROID__) || TARGET_OS_IPHONE");
out.println(" return JNI_OK;");
out.println("#else");
out.println(" if (JavaCPP_vm != NULL) {");
out.println(" return JNI_OK;");
out.println(" }");
out.println(" int err;");
out.println(" JavaVM *vm;");
out.println(" JNIEnv *env;");
out.println(" int nOptions = 1 + (argc > 255 ? 255 : argc);");
out.println(" JavaVMOption options[256] = { { NULL } };");
out.println(" options[0].optionString = (char*)\"-Djava.class.path=" + classPath.replace('\\', '/') + "\";");
out.println(" for (int i = 1; i < nOptions && argv != NULL; i++) {");
out.println(" options[i].optionString = (char*)argv[i - 1];");
out.println(" }");
out.println(" JavaVMInitArgs vm_args = { " + JNI_VERSION + ", nOptions, options };");
out.println(" return (err = JNI_CreateJavaVM(&vm, (void**)&env, &vm_args)) == JNI_OK && vm != NULL && (err = JNI_OnLoad" + loadSuffix + "(vm, NULL)) >= 0 ? JNI_OK : err;");
out.println("#endif");
out.println("}");
}
if (baseLoadSuffix != null && !baseLoadSuffix.isEmpty()) {
out.println();
out.println("JNIEXPORT jint JNICALL JNI_OnLoad" + baseLoadSuffix + "(JavaVM* vm, void* reserved);");
out.println("JNIEXPORT void JNICALL JNI_OnUnload" + baseLoadSuffix + "(JavaVM* vm, void* reserved);");
}
out.println(); // XXX: JNI_OnLoad() should ideally be protected by some mutex
out.println("JNIEXPORT jint JNICALL JNI_OnLoad" + loadSuffix + "(JavaVM* vm, void* reserved) {");
if (baseLoadSuffix != null && !baseLoadSuffix.isEmpty()) {
out.println(" if (JNI_OnLoad" + baseLoadSuffix + "(vm, reserved) == JNI_ERR) {");
out.println(" return JNI_ERR;");
out.println(" }");
}
out.println(" JNIEnv* env;");
out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnLoad" + loadSuffix + "().\");");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" if (JavaCPP_vm == vm) {");
out.println(" return env->GetVersion();");
out.println(" }");
out.println(" JavaCPP_vm = vm;");
out.println(" JavaCPP_haveAllocObject = env->functions->AllocObject != NULL;");
out.println(" JavaCPP_haveNonvirtual = env->functions->CallNonvirtualVoidMethodA != NULL;");
out.println(" jmethodID putMemberOffsetMID = JavaCPP_getStaticMethodID(env, " +
jclasses.index(Loader.class) + ", \"putMemberOffset\", \"(Ljava/lang/String;Ljava/lang/String;I)Ljava/lang/Class;\");");
out.println(" if (putMemberOffsetMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" for (int i = 0; i < " + jclasses.size() + " && !env->ExceptionCheck(); i++) {");
out.println(" for (int j = 0; j < JavaCPP_memberOffsetSizes[i] && !env->ExceptionCheck(); j++) {");
out.println(" if (env->PushLocalFrame(3) == 0) {");
out.println(" jvalue args[3];");
out.println(" args[0].l = env->NewStringUTF(JavaCPP_classNames[i]);");
out.println(" args[1].l = JavaCPP_members[i][j] == NULL ? NULL : env->NewStringUTF(JavaCPP_members[i][j]);");
out.println(" args[2].i = JavaCPP_offsets[i][j];");
out.println(" jclass cls = (jclass)env->CallStaticObjectMethodA(JavaCPP_getClass(env, " +
jclasses.index(Loader.class) + "), putMemberOffsetMID, args);");
out.println(" if (cls == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error putting member offsets for class %s.\", JavaCPP_classNames[i]);");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_classes[i] = (jclass)env->NewWeakGlobalRef(cls);"); // cache here for custom class loaders
out.println(" if (JavaCPP_classes[i] == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error creating global reference of class %s.\", JavaCPP_classNames[i]);");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" env->PopLocalFrame(NULL);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" JavaCPP_addressFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"address\", \"J\");");
out.println(" if (JavaCPP_addressFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_positionFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"position\", \"J\");");
out.println(" if (JavaCPP_positionFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_limitFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"limit\", \"J\");");
out.println(" if (JavaCPP_limitFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_capacityFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"capacity\", \"J\");");
out.println(" if (JavaCPP_capacityFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_deallocatorFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"deallocator\", \"" + signature(deallocator) + "\");");
out.println(" if (JavaCPP_deallocatorFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_ownerAddressFID = JavaCPP_getFieldID(env, " +
jclasses.index(nativeDeallocator) + ", \"ownerAddress\", \"J\");");
out.println(" if (JavaCPP_ownerAddressFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_initMID = JavaCPP_getMethodID(env, " +
jclasses.index(Pointer.class) + ", \"init\", \"(JJJJ)V\");");
out.println(" if (JavaCPP_initMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_arrayMID = JavaCPP_getMethodID(env, " +
jclasses.index(Buffer.class) + ", \"array\", \"()Ljava/lang/Object;\");");
out.println(" if (JavaCPP_arrayMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_stringMID = JavaCPP_getMethodID(env, " +
jclasses.index(String.class) + ", \"<init>\", \"([B)V\");");
out.println(" if (JavaCPP_stringMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_getBytesMID = JavaCPP_getMethodID(env, " +
jclasses.index(String.class) + ", \"getBytes\", \"()[B\");");
out.println(" if (JavaCPP_getBytesMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_toStringMID = JavaCPP_getMethodID(env, " +
jclasses.index(Object.class) + ", \"toString\", \"()Ljava/lang/String;\");");
out.println(" if (JavaCPP_toStringMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" return env->GetVersion();");
out.println("}");
out.println();
if (out2 != null) {
out2.println("JNIIMPORT int JavaCPP_uninit" + loadSuffix + "();");
out2.println();
out.println("JNIEXPORT int JavaCPP_uninit" + loadSuffix + "() {");
out.println("#if defined(__ANDROID__) || TARGET_OS_IPHONE");
out.println(" return JNI_OK;");
out.println("#else");
out.println(" JavaVM *vm = JavaCPP_vm;");
out.println(" JNI_OnUnload" + loadSuffix + "(JavaCPP_vm, NULL);");
out.println(" return vm->DestroyJavaVM();");
out.println("#endif");
out.println("}");
}
out.println();
out.println("JNIEXPORT void JNICALL JNI_OnUnload" + loadSuffix + "(JavaVM* vm, void* reserved) {");
out.println(" JNIEnv* env;");
out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnUnLoad" + loadSuffix + "().\");");
out.println(" return;");
out.println(" }");
out.println(" for (int i = 0; i < " + jclasses.size() + "; i++) {");
out.println(" env->DeleteWeakGlobalRef((jweak)JavaCPP_classes[i]);");
out.println(" JavaCPP_classes[i] = NULL;");
out.println(" }");
if (baseLoadSuffix != null && !baseLoadSuffix.isEmpty()) {
out.println(" JNI_OnUnload" + baseLoadSuffix + "(vm, reserved);");
}
out.println(" JavaCPP_vm = NULL;");
out.println("}");
out.println();
boolean supportedPlatform = false;
LinkedHashSet<Class> allClasses = new LinkedHashSet<Class>();
if (baseLoadSuffix == null || baseLoadSuffix.isEmpty()) {
supportedPlatform = true;
allClasses.addAll(baseClasses);
}
if (classes != null) {
allClasses.addAll(Arrays.asList(classes));
for (Class<?> cls : classes) {
supportedPlatform |= checkPlatform(cls);
}
}
boolean didSomethingUseful = false;
for (Class<?> cls : allClasses) {
try {
didSomethingUseful |= methods(cls);
} catch (NoClassDefFoundError e) {
logger.warn("Could not generate code for class " + cls.getCanonicalName() + ": " + e);
}
}
out.println("}");
out.println();
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("}");
out2.println("#endif");
}
return supportedPlatform;
} | #vulnerable code
boolean checkPlatform(Platform platform, String[] defaultNames) {
if (platform == null) {
return true;
}
if (defaultNames == null) {
defaultNames = new String[0];
}
String platform2 = properties.getProperty("platform");
String[][] names = { platform.value().length > 0 ? platform.value() : defaultNames, platform.not() };
boolean[] matches = { false, false };
for (int i = 0; i < names.length; i++) {
for (String s : names[i]) {
if (platform2.startsWith(s)) {
matches[i] = true;
break;
}
}
}
if ((names[0].length == 0 || matches[0]) && (names[1].length == 0 || !matches[1])) {
return true;
}
return false;
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected <P extends Pointer> P deallocator(Deallocator deallocator) {
if (this.deallocator != null) {
if (logger.isDebugEnabled()) {
logger.debug("Predeallocating " + this);
}
this.deallocator.deallocate();
this.deallocator = null;
}
if (deallocator != null && !deallocator.equals(null)) {
this.deallocator = deallocator;
DeallocatorReference r = deallocator instanceof DeallocatorReference ?
(DeallocatorReference)deallocator :
new DeallocatorReference(this, deallocator);
boolean lowMemory = false;
try {
if (maxBytes > 0 && DeallocatorReference.totalBytes + r.bytes > maxBytes) {
lowMemory = true;
lowMemoryCount.incrementAndGet();
}
if (lowMemoryCount.get() > 0) {
// synchronize allocation across threads when low on memory
synchronized (lowMemoryCount) {
int count = 0;
while (count++ < maxRetries && DeallocatorReference.totalBytes + r.bytes > maxBytes) {
// try to get some more memory back
System.gc();
Thread.sleep(100);
}
if (count >= maxRetries && DeallocatorReference.totalBytes + r.bytes > maxBytes) {
deallocate();
throw new OutOfMemoryError("Cannot allocate " + DeallocatorReference.totalBytes
+ " + " + r.bytes + " bytes (> Pointer.maxBytes)");
}
}
}
} catch (InterruptedException ex) {
// reset interrupt to be nice
Thread.currentThread().interrupt();
} finally {
if (lowMemory) {
lowMemoryCount.decrementAndGet();
}
}
if (logger.isDebugEnabled()) {
logger.debug("Registering " + this);
}
r.add();
}
return (P)this;
} | #vulnerable code
protected <P extends Pointer> P deallocator(Deallocator deallocator) {
if (this.deallocator != null) {
if (logger.isDebugEnabled()) {
logger.debug("Predeallocating " + this);
}
this.deallocator.deallocate();
this.deallocator = null;
}
if (deallocator != null && !deallocator.equals(null)) {
this.deallocator = deallocator;
DeallocatorReference r = deallocator instanceof DeallocatorReference ?
(DeallocatorReference)deallocator :
new DeallocatorReference(this, deallocator);
int count = 0;
while (count++ < maxRetries && maxBytes > 0 && DeallocatorReference.totalBytes + r.bytes > maxBytes) {
try {
// try to get some more memory back
System.gc();
Thread.sleep(100);
} catch (InterruptedException ex) {
// reset interrupt to be nice
Thread.currentThread().interrupt();
break;
}
}
if (maxBytes > 0 && DeallocatorReference.totalBytes + r.bytes > maxBytes) {
deallocate();
throw new OutOfMemoryError("Cannot allocate " + DeallocatorReference.totalBytes
+ " + " + r.bytes + " bytes (> Pointer.maxBytes)");
}
if (logger.isDebugEnabled()) {
logger.debug("Registering " + this);
}
r.add();
}
return (P)this;
}
#location 27
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override public void execute() throws MojoExecutionException {
final Log log = getLog();
try {
log.info("Executing JavaCPP Builder");
if (log.isDebugEnabled()) {
log.debug("classPath: " + classPath);
log.debug("classPaths: " + Arrays.deepToString(classPaths));
log.debug("includePath: " + includePath);
log.debug("includePaths: " + Arrays.deepToString(includePaths));
log.debug("linkPath: " + linkPath);
log.debug("linkPaths: " + Arrays.deepToString(linkPaths));
log.debug("preloadPath: " + preloadPath);
log.debug("preloadPaths: " + Arrays.deepToString(preloadPaths));
log.debug("outputDirectory: " + outputDirectory);
log.debug("outputName: " + outputName);
log.debug("compile: " + compile);
log.debug("header: " + header);
log.debug("copyLibs: " + copyLibs);
log.debug("jarPrefix: " + jarPrefix);
log.debug("properties: " + properties);
log.debug("propertyFile: " + propertyFile);
log.debug("propertyKeysAndValues: " + propertyKeysAndValues);
log.debug("classOrPackageName: " + classOrPackageName);
log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames));
log.debug("environmentVariables: " + environmentVariables);
log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions));
log.debug("skip: " + skip);
}
if (skip) {
log.info("Skipped execution of JavaCPP Builder");
return;
}
classPaths = merge(classPaths, classPath);
classOrPackageNames = merge(classOrPackageNames, classOrPackageName);
Logger logger = new Logger() {
@Override public void debug(CharSequence cs) { log.debug(cs); }
@Override public void info (CharSequence cs) { log.info(cs); }
@Override public void warn (CharSequence cs) { log.warn(cs); }
@Override public void error(CharSequence cs) { log.error(cs); }
};
Builder builder = new Builder(logger)
.classPaths(classPaths)
.outputDirectory(outputDirectory)
.outputName(outputName)
.compile(compile)
.header(header)
.copyLibs(copyLibs)
.jarPrefix(jarPrefix)
.properties(properties)
.propertyFile(propertyFile)
.properties(propertyKeysAndValues)
.classesOrPackages(classOrPackageNames)
.environmentVariables(environmentVariables)
.compilerOptions(compilerOptions);
Properties properties = builder.properties;
String separator = properties.getProperty("platform.path.separator");
for (String s : merge(includePaths, includePath)) {
String v = properties.getProperty("platform.includepath", "");
properties.setProperty("platform.includepath",
v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s);
}
for (String s : merge(linkPaths, linkPath)) {
String v = properties.getProperty("platform.linkpath", "");
properties.setProperty("platform.linkpath",
v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s);
}
for (String s : merge(preloadPaths, preloadPath)) {
String v = properties.getProperty("platform.preloadpath", "");
properties.setProperty("platform.preloadpath",
v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s);
}
project.getProperties().putAll(properties);
File[] outputFiles = builder.build();
log.info("Successfully executed JavaCPP Builder");
if (log.isDebugEnabled()) {
log.debug("outputFiles: " + Arrays.deepToString(outputFiles));
}
} catch (Exception e) {
log.error("Failed to execute JavaCPP Builder: " + e.getMessage());
throw new MojoExecutionException("Failed to execute JavaCPP Builder", e);
}
} | #vulnerable code
@Override public void execute() throws MojoExecutionException {
final Log log = getLog();
try {
log.info("Executing JavaCPP Builder");
if (log.isDebugEnabled()) {
log.debug("classPath: " + classPath);
log.debug("classPaths: " + Arrays.deepToString(classPaths));
log.debug("outputDirectory: " + outputDirectory);
log.debug("outputName: " + outputName);
log.debug("compile: " + compile);
log.debug("header: " + header);
log.debug("copyLibs: " + copyLibs);
log.debug("jarPrefix: " + jarPrefix);
log.debug("properties: " + properties);
log.debug("propertyFile: " + propertyFile);
log.debug("propertyKeysAndValues: " + propertyKeysAndValues);
log.debug("classOrPackageName: " + classOrPackageName);
log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames));
log.debug("environmentVariables: " + environmentVariables);
log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions));
log.debug("skip: " + skip);
}
if (skip) {
log.info("Skipped execution of JavaCPP Builder");
return;
}
if (classPaths != null && classPath != null) {
classPaths = Arrays.copyOf(classPaths, classPaths.length + 1);
classPaths[classPaths.length - 1] = classPath;
} else if (classPath != null) {
classPaths = new String[] { classPath };
}
if (classOrPackageNames != null && classOrPackageName != null) {
classOrPackageNames = Arrays.copyOf(classOrPackageNames, classOrPackageNames.length + 1);
classOrPackageNames[classOrPackageNames.length - 1] = classOrPackageName;
} else if (classOrPackageName != null) {
classOrPackageNames = new String[] { classOrPackageName };
}
Logger logger = new Logger() {
@Override public void debug(CharSequence cs) { log.debug(cs); }
@Override public void info (CharSequence cs) { log.info(cs); }
@Override public void warn (CharSequence cs) { log.warn(cs); }
@Override public void error(CharSequence cs) { log.error(cs); }
};
Builder builder = new Builder(logger)
.classPaths(classPaths)
.outputDirectory(outputDirectory)
.outputName(outputName)
.compile(compile)
.header(header)
.copyLibs(copyLibs)
.jarPrefix(jarPrefix)
.properties(properties)
.propertyFile(propertyFile)
.properties(propertyKeysAndValues)
.classesOrPackages(classOrPackageNames)
.environmentVariables(environmentVariables)
.compilerOptions(compilerOptions);
project.getProperties().putAll(builder.properties);
File[] outputFiles = builder.build();
log.info("Successfully executed JavaCPP Builder");
if (log.isDebugEnabled()) {
log.debug("outputFiles: " + Arrays.deepToString(outputFiles));
}
} catch (Exception e) {
log.error("Failed to execute JavaCPP Builder: " + e.getMessage());
throw new MojoExecutionException("Failed to execute JavaCPP Builder", e);
}
}
#location 58
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean generate(String sourceFilename, String headerFilename,
String classPath, Class<?> ... classes) throws IOException {
// first pass using a null writer to fill up the IndexedSet objects
out = new PrintWriter(new Writer() {
@Override public void write(char[] cbuf, int off, int len) { }
@Override public void flush() { }
@Override public void close() { }
});
out2 = null;
callbacks = new IndexedSet<String>();
functions = new IndexedSet<Class>();
deallocators = new IndexedSet<Class>();
arrayDeallocators = new IndexedSet<Class>();
jclasses = new IndexedSet<Class>();
members = new HashMap<Class,Set<String>>();
virtualFunctions = new HashMap<Class,Set<String>>();
virtualMembers = new HashMap<Class,Set<String>>();
annotationCache = new HashMap<Method,MethodInformation>();
mayThrowExceptions = false;
usesAdapters = false;
passesStrings = false;
for (Class<?> cls : baseClasses) {
jclasses.index(cls);
}
if (classes(true, true, true, classPath, classes)) {
// second pass with a real writer
File sourceFile = new File(sourceFilename);
File sourceDir = sourceFile.getParentFile();
if (sourceDir != null) {
sourceDir.mkdirs();
}
out = encoding != null ? new PrintWriter(sourceFile, encoding) : new PrintWriter(sourceFile);
if (headerFilename != null) {
File headerFile = new File(headerFilename);
File headerDir = headerFile.getParentFile();
if (headerDir != null) {
headerDir.mkdirs();
}
out2 = encoding != null ? new PrintWriter(headerFile, encoding) : new PrintWriter(headerFile);
}
return classes(mayThrowExceptions, usesAdapters, passesStrings, classPath, classes);
} else {
return false;
}
} | #vulnerable code
public boolean generate(String sourceFilename, String headerFilename,
String classPath, Class<?> ... classes) throws FileNotFoundException {
// first pass using a null writer to fill up the IndexedSet objects
out = new PrintWriter(new Writer() {
@Override public void write(char[] cbuf, int off, int len) { }
@Override public void flush() { }
@Override public void close() { }
});
out2 = null;
callbacks = new IndexedSet<String>();
functions = new IndexedSet<Class>();
deallocators = new IndexedSet<Class>();
arrayDeallocators = new IndexedSet<Class>();
jclasses = new IndexedSet<Class>();
members = new HashMap<Class,Set<String>>();
virtualFunctions = new HashMap<Class,Set<String>>();
virtualMembers = new HashMap<Class,Set<String>>();
annotationCache = new HashMap<Method,MethodInformation>();
mayThrowExceptions = false;
usesAdapters = false;
passesStrings = false;
for (Class<?> cls : baseClasses) {
jclasses.index(cls);
}
if (classes(true, true, true, classPath, classes)) {
// second pass with a real writer
File sourceFile = new File(sourceFilename);
File sourceDir = sourceFile.getParentFile();
if (sourceDir != null) {
sourceDir.mkdirs();
}
out = new PrintWriter(sourceFile);
if (headerFilename != null) {
File headerFile = new File(headerFilename);
File headerDir = headerFile.getParentFile();
if (headerDir != null) {
headerDir.mkdirs();
}
out2 = new PrintWriter(headerFile);
}
return classes(mayThrowExceptions, usesAdapters, passesStrings, classPath, classes);
} else {
return false;
}
}
#location 32
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
TokenIndexer(InfoMap infoMap, Token[] array, boolean isCFile) {
this.infoMap = infoMap;
this.array = array;
this.isCFile = isCFile;
} | #vulnerable code
Token[] expand(Token[] array, int index) {
if (index < array.length && infoMap.containsKey(array[index].value)) {
// if we hit a token whose info.cppText starts with #define (a macro), expand it
int startIndex = index;
Info info = infoMap.getFirst(array[index].value);
if (info != null && info.cppText != null) {
try {
Tokenizer tokenizer = new Tokenizer(info.cppText, array[index].file, array[index].lineNumber);
if (!tokenizer.nextToken().match('#')
|| !tokenizer.nextToken().match(Token.DEFINE)
|| !tokenizer.nextToken().match(info.cppNames[0])) {
return array;
}
// copy the array of tokens up to this point
List<Token> tokens = new ArrayList<Token>();
for (int i = 0; i < index; i++) {
tokens.add(array[i]);
}
List<String> params = new ArrayList<String>();
List<Token>[] args = null;
Token token = tokenizer.nextToken();
if (info.cppNames[0].equals("__COUNTER__")) {
token.value = Integer.toString(counter++);
}
// pick up the parameters and arguments of the macro if it has any
String name = array[index].value;
if (token.match('(')) {
token = tokenizer.nextToken();
while (!token.isEmpty()) {
if (token.match(Token.IDENTIFIER)) {
params.add(token.value);
} else if (token.match(')')) {
token = tokenizer.nextToken();
break;
}
token = tokenizer.nextToken();
}
index++;
if (params.size() > 0 && (index >= array.length || !array[index].match('('))) {
return array;
}
name += array[index].spacing + array[index];
args = new List[params.size()];
int count = 0, count2 = 0;
for (index++; index < array.length; index++) {
Token token2 = array[index];
name += token2.spacing + token2;
if (count2 == 0 && token2.match(')')) {
break;
} else if (count2 == 0 && token2.match(',')) {
count++;
continue;
} else if (token2.match('(','[','{')) {
count2++;
} else if (token2.match(')',']','}')) {
count2--;
}
if (count < args.length) {
if (args[count] == null) {
args[count] = new ArrayList<Token>();
}
args[count].add(token2);
}
}
// expand the arguments of the macros as well
for (int i = 0; i < args.length; i++) {
if (infoMap.containsKey(args[i].get(0).value)) {
args[i] = Arrays.asList(expand(args[i].toArray(new Token[args[i].size()]), 0));
}
}
}
int startToken = tokens.size();
// expand the token in question, unless we should skip it
info = infoMap.getFirst(name);
while ((info == null || !info.skip) && !token.isEmpty()) {
boolean foundArg = false;
for (int i = 0; i < params.size(); i++) {
if (params.get(i).equals(token.value)) {
String s = token.spacing;
for (Token arg : args[i]) {
// clone tokens here to avoid potential problems with concatenation below
Token t = new Token(arg);
if (s != null) {
t.spacing += s;
}
tokens.add(t);
s = null;
}
foundArg = true;
break;
}
}
if (!foundArg) {
if (token.type == -1) {
token.type = Token.COMMENT;
}
tokens.add(token);
}
token = tokenizer.nextToken();
}
// concatenate tokens as required
for (int i = startToken; i < tokens.size(); i++) {
if (tokens.get(i).match("##") && i > 0 && i + 1 < tokens.size()) {
tokens.get(i - 1).value += tokens.get(i + 1).value;
tokens.remove(i);
tokens.remove(i);
i--;
}
}
// copy the rest of the tokens from this point on
for (index++; index < array.length; index++) {
tokens.add(array[index]);
}
if ((info == null || !info.skip) && startToken < tokens.size()) {
tokens.get(startToken).spacing = array[startIndex].spacing;
}
array = tokens.toArray(new Token[tokens.size()]);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
return array;
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public BytePointer putString(String s, String charsetName)
throws UnsupportedEncodingException {
byte[] bytes = s.getBytes(charsetName);
//capacity(bytes.length+1);
put(bytes).put(bytes.length, (byte)0);
return this;
} | #vulnerable code
public BytePointer putString(String s, String charsetName)
throws UnsupportedEncodingException {
byte[] bytes = s.getBytes(charsetName);
//capacity(bytes.length+1);
asBuffer().put(bytes).put((byte)0);
return this;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public List<Task> assignTasks(TaskTracker taskTracker)
throws IOException {
HttpHost tracker = new HttpHost(taskTracker.getStatus().getHost(),
taskTracker.getStatus().getHttpPort());
if (!mesosTrackers.containsKey(tracker)) {
LOG.info("Unknown/exited TaskTracker: " + tracker + ". ");
return null;
}
MesosTracker mesosTracker = mesosTrackers.get(tracker);
// Make sure we're not asked to assign tasks to any task trackers that have
// been stopped. This could happen while the task tracker has not been
// removed from the cluster e.g still in the heartbeat timeout period.
synchronized (this) {
if (mesosTracker.stopped) {
LOG.info("Asked to assign tasks to stopped tracker " + tracker + ".");
return null;
}
}
// Let the underlying task scheduler do the actual task scheduling.
List<Task> tasks = taskScheduler.assignTasks(taskTracker);
// The Hadoop Fair Scheduler is known to return null.
if (tasks == null) {
return null;
}
// Keep track of which TaskTracker contains which tasks.
for (Task task : tasks) {
mesosTracker.jobs.add(task.getJobID());
}
return tasks;
} | #vulnerable code
@Override
public List<Task> assignTasks(TaskTracker taskTracker)
throws IOException {
HttpHost tracker = new HttpHost(taskTracker.getStatus().getHost(),
taskTracker.getStatus().getHttpPort());
if (!mesosTrackers.containsKey(tracker)) {
LOG.info("Unknown/exited TaskTracker: " + tracker + ". ");
return null;
}
// Let the underlying task scheduler do the actual task scheduling.
List<Task> tasks = taskScheduler.assignTasks(taskTracker);
// The Hadoop Fair Scheduler is known to return null.
if (tasks == null) {
return null;
}
// Keep track of which TaskTracker contains which tasks.
for (Task task : tasks) {
mesosTrackers.get(tracker).jobs.add(task.getJobID());
}
return tasks;
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public <T> T get(String claimName, Class<T> requiredType) {
Object value = get(claimName);
if (value == null) { return null; }
if (Claims.EXPIRATION.equals(claimName) ||
Claims.ISSUED_AT.equals(claimName) ||
Claims.NOT_BEFORE.equals(claimName)
) {
value = getDate(claimName);
}
return castClaimValue(value, requiredType);
} | #vulnerable code
@Override
public <T> T get(String claimName, Class<T> requiredType) {
Object value = get(claimName);
if (value == null) { return null; }
if (Claims.EXPIRATION.equals(claimName) ||
Claims.ISSUED_AT.equals(claimName) ||
Claims.NOT_BEFORE.equals(claimName)
) {
value = getDate(claimName);
}
if (requiredType == Date.class && value instanceof Long) {
value = new Date((Long)value);
}
if (!requiredType.isInstance(value)) {
throw new RequiredTypeException("Expected value to be of type: " + requiredType + ", but was " + value.getClass());
}
return requiredType.cast(value);
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected byte[] doDecompress(byte[] compressed) throws IOException {
return readAndClose(new GZIPInputStream(new ByteArrayInputStream(compressed)));
} | #vulnerable code
@Override
protected byte[] doDecompress(byte[] compressed) throws IOException {
byte[] buffer = new byte[512];
ByteArrayOutputStream outputStream = null;
GZIPInputStream gzipInputStream = null;
ByteArrayInputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(compressed);
gzipInputStream = new GZIPInputStream(inputStream);
outputStream = new ByteArrayOutputStream();
int read = gzipInputStream.read(buffer);
while (read != -1) {
outputStream.write(buffer, 0, read);
read = gzipInputStream.read(buffer);
}
return outputStream.toByteArray();
} finally {
Objects.nullSafeClose(inputStream, gzipInputStream, outputStream);
}
}
#location 20
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public boolean updateRule(@PathVariable String id, @RequestBody RouteDTO routeDTO, @PathVariable String env) {
Route route = routeService.findRoute(id);
if (route == null) {
throw new ResourceNotFoundException("Unknown ID!");
}
routeDTO.setVersion(route.getVersion());
routeDTO.setService(route.getService());
Route newRoute = convertRouteDTOtoRoute(routeDTO, id);
routeService.updateRoute(newRoute);
return true;
} | #vulnerable code
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public boolean updateRule(@PathVariable String id, @RequestBody RouteDTO routeDTO, @PathVariable String env) {
Route route = routeService.findRoute(id);
if (route == null) {
//TODO Exception
}
routeDTO.setVersion(route.getVersion());
routeDTO.setService(route.getService());
Route newRoute = convertRouteDTOtoRoute(routeDTO, id);
routeService.updateRoute(newRoute);
return true;
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public RouteDTO detailRoute(@PathVariable String id, @PathVariable String env) {
Route route = routeService.findRoute(id);
if (route == null) {
// TODO throw exception
}
RouteDTO routeDTO = convertRoutetoRouteDTO(route, id);
return routeDTO;
} | #vulnerable code
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public RouteDTO detailRoute(@PathVariable String id, @PathVariable String env) {
Route route = routeService.findRoute(id);
if (route == null) {
// TODO throw exception
}
RouteDTO routeDTO = new RouteDTO();
routeDTO.setDynamic(route.isDynamic());
routeDTO.setConditions(new String[]{route.getRule()});
routeDTO.setEnabled(route.isEnabled());
routeDTO.setForce(route.isForce());
routeDTO.setGroup(route.getGroup());
routeDTO.setPriority(route.getPriority());
routeDTO.setRuntime(route.isRuntime());
routeDTO.setService(route.getService());
routeDTO.setId(route.getHash());
return routeDTO;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public RouteDTO detailRoute(@PathVariable String id, @PathVariable String env) {
Route route = routeService.findRoute(id);
if (route == null) {
throw new ResourceNotFoundException("Unknown ID!");
}
RouteDTO routeDTO = convertRoutetoRouteDTO(route, id);
return routeDTO;
} | #vulnerable code
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public RouteDTO detailRoute(@PathVariable String id, @PathVariable String env) {
Route route = routeService.findRoute(id);
if (route == null) {
// TODO throw exception
}
RouteDTO routeDTO = convertRoutetoRouteDTO(route, id);
return routeDTO;
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public OverrideDTO detailOverride(@PathVariable String id, @PathVariable String env) {
Override override = overrideService.findById(id);
if (override == null) {
throw new ResourceNotFoundException("Unknown ID!");
}
OverrideDTO overrideDTO = new OverrideDTO();
overrideDTO.setAddress(override.getAddress());
overrideDTO.setApp(override.getApplication());
overrideDTO.setEnabled(override.isEnabled());
overrideDTO.setService(override.getService());
paramsToOverrideDTO(override, overrideDTO);
return overrideDTO;
} | #vulnerable code
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public OverrideDTO detailOverride(@PathVariable String id, @PathVariable String env) {
Override override = overrideService.findById(id);
if (override == null) {
//TODO throw exception
}
OverrideDTO overrideDTO = new OverrideDTO();
overrideDTO.setAddress(override.getAddress());
overrideDTO.setApp(override.getApplication());
overrideDTO.setEnabled(override.isEnabled());
overrideDTO.setService(override.getService());
paramsToOverrideDTO(override, overrideDTO);
return overrideDTO;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void addToWindow(Datum newDatum) {
if (window.size() == 0) {
// We don't know what weight to use for the first datum, so we wait
// until we have the second one to actually process it.
window.add(new DatumWithInfo(newDatum, 0));
} else {
int weight = newDatum.getTime(timeColumn) - getLatestDatum().getTime(timeColumn);
if (window.size() == 1) {
windowSum = new ArrayRealVector(newDatum.getMetrics()
.getDimension());
// Remove and re-add first datum with the correct weight
Datum first = window.remove().getDatum();
// Assume same weight for first as for second
addDatumWithWeight(first, weight);
}
addDatumWithWeight(newDatum, weight);
}
} | #vulnerable code
@Override
public void addToWindow(Datum newDatum) {
if (window.size() == 0) {
// We don't know what weight to use for the first datum, so we wait
// until we have the second one to actually process it.
window.add(new DatumWithInfo(newDatum, 0));
} else {
int weight = newDatum.getTime() - getLatestDatum().getTime();
if (window.size() == 1) {
windowSum = new ArrayRealVector(newDatum.getMetrics()
.getDimension());
// Remove and re-add first datum with the correct weight
Datum first = window.remove().getDatum();
// Assume same weight for first as for second
addDatumWithWeight(first, weight);
}
addDatumWithWeight(newDatum, weight);
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testDumpSmall() throws Exception {
MacroBaseConf conf = new MacroBaseConf();
ArrayList<Integer> attrs = new ArrayList<>();
attrs.add(1);
attrs.add(2);
OutlierClassifier dummy = new OutlierClassifier() {
MBStream<OutlierClassificationResult> result = new MBStream<>();
@Override
public MBStream<OutlierClassificationResult> getStream() throws Exception {
return result;
}
@Override
public void initialize() throws Exception {
}
@Override
public void consume(List<Datum> records) throws Exception {
for(Datum r : records) {
result.add(new OutlierClassificationResult(r, true));
}
}
@Override
public void shutdown() throws Exception {
}
};
File f = folder.newFile("testDumpSmall");
DumpClassifier dumper = new DumpClassifier(conf, dummy, f.getAbsolutePath());
List<Datum> data = new ArrayList<>();
data.add(new Datum(attrs, new ArrayRealVector()));
data.add(new Datum(attrs, new ArrayRealVector()));
dumper.consume(data);
List<OutlierClassificationResult> results = dumper.getStream().drain();
dumper.shutdown();
assertEquals(results.size(), data.size());
OutlierClassificationResult first = results.get(0);
assertEquals(true, first.isOutlier());
assertEquals(1, first.getDatum().getAttributes().get(0).intValue());
Path filePath = Paths.get(dumper.getFilePath());
assertTrue(Files.exists(filePath));
Files.deleteIfExists(Paths.get(dumper.getFilePath()));
} | #vulnerable code
@Test
public void testDumpSmall() throws Exception {
MacroBaseConf conf = new MacroBaseConf();
ArrayList<Integer> attrs = new ArrayList<>();
attrs.add(1);
attrs.add(2);
OutlierClassifier dummy = new OutlierClassifier() {
MBStream<OutlierClassificationResult> result = new MBStream<>();
@Override
public MBStream<OutlierClassificationResult> getStream() throws Exception {
return result;
}
@Override
public void initialize() throws Exception {
}
@Override
public void consume(List<Datum> records) throws Exception {
for(Datum r : records) {
result.add(new OutlierClassificationResult(r, true));
}
}
@Override
public void shutdown() throws Exception {
}
};
File f = folder.newFile("testDumpSmall");
DumpClassifier dumper = new DumpClassifier(conf, dummy, f.getAbsolutePath());
List<Datum> data = new ArrayList<>();
data.add(new Datum(attrs, new ArrayRealVector()));
data.add(new Datum(attrs, new ArrayRealVector()));
dumper.consume(data);
List<OutlierClassificationResult> results = dumper.getStream().drain();
assertEquals(results.size(), data.size());
OutlierClassificationResult first = results.get(0);
assertEquals(true, first.isOutlier());
assertEquals(1, first.getDatum().getAttributes().get(0).intValue());
Path filePath = Paths.get(dumper.getFilePath());
assertTrue(Files.exists(filePath));
Files.deleteIfExists(Paths.get(dumper.getFilePath()));
}
#location 52
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public List<AnalysisResult> run() throws Exception {
final int batchSize = conf.getInt(MacroBaseConf.TUPLE_BATCH_SIZE,
MacroBaseDefaults.TUPLE_BATCH_SIZE);
Stopwatch sw = Stopwatch.createStarted();
DataIngester ingester = conf.constructIngester();
List<Datum> data = ingester.getStream().drain();
System.gc();
final long loadMs = sw.elapsed(TimeUnit.MILLISECONDS);
MBStream<Datum> streamData = new MBStream<>(data);
Summarizer summarizer = new EWStreamingSummarizer(conf);
MBOperator<Datum, Summary> pipeline =
new EWFeatureTransform(conf)
.then(new EWAppxPercentileOutlierClassifier(conf), batchSize)
.then(summarizer, batchSize);
while(streamData.remaining() > 0) {
pipeline.consume(streamData.drain(batchSize));
}
Summary result = summarizer.summarize().getStream().drain().get(0);
final long totalMs = sw.elapsed(TimeUnit.MILLISECONDS) - loadMs;
final long summarizeMs = result.getCreationTimeMs();
final long executeMs = totalMs - result.getCreationTimeMs();
log.info("took {}ms ({} tuples/sec)",
totalMs,
(result.getNumInliers()+result.getNumOutliers())/(double)totalMs*1000);
return Arrays.asList(new AnalysisResult(result.getNumOutliers(),
result.getNumInliers(),
loadMs,
executeMs,
summarizeMs,
result.getItemsets()));
} | #vulnerable code
@Override
public List<AnalysisResult> run() throws Exception {
final int batchSize = conf.getInt(MacroBaseConf.TUPLE_BATCH_SIZE,
MacroBaseDefaults.TUPLE_BATCH_SIZE);
Stopwatch sw = Stopwatch.createStarted();
DataIngester ingester = conf.constructIngester();
List<Datum> data = ingester.getStream().drain();
System.gc();
final long loadMs = sw.elapsed(TimeUnit.MILLISECONDS);
MBStream<Datum> streamData = new MBStream<>(data);
MBOperator<Datum, OutlierClassificationResult> ocr =
new EWFeatureTransform(conf)
.then(new EWAppxPercentileOutlierClassifier(conf), batchSize);
while(streamData.remaining() > 0) {
ocr.consume(streamData.drain(batchSize));
}
MBStream<OutlierClassificationResult> ocrs = ocr.getStream();
Summarizer summarizer = new EWStreamingSummarizer(conf);
summarizer.consume(ocrs.drain());
Summary result = summarizer.getStream().drain().get(0);
final long totalMs = sw.elapsed(TimeUnit.MILLISECONDS) - loadMs;
final long summarizeMs = result.getCreationTimeMs();
final long executeMs = totalMs - result.getCreationTimeMs();
log.info("took {}ms ({} tuples/sec)",
totalMs,
(result.getNumInliers()+result.getNumOutliers())/(double)totalMs*1000);
return Arrays.asList(new AnalysisResult(result.getNumOutliers(),
result.getNumInliers(),
loadMs,
executeMs,
summarizeMs,
result.getItemsets()));
}
#location 27
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@POST
@Consumes(MediaType.APPLICATION_JSON)
public FormattedRowSetResponse getRowsFormatted(RowSetRequest request) {
FormattedRowSetResponse response = new FormattedRowSetResponse();
try {
conf.set(MacroBaseConf.DB_URL, request.pgUrl);
conf.set(MacroBaseConf.BASE_QUERY, request.baseQuery);
HashMap<String, String> preds = new HashMap<>();
request.columnValues.stream().forEach(a -> preds.put(a.column, a.value));
if(request.returnType == RETURNTYPE.SQL) {
response.response = ((SQLIngester) getLoader()).getRowsSql(request.baseQuery,
preds,
request.limit,
request.offset)+";";
return response;
}
RowSet r = getLoader().getRows(request.baseQuery,
preds,
request.limit,
request.offset);
if (request.returnType == RETURNTYPE.JSON) {
response.response = new ObjectMapper().writeValueAsString(r);
} else {
assert (request.returnType == RETURNTYPE.CSV);
StringWriter sw = new StringWriter();
CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
if(r.getRows().isEmpty()) {
printer.printRecord(preds.keySet());
} else {
printer.printRecord(r.getRows().get(0).getColumnValues().stream().map(a -> a.getColumn()).toArray());
for (RowSet.Row row : r.getRows()) {
printer.printRecord(row.getColumnValues().stream().map(a -> a.getValue()).toArray());
}
}
response.response = sw.toString();
}
} catch (Exception e) {
log.error("An error occurred while processing a request:", e);
response.errorMessage = ExceptionUtils.getStackTrace(e);
}
return response;
} | #vulnerable code
@POST
@Consumes(MediaType.APPLICATION_JSON)
public FormattedRowSetResponse getRowsFormatted(RowSetRequest request) {
FormattedRowSetResponse response = new FormattedRowSetResponse();
try {
conf.set(MacroBaseConf.DB_URL, request.pgUrl);
conf.set(MacroBaseConf.BASE_QUERY, request.baseQuery);
HashMap<String, String> preds = new HashMap<>();
request.columnValues.stream().forEach(a -> preds.put(a.column, a.value));
if(request.returnType == RETURNTYPE.SQL) {
response.response = getLoader().getRowsSql(request.baseQuery,
preds,
request.limit,
request.offset)+";";
return response;
}
RowSet r = getLoader().getRows(request.baseQuery,
preds,
request.limit,
request.offset);
if (request.returnType == RETURNTYPE.JSON) {
response.response = new ObjectMapper().writeValueAsString(r);
} else {
assert (request.returnType == RETURNTYPE.CSV);
StringWriter sw = new StringWriter();
CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
if(r.getRows().isEmpty()) {
printer.printRecord(preds.keySet());
} else {
printer.printRecord(r.getRows().get(0).getColumnValues().stream().map(a -> a.getColumn()).toArray());
for (RowSet.Row row : r.getRows()) {
printer.printRecord(row.getColumnValues().stream().map(a -> a.getValue()).toArray());
}
}
response.response = sw.toString();
}
} catch (Exception e) {
log.error("An error occurred while processing a request:", e);
response.errorMessage = ExceptionUtils.getStackTrace(e);
}
return response;
}
#location 38
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@POST
@Consumes(MediaType.APPLICATION_JSON)
public FormattedRowSetResponse getRowsFormatted(RowSetRequest request) {
FormattedRowSetResponse response = new FormattedRowSetResponse();
try {
conf.set(MacroBaseConf.DB_URL, request.pgUrl);
conf.set(MacroBaseConf.BASE_QUERY, request.baseQuery);
HashMap<String, String> preds = new HashMap<>();
request.columnValues.stream().forEach(a -> preds.put(a.column, a.value));
if(request.returnType == RETURNTYPE.SQL) {
response.response = ((SQLIngester) getLoader()).getRowsSql(request.baseQuery,
preds,
request.limit,
request.offset)+";";
return response;
}
RowSet r = getLoader().getRows(request.baseQuery,
preds,
request.limit,
request.offset);
if (request.returnType == RETURNTYPE.JSON) {
response.response = new ObjectMapper().writeValueAsString(r);
} else {
assert (request.returnType == RETURNTYPE.CSV);
StringWriter sw = new StringWriter();
CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
if(r.getRows().isEmpty()) {
printer.printRecord(preds.keySet());
} else {
printer.printRecord(r.getRows().get(0).getColumnValues().stream().map(a -> a.getColumn()).toArray());
for (RowSet.Row row : r.getRows()) {
printer.printRecord(row.getColumnValues().stream().map(a -> a.getValue()).toArray());
}
}
response.response = sw.toString();
}
} catch (Exception e) {
log.error("An error occurred while processing a request:", e);
response.errorMessage = ExceptionUtils.getStackTrace(e);
}
return response;
} | #vulnerable code
@POST
@Consumes(MediaType.APPLICATION_JSON)
public FormattedRowSetResponse getRowsFormatted(RowSetRequest request) {
FormattedRowSetResponse response = new FormattedRowSetResponse();
try {
conf.set(MacroBaseConf.DB_URL, request.pgUrl);
conf.set(MacroBaseConf.BASE_QUERY, request.baseQuery);
HashMap<String, String> preds = new HashMap<>();
request.columnValues.stream().forEach(a -> preds.put(a.column, a.value));
if(request.returnType == RETURNTYPE.SQL) {
response.response = getLoader().getRowsSql(request.baseQuery,
preds,
request.limit,
request.offset)+";";
return response;
}
RowSet r = getLoader().getRows(request.baseQuery,
preds,
request.limit,
request.offset);
if (request.returnType == RETURNTYPE.JSON) {
response.response = new ObjectMapper().writeValueAsString(r);
} else {
assert (request.returnType == RETURNTYPE.CSV);
StringWriter sw = new StringWriter();
CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
if(r.getRows().isEmpty()) {
printer.printRecord(preds.keySet());
} else {
printer.printRecord(r.getRows().get(0).getColumnValues().stream().map(a -> a.getColumn()).toArray());
for (RowSet.Row row : r.getRows()) {
printer.printRecord(row.getColumnValues().stream().map(a -> a.getValue()).toArray());
}
}
response.response = sw.toString();
}
} catch (Exception e) {
log.error("An error occurred while processing a request:", e);
response.errorMessage = ExceptionUtils.getStackTrace(e);
}
return response;
}
#location 35
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public AnalysisResult run() throws Exception {
long startMs = System.currentTimeMillis();
DataIngester ingester = conf.constructIngester();
List<Datum> data = ingester.getStream().drain();
long loadEndMs = System.currentTimeMillis();
MBStream<OutlierClassificationResult> ocrs =
MBOperatorChain.begin(data)
.then(new EWFeatureTransform(conf))
.then(new EWAppxPercentileOutlierClassifier(conf)).executeMiniBatchUntilFixpoint(1000);
Summarizer summarizer = new EWStreamingSummarizer(conf);
summarizer.consume(ocrs.drain());
Summary result = summarizer.getStream().drain().get(0);
final long endMs = System.currentTimeMillis();
final long loadMs = loadEndMs - startMs;
final long totalMs = endMs - loadEndMs;
final long summarizeMs = result.getCreationTimeMs();
final long executeMs = totalMs - result.getCreationTimeMs();
log.info("took {}ms ({} tuples/sec)",
totalMs,
(result.getNumInliers()+result.getNumOutliers())/(double)totalMs*1000);
return new AnalysisResult(result.getNumOutliers(),
result.getNumInliers(),
loadMs,
executeMs,
summarizeMs,
result.getItemsets());
} | #vulnerable code
@Override
public AnalysisResult run() throws Exception {
long startMs = System.currentTimeMillis();
DataIngester ingester = conf.constructIngester();
List<Datum> data = ingester.getStream().drain();
long loadEndMs = System.currentTimeMillis();
FeatureTransform featureTransform = new EWFeatureTransform(conf);
featureTransform.consume(ingester.getStream().drain());
OutlierClassifier outlierClassifier = new EWAppxPercentileOutlierClassifier(conf);
outlierClassifier.consume(featureTransform.getStream().drain());
Summarizer summarizer = new EWStreamingSummarizer(conf);
summarizer.consume(outlierClassifier.getStream().drain());
Summary result = summarizer.getStream().drain().get(0);
final long endMs = System.currentTimeMillis();
final long loadMs = loadEndMs - startMs;
final long totalMs = endMs - loadEndMs;
final long summarizeMs = result.getCreationTimeMs();
final long executeMs = totalMs - result.getCreationTimeMs();
log.info("took {}ms ({} tuples/sec)",
totalMs,
(result.getNumInliers()+result.getNumOutliers())/(double)totalMs*1000);
return new AnalysisResult(result.getNumOutliers(),
result.getNumInliers(),
loadMs,
executeMs,
summarizeMs,
result.getItemsets());
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldHandleErrorResponse() throws Exception {
//given
final HttpResponse errorResponse = new HttpResponse(401, "{\n" +
" \"error\": {\n" +
" \"message\": \"Invalid OAuth access token.\",\n" +
" \"type\": \"OAuthException\",\n" +
" \"code\": 190,\n" +
" \"fbtrace_id\": \"BLBz/WZt8dN\"\n" +
" }\n" +
"}");
when(mockHttpClient.execute(eq(GET), anyString(), isNull())).thenReturn(errorResponse);
//when
MessengerApiException messengerApiException = null;
try {
messenger.queryUserProfileById("USER_ID");
} catch (MessengerApiException e) {
messengerApiException = e;
}
//then
assertThat(messengerApiException, is(notNullValue()));
assertThat(messengerApiException.getMessage(), is(equalTo("Invalid OAuth access token.")));
assertThat(messengerApiException.getType(), is(equalTo("OAuthException")));
assertThat(messengerApiException.getCode(), is(equalTo(190)));
assertThat(messengerApiException.getFbTraceId(), is(equalTo("BLBz/WZt8dN")));
} | #vulnerable code
@Test
public void shouldHandleErrorResponse() throws Exception {
//given
final HttpResponse errorResponse = new HttpResponse(401, "{\n" +
" \"error\": {\n" +
" \"message\": \"Invalid OAuth access token.\",\n" +
" \"type\": \"OAuthException\",\n" +
" \"code\": 190,\n" +
" \"fbtrace_id\": \"BLBz/WZt8dN\"\n" +
" }\n" +
"}");
when(mockHttpClient.execute(eq(GET), anyString(), (String) isNull())).thenReturn(errorResponse);
//when
MessengerApiException messengerApiException = null;
try {
this.userProfileClient.queryUserProfile("USER_ID");
} catch (MessengerApiException e) {
messengerApiException = e;
}
//then
assertThat(messengerApiException, is(notNullValue()));
assertThat(messengerApiException.getMessage(), is(equalTo("Invalid OAuth access token.")));
assertThat(messengerApiException.getType(), is(equalTo("OAuthException")));
assertThat(messengerApiException.getCode(), is(equalTo(190)));
assertThat(messengerApiException.getFbTraceId(), is(equalTo("BLBz/WZt8dN")));
}
#location 24
#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 Exception {
if (args.length < 1){
System.out.println("usage: <index location> <command> <command args>");
System.exit(1);
}
String idxLocation = args[0];
ClueApplication app = null;
if (args.length > 1){
String cmd = args[1];
if ("readonly".equalsIgnoreCase(cmd)) {
if (args.length > 2) {
cmd = args[2];
app = new ClueApplication(idxLocation, false);
String[] cmdArgs;
cmdArgs = new String[args.length - 3];
System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length);
app.ctx.setReadOnlyMode(true);
app.handleCommand(cmd, cmdArgs, System.out);
}
}
else {
app = new ClueApplication(idxLocation, false);
String[] cmdArgs;
cmdArgs = new String[args.length - 2];
System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length);
app.handleCommand(cmd, cmdArgs, System.out);
}
return;
}
app = new ClueApplication(idxLocation, true);
BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print("> ");
String line = inReader.readLine().trim();
if (line.isEmpty()) continue;
String[] parts = line.split("\\s");
if (parts.length > 0){
String cmd = parts[0];
String[] cmdArgs = new String[parts.length - 1];
System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length);
app.handleCommand(cmd, cmdArgs, System.out);
}
}
} | #vulnerable code
public static void main(String[] args) throws Exception {
if (args.length < 1){
System.out.println("usage: <index location> <command> <command args>");
System.exit(1);
}
String idxLocation = args[0];
ClueApplication app = null;
if (args.length > 1){
app = new ClueApplication(idxLocation, false);
String cmd = args[1];
String[] cmdArgs;
cmdArgs = new String[args.length - 2];
System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length);
app.handleCommand(cmd, cmdArgs, System.out);
}
else{
app = new ClueApplication(idxLocation, true);
BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print("> ");
String line = inReader.readLine().trim();
if (line.isEmpty()) continue;
String[] parts = line.split("\\s");
if (parts.length > 0){
String cmd = parts[0];
String[] cmdArgs = new String[parts.length - 1];
System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length);
app.handleCommand(cmd, cmdArgs, System.out);
}
}
}
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void run() throws IOException {
while(true){
System.out.print("> ");
String line = ctx.readCommand();
if (line == null || line.isEmpty()) continue;
line = line.trim();
String[] parts = line.split("\\s");
if (parts.length > 0){
String cmd = parts[0];
String[] cmdArgs = new String[parts.length - 1];
System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length);
handleCommand(cmd, cmdArgs, System.out);
}
}
} | #vulnerable code
public void run() throws IOException {
BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print("> ");
String line = inReader.readLine();
if (line == null || line.isEmpty()) continue;
line = line.trim();
String[] parts = line.split("\\s");
if (parts.length > 0){
String cmd = parts[0];
String[] cmdArgs = new String[parts.length - 1];
System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length);
handleCommand(cmd, cmdArgs, System.out);
}
}
}
#location 14
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void execute(String[] args, PrintStream out) throws Exception {
String field = null;
String termVal = null;
try{
field = args[0];
}
catch(Exception e){
field = null;
}
if (field != null){
String[] parts = field.split(":");
if (parts.length > 1){
field = parts[0];
termVal = parts[1];
}
}
IndexReader reader = ctx.getIndexReader();
List<AtomicReaderContext> leaves = reader.leaves();
TreeMap<BytesRef,TermsEnum> termMap = null;
HashMap<BytesRef,AtomicInteger> termCountMap = new HashMap<BytesRef,AtomicInteger>();
for (AtomicReaderContext leaf : leaves){
AtomicReader atomicReader = leaf.reader();
if (field == null){
continue;
}
Terms terms = atomicReader.fields().terms(field);
if (terms == null) {
continue;
}
if (termMap == null){
termMap = new TreeMap<BytesRef,TermsEnum>(terms.getComparator());
}
TermsEnum te = terms.iterator(null);
BytesRef termBytes;
if (termVal != null){
te.seekCeil(new BytesRef(termVal));
termBytes = te.term();
}
else{
termBytes = te.next();
}
while(true){
if (termBytes == null) break;
AtomicInteger count = termCountMap.get(termBytes);
if (count == null){
termCountMap.put(termBytes, new AtomicInteger(te.docFreq()));
termMap.put(termBytes, te);
break;
}
count.getAndAdd(te.docFreq());
termBytes = te.next();
}
}
while(termMap != null && !termMap.isEmpty()){
Entry<BytesRef,TermsEnum> entry = termMap.pollFirstEntry();
if (entry == null) break;
BytesRef key = entry.getKey();
AtomicInteger count = termCountMap.remove(key);
out.println(key.utf8ToString()+" ("+count+") ");
TermsEnum te = entry.getValue();
BytesRef nextKey = te.next();
while(true){
if (nextKey == null) break;
count = termCountMap.get(nextKey);
if (count == null){
termCountMap.put(nextKey, new AtomicInteger(te.docFreq()));
termMap.put(nextKey, te);
break;
}
count.getAndAdd(te.docFreq());
nextKey = te.next();
}
}
out.flush();
} | #vulnerable code
@Override
public void execute(String[] args, PrintStream out) throws Exception {
String field = null;
String termVal = null;
try{
field = args[0];
}
catch(Exception e){
field = null;
}
if (field != null){
String[] parts = field.split(":");
if (parts.length > 1){
field = parts[0];
termVal = parts[1];
}
}
IndexReader reader = ctx.getIndexReader();
List<AtomicReaderContext> leaves = reader.leaves();
TreeMap<BytesRef,TermsEnum> termMap = null;
HashMap<BytesRef,AtomicInteger> termCountMap = new HashMap<BytesRef,AtomicInteger>();
for (AtomicReaderContext leaf : leaves){
AtomicReader atomicReader = leaf.reader();
Terms terms = atomicReader.fields().terms(field);
if (terms == null) {
continue;
}
if (termMap == null){
termMap = new TreeMap<BytesRef,TermsEnum>(terms.getComparator());
}
TermsEnum te = terms.iterator(null);
BytesRef termBytes;
if (termVal != null){
te.seekCeil(new BytesRef(termVal));
termBytes = te.term();
}
else{
termBytes = te.next();
}
while(true){
if (termBytes == null) break;
AtomicInteger count = termCountMap.get(termBytes);
if (count == null){
termCountMap.put(termBytes, new AtomicInteger(te.docFreq()));
termMap.put(termBytes, te);
break;
}
count.getAndAdd(te.docFreq());
termBytes = te.next();
}
}
while(!termMap.isEmpty()){
Entry<BytesRef,TermsEnum> entry = termMap.pollFirstEntry();
if (entry == null) break;
BytesRef key = entry.getKey();
AtomicInteger count = termCountMap.remove(key);
out.println(key.utf8ToString()+" ("+count+") ");
TermsEnum te = entry.getValue();
BytesRef nextKey = te.next();
while(true){
if (nextKey == null) break;
count = termCountMap.get(nextKey);
if (count == null){
termCountMap.put(nextKey, new AtomicInteger(te.docFreq()));
termMap.put(nextKey, te);
break;
}
count.getAndAdd(te.docFreq());
nextKey = te.next();
}
}
out.flush();
}
#location 61
#vulnerability type NULL_DEREFERENCE | 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.