instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code 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 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 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 @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 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 @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 @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 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 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 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 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 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 @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 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 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 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 public static int sizeof(Class<? extends Pointer> type) { return offsetof(type, "sizeof"); }
#vulnerable code public static int sizeof(Class<? extends Pointer> type) { // Should we synchronize that? return memberOffsets.get(type).get("sizeof"); } #location 3 #vulnerability type NULL_DEREFERENCE
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 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 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 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 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 @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 64 #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; 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 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 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 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 @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 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 @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 public ColumnValue getAttribute(int encodedAttr) { int matchingColumn = integerToColumn.get(encodedAttr); String columnName = attributeDimensionNameMap.get(matchingColumn); Map<String, Integer> columnEncoding = integerEncoding.get(matchingColumn); String columnValue = null; for(Map.Entry<String, Integer> ce : columnEncoding.entrySet()) { if(ce.getValue() == encodedAttr) { columnValue = ce.getKey(); } } return new ColumnValue(columnName, columnValue); }
#vulnerable code public ColumnValue getAttribute(int encodedAttr) { int matchingColumn = integerToColumn.get(encodedAttr); String columnName = attributeDimensionNameMap.get(matchingColumn); String columnValue = integerEncoding.get(matchingColumn).inverse().get(encodedAttr); return new ColumnValue(columnName, columnValue); } #location 5 #vulnerability type NULL_DEREFERENCE
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 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 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void printScreen() { if (error == null || error || !error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } }
#vulnerable code public static void printScreen() { if (error != null && error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void buildSysGenProfilingFile() { long startMills = System.currentTimeMillis(); String filePath = ProfilingConfig.getInstance().getSysProfilingParamsFile(); String tempFilePath = filePath + "_tmp"; File tempFile = new File(tempFilePath); try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(tempFile, false), 8 * 1024)) { fileWriter.write("#This is a file automatically generated by MyPerf4J, please do not edit!\n"); MethodTagMaintainer tagMaintainer = MethodTagMaintainer.getInstance(); Map<Integer, MethodMetricsInfo> methodMap = MethodMetricsHistogram.methodMap; for (Map.Entry<Integer, MethodMetricsInfo> entry : methodMap.entrySet()) { Integer methodId = entry.getKey(); MethodMetricsInfo info = entry.getValue(); if (info.getCount() <= 0) { continue; } MethodTag methodTag = tagMaintainer.getMethodTag(methodId); fileWriter.write(methodTag.getFullDesc()); fileWriter.write('='); int mostTimeThreshold = calMostTimeThreshold(info); fileWriter.write(mostTimeThreshold + ":" + calOutThresholdCount(mostTimeThreshold)); fileWriter.newLine(); } fileWriter.flush(); File destFile = new File(filePath); boolean rename = tempFile.renameTo(destFile) && destFile.setReadOnly(); Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile(): rename " + tempFile.getName() + " to " + destFile.getName() + " " + (rename ? "success" : "fail")); } catch (Exception e) { Logger.error("MethodMetricsHistogram.buildSysGenProfilingFile()", e); } finally { Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile() finished, cost=" + (System.currentTimeMillis() - startMills) + "ms"); } }
#vulnerable code public static void buildSysGenProfilingFile() { long startMills = System.currentTimeMillis(); String filePath = ProfilingConfig.getInstance().getSysProfilingParamsFile(); String tempFilePath = filePath + "_tmp"; File tempFile = new File(tempFilePath); try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(tempFile, false), 8 * 1024)) { fileWriter.write("#This is a file automatically generated by MyPerf4J, please do not edit!\n"); MethodTagMaintainer tagMaintainer = MethodTagMaintainer.getInstance(); Map<Integer, MethodMetricsInfo> methodMap = MethodMetricsHistogram.methodMap; for (Map.Entry<Integer, MethodMetricsInfo> entry : methodMap.entrySet()) { Integer methodId = entry.getKey(); MethodMetricsInfo info = entry.getValue(); if (info.getCount() <= 0) { continue; } MethodTag methodTag = tagMaintainer.getMethodTag(methodId); fileWriter.write(methodTag.getFullDesc()); fileWriter.write('='); int mostTimeThreshold = calMostTimeThreshold(info); fileWriter.write(mostTimeThreshold + ":" + calOutThresholdCount(mostTimeThreshold)); fileWriter.newLine(); } fileWriter.flush(); File destFile = new File(filePath); boolean rename = tempFile.renameTo(destFile); Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile(): rename " + tempFile.getName() + " to " + destFile.getName() + " " + (rename ? "success" : "fail")); } catch (Exception e) { Logger.error("MethodMetricsHistogram.buildSysGenProfilingFile()", e); } finally { Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile() finished, cost=" + (System.currentTimeMillis() - startMills) + "ms"); } } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void authenticationStepsShouldAuthenticatePushModeWithProvidedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = "hello_world_two"; VaultResponse customSecretIdResponse = getVaultOperations().write( "auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId)); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(RoleId.provided(roleId)).secretId(SecretId.provided(secretId)) .build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( AppRoleAuthentication.createAuthenticationSteps(options), prepare() .getRestTemplate()); assertThat(executor.login()).isNotNull(); getVaultOperations().write( "auth/approle/role/with-secret-id/secret-id-accessor/destroy", customSecretIdResponse.getRequiredData()); }
#vulnerable code @Test void authenticationStepsShouldAuthenticatePushModeWithProvidedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = "hello_world_two"; VaultResponse customSecretIdResponse = getVaultOperations().write( "auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId)); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(roleId).secretId(secretId).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( AppRoleAuthentication.createAuthenticationSteps(options), prepare() .getRestTemplate()); assertThat(executor.login()).isNotNull(); getVaultOperations().write( "auth/approle/role/with-secret-id/secret-id-accessor/destroy", customSecretIdResponse.getRequiredData()); } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") private Lease renew(Lease lease) { return operations.doWithSession(restOperations -> leaseEndpoints.renew(lease, restOperations)); }
#vulnerable code @SuppressWarnings("unchecked") private Lease renew(Lease lease) { HttpEntity<Object> leaseRenewalEntity = getLeaseRenewalBody(lease); ResponseEntity<Map<String, Object>> entity = operations .doWithSession(restOperations -> (ResponseEntity) restOperations .exchange("sys/renew", HttpMethod.PUT, leaseRenewalEntity, Map.class)); Assert.state(entity != null && entity.getBody() != null, "Renew response must not be null"); Map<String, Object> body = entity.getBody(); String leaseId = (String) body.get("lease_id"); Number leaseDuration = (Number) body.get("lease_duration"); boolean renewable = (Boolean) body.get("renewable"); return Lease.of(leaseId, leaseDuration != null ? leaseDuration.longValue() : 0, renewable); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override @SuppressWarnings("unchecked") public boolean isInitialized() { return requireResponse(vaultOperations.doWithSession(restOperations -> { try { ResponseEntity<Map<String, Boolean>> body = (ResponseEntity) restOperations .exchange("sys/init", HttpMethod.GET, emptyNamespace(null), Map.class); Assert.state(body.getBody() != null, "Initialization response must not be null"); return body.getBody().get("initialized"); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); } })); }
#vulnerable code @Override @SuppressWarnings("unchecked") public boolean isInitialized() { return requireResponse(vaultOperations.doWithVault(restOperations -> { try { Map<String, Boolean> body = restOperations.getForObject("sys/init", Map.class); Assert.state(body != null, "Initialization response must not be null"); return body.get("initialized"); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); } })); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void shouldAuthenticatePullModeWithGeneratedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = (String) getVaultOperations() .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData().get("secret_id"); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(RoleId.provided(roleId)).secretId(SecretId.provided(secretId)) .build(); AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); }
#vulnerable code @Test void shouldAuthenticatePullModeWithGeneratedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = (String) getVaultOperations() .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData().get("secret_id"); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(roleId).secretId(secretId).build(); AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean initForceBatchStatementsOrdering(TypedMap configMap) { return configMap.getTypedOr(FORCE_BATCH_STATEMENTS_ORDERING, DEFAULT_FORCE_BATCH_STATEMENTS_ORDERING); }
#vulnerable code public boolean initForceBatchStatementsOrdering(TypedMap configMap) { return configMap.getTypedOr(FORCE_BATCH_STATEMENTS_ORDERING, true); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private TypeParsingResult parseComputedType(AnnotationTree annotationTree, FieldParsingContext context, TypeName sourceType) { final CodecInfo codecInfo = codecFactory.createCodec(sourceType, annotationTree, context, Optional.empty()); final TypeName rawTargetType = getRawType(codecInfo.targetType); final TypedMap computed = extractTypedMap(annotationTree, Computed.class).get(); final String alias = computed.getTyped("alias"); CodeBlock extractor = context.buildExtractor ? CodeBlock.builder().add("gettableData$$ -> gettableData$$.$L", TypeUtils.gettableDataGetter(rawTargetType, alias)).build() : NO_GETTER; CodeBlock typeCode = CodeBlock.builder().add("new $T<$T, $T, $T>($L, $L, $L)", COMPUTED_PROPERTY, context.entityRawType, sourceType, codecInfo.targetType, context.fieldInfoCode, extractor, codecInfo.codecCode) .build(); final ParameterizedTypeName propertyType = genericType(COMPUTED_PROPERTY, context.entityRawType, codecInfo.sourceType, codecInfo.targetType); return new TypeParsingResult(context, annotationTree.hasNext() ? annotationTree.next() : annotationTree, sourceType, codecInfo.targetType, propertyType, typeCode); }
#vulnerable code private TypeParsingResult parseComputedType(AnnotationTree annotationTree, FieldParsingContext context, TypeName sourceType) { final CodecInfo codecInfo = codecFactory.createCodec(sourceType, annotationTree, context); final TypeName rawTargetType = getRawType(codecInfo.targetType); final TypedMap computed = extractTypedMap(annotationTree, Computed.class).get(); final String alias = computed.getTyped("alias"); CodeBlock extractor = context.buildExtractor ? CodeBlock.builder().add("gettableData$$ -> gettableData$$.$L", TypeUtils.gettableDataGetter(rawTargetType, alias)).build() : NO_GETTER; CodeBlock typeCode = CodeBlock.builder().add("new $T<$T, $T, $T>($L, $L, $L)", COMPUTED_PROPERTY, context.entityRawType, sourceType, codecInfo.targetType, context.fieldInfoCode, extractor, codecInfo.codecCode) .build(); final ParameterizedTypeName propertyType = genericType(COMPUTED_PROPERTY, context.entityRawType, codecInfo.sourceType, codecInfo.targetType); return new TypeParsingResult(context, annotationTree.hasNext() ? annotationTree.next() : annotationTree, sourceType, codecInfo.targetType, propertyType, typeCode); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public PreparedStatement prepareUpdateFields(Session session, EntityMeta entityMeta, List<PropertyMeta> pms) { log.trace("Generate prepared statement for UPDATE properties {}", pms); PropertyMeta idMeta = entityMeta.getIdMeta(); Update update = update(entityMeta.getTableName()); Assignments assignments = null; for (int i = 0; i < pms.size(); i++) { PropertyMeta pm = pms.get(i); if (i == 0) { assignments = update.with(set(pm.getPropertyName(), bindMarker())); } else { assignments.and(set(pm.getPropertyName(), bindMarker())); } } RegularStatement statement = prepareWhereClauseForUpdate(idMeta, assignments,true); return session.prepare(statement.getQueryString()); }
#vulnerable code public PreparedStatement prepareUpdateFields(Session session, EntityMeta entityMeta, List<PropertyMeta> pms) { log.trace("Generate prepared statement for UPDATE properties {}", pms); PropertyMeta idMeta = entityMeta.getIdMeta(); Update update = update(entityMeta.getTableName()); Assignments assignments = null; for (int i = 0; i < pms.size(); i++) { PropertyMeta pm = pms.get(i); if (i == 0) { assignments = update.with(set(pm.getPropertyName(), bindMarker())); } else { assignments.and(set(pm.getPropertyName(), bindMarker())); } } RegularStatement statement = prepareWhereClauseForUpdate(idMeta, assignments); return session.prepare(statement.getQueryString()); } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { final boolean kubernetesEnabled = environment .getProperty("spring.cloud.kubernetes.enabled", Boolean.class, true); if (!kubernetesEnabled) { return; } if (isInsideKubernetes()) { if (hasKubernetesProfile(environment)) { if (LOG.isDebugEnabled()) { LOG.debug("'kubernetes' already in list of active profiles"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Adding 'kubernetes' to list of active profiles"); } environment.addActiveProfile(KUBERNETES_PROFILE); } } else { if (LOG.isDebugEnabled()) { LOG.warn( "Not running inside kubernetes. Skipping 'kubernetes' profile activation."); } } }
#vulnerable code @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { final boolean kubernetesEnabled = environment .getProperty("spring.cloud.kubernetes.enabled", Boolean.class, true); if (!kubernetesEnabled) { return; } final StandardPodUtils podUtils = new StandardPodUtils( new DefaultKubernetesClient()); if (podUtils.isInsideKubernetes()) { if (hasKubernetesProfile(environment)) { if (LOG.isDebugEnabled()) { LOG.debug("'kubernetes' already in list of active profiles"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Adding 'kubernetes' to list of active profiles"); } environment.addActiveProfile(KUBERNETES_PROFILE); } } else { if (LOG.isDebugEnabled()) { LOG.warn( "Not running inside kubernetes. Skipping 'kubernetes' profile activation."); } } } #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 testDecodeWithMessageIdAndAck() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("5:1+::{\"name\":\"tobi\"}", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.EVENT, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Assert.assertEquals("tobi", packet.getName()); }
#vulnerable code @Test public void testDecodeWithMessageIdAndAck() throws IOException { Packet packet = decoder.decodePacket("5:1+::{\"name\":\"tobi\"}", null); Assert.assertEquals(PacketType.EVENT, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Assert.assertEquals("tobi", packet.getName()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void doReconnect(Channel channel, HttpRequest req) { this.isKeepAlive = HttpHeaders.isKeepAlive(req); this.origin = req.getHeader(HttpHeaders.Names.ORIGIN); this.channel = channel; this.connected = true; sendPayload(); }
#vulnerable code public void doReconnect(Channel channel, HttpRequest req) { isKeepAlive = isKeepAlive(req); this.channel = channel; this.connected = true; sendPayload(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("5:::{\"name\":\"woot\"}", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("woot", packet.getName()); }
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("5:::{\"name\":\"woot\"}", null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("woot", packet.getName()); } #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 testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:::woot", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("woot", packet.getData()); }
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("3:::woot", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("woot", packet.getData()); } #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 testDecodeWithData() throws IOException { JacksonJsonSupport jsonSupport = new JacksonJsonSupport(); jsonSupport.addEventMapping("", "edwald", HashMap.class, Integer.class, String.class); PacketDecoder decoder = new PacketDecoder(jsonSupport, ackManager); Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("5:::{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"},2,\"3\"]}", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("edwald", packet.getName()); // Assert.assertEquals(3, packet.getArgs().size()); // Map obj = (Map) packet.getArgs().get(0); // Assert.assertEquals("b", obj.get("a")); // Assert.assertEquals(2, packet.getArgs().get(1)); // Assert.assertEquals("3", packet.getArgs().get(2)); }
#vulnerable code @Test public void testDecodeWithData() throws IOException { JacksonJsonSupport jsonSupport = new JacksonJsonSupport(); jsonSupport.addEventMapping("", "edwald", HashMap.class, Integer.class, String.class); PacketDecoder decoder = new PacketDecoder(jsonSupport, ackManager); Packet packet = decoder.decodePacket("5:::{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"},2,\"3\"]}", null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("edwald", packet.getName()); // Assert.assertEquals(3, packet.getArgs().size()); // Map obj = (Map) packet.getArgs().get(0); // Assert.assertEquals("b", obj.get("a")); // Assert.assertEquals(2, packet.getArgs().get(1)); // Assert.assertEquals("3", packet.getArgs().get(2)); } #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 testDecodeWithMessageIdAndAckData() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("4:1+::{\"a\":\"b\"}", CharsetUtil.UTF_8), null); // Assert.assertEquals(PacketType.JSON, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Map obj = (Map) packet.getData(); Assert.assertEquals("b", obj.get("a")); Assert.assertEquals(1, obj.size()); }
#vulnerable code @Test public void testDecodeWithMessageIdAndAckData() throws IOException { Packet packet = decoder.decodePacket("4:1+::{\"a\":\"b\"}", null); // Assert.assertEquals(PacketType.JSON, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Map obj = (Map) packet.getData(); Assert.assertEquals("b", obj.get("a")); Assert.assertEquals(1, obj.size()); } #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 testDecodeWithArgs() throws IOException { initExpectations(); Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("6:::12+[\"woot\",\"wa\"]", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.ACK, packet.getType()); Assert.assertEquals(12, (long)packet.getAckId()); // Assert.assertEquals(Arrays.<Object>asList("woot", "wa"), packet.getArgs()); }
#vulnerable code @Test public void testDecodeWithArgs() throws IOException { initExpectations(); Packet packet = decoder.decodePacket("6:::12+[\"woot\",\"wa\"]", null); Assert.assertEquals(PacketType.ACK, packet.getType()); Assert.assertEquals(12, (long)packet.getAckId()); // Assert.assertEquals(Arrays.<Object>asList("woot", "wa"), packet.getArgs()); } #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 testUTF8Decode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("4:::\"Привет\"", CharsetUtil.UTF_8), null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("Привет", packet.getData()); }
#vulnerable code @Test public void testUTF8Decode() throws IOException { Packet packet = decoder.decodePacket("4:::\"Привет\"", null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("Привет", packet.getData()); } #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 testDecodeId() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:1::asdfasdf", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertTrue(packet.getArgs().isEmpty()); // Assert.assertTrue(packet.getAck().equals(Boolean.TRUE)); }
#vulnerable code @Test public void testDecodeId() throws IOException { Packet packet = decoder.decodePacket("3:1::asdfasdf", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertTrue(packet.getArgs().isEmpty()); // Assert.assertTrue(packet.getAck().equals(Boolean.TRUE)); } #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 testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("6:::140", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.ACK, packet.getType()); Assert.assertEquals(140, (long)packet.getAckId()); // Assert.assertTrue(packet.getArgs().isEmpty()); }
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("6:::140", null); Assert.assertEquals(PacketType.ACK, packet.getType()); Assert.assertEquals(140, (long)packet.getAckId()); // Assert.assertTrue(packet.getArgs().isEmpty()); } #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 testDecodingNewline() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:::\n", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("\n", packet.getData()); }
#vulnerable code @Test public void testDecodingNewline() throws IOException { Packet packet = decoder.decodePacket("3:::\n", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("\n", packet.getData()); } #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 testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("4:::\"2\"", CharsetUtil.UTF_8), null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("2", packet.getData()); }
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("4:::\"2\"", null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("2", packet.getData()); } #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 testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("1::/tobi", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.CONNECT, packet.getType()); Assert.assertEquals("/tobi", packet.getNsp()); }
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("1::/tobi", null); Assert.assertEquals(PacketType.CONNECT, packet.getType()); Assert.assertEquals("/tobi", packet.getNsp()); } #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 testDecodeWithIdAndEndpoint() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:5:/tobi", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(5, (long)packet.getId()); // Assert.assertEquals(true, packet.getAck()); Assert.assertEquals("/tobi", packet.getNsp()); }
#vulnerable code @Test public void testDecodeWithIdAndEndpoint() throws IOException { Packet packet = decoder.decodePacket("3:5:/tobi", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(5, (long)packet.getId()); // Assert.assertEquals(true, packet.getAck()); Assert.assertEquals("/tobi", packet.getNsp()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); String resource = resources.get(queryDecoder.path()); if (resource != null) { // create ok response HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); // set content type HttpHeaders.setHeader(res, HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream"); // write header ctx.write(res); // create resource inputstream and check InputStream is = getClass().getResourceAsStream(resource); if (is == null) { sendError(ctx, NOT_FOUND); return; } // write the stream ChannelFuture writeFuture = ctx.channel().write(new ChunkedStream(is)); // close the channel on finish writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } ctx.fireChannelRead(msg); }
#vulnerable code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); File resource = resources.get(queryDecoder.path()); if (resource != null) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); if (isNotModified(req, resource)) { sendNotModified(ctx); req.release(); return; } RandomAccessFile raf; try { raf = new RandomAccessFile(resource, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); setContentLength(res, fileLength); setContentTypeHeader(res, resource); setDateAndCacheHeaders(res, resource); // write the response header ctx.write(res); // write the content to the channel ChannelFuture writeFuture = writeContent(raf, fileLength, ctx.channel()); // close the request channel writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } super.channelRead(ctx, msg); } #location 32 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBench1() throws Exception { if (System.getProperty("skipBenchmark") != null) { System.out.println(":: skipping naive benchmarks..."); return; } System.out.println(":: running naive benchmarks, set -DskipBenchmark to skip"); String expr = "foo(x,y)=log(x) - y * (sqrt(x^cos(y)))"; Calculable calc = new ExpressionBuilder(expr).build(); double val = 0; Random rnd = new Random(); long timeout = 2; long time = System.currentTimeMillis() + (1000 * timeout); int count = 0; while (time > System.currentTimeMillis()) { calc.setVariable("x", rnd.nextDouble()); calc.setVariable("y", rnd.nextDouble()); val = calc.calculate(); count++; } System.out.println("\n:: running simple benchmarks [" + timeout + " seconds]"); System.out.println("expression\t\t" + expr); double rate = count / timeout; System.out.println("exp4j\t\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); time = System.currentTimeMillis() + (1000 * timeout); double x, y; count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); count++; } rate = count / timeout; System.out.println("Java Math\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); if (engine == null) { System.err.println("Unable to instantiate javascript engine. skipping naive JS bench."); } else { time = System.currentTimeMillis() + (1000 * timeout); count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); engine.eval("Math.log(" + x + ") - " + y + "* (Math.sqrt(" + x + "^Math.cos(" + y + ")))"); count++; } rate = count / timeout; System.out.println("JSR 223(Javascript)\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); } }
#vulnerable code @Test public void testBench1() throws Exception { if (System.getProperty("skipBenchmark") != null && System.getProperty("skipBenchmark").equals("true")) { System.out.println(":: skipping naive benchmarks..."); return; } System.out.println(":: running naive benchmarks, set -DskipBenchmark to skip"); String expr = "foo(x,y)=log(x) - y * (sqrt(x^cos(y)))"; Calculable calc = new ExpressionBuilder(expr).build(); double val = 0; Random rnd = new Random(); long timeout = 2; long time = System.currentTimeMillis() + (1000 * timeout); int count = 0; while (time > System.currentTimeMillis()) { calc.setVariable("x", rnd.nextDouble()); calc.setVariable("y", rnd.nextDouble()); val = calc.calculate(); count++; } System.out.println("\n:: [PostfixExpression] simple benchmark"); System.out.println("expression\t\t" + expr); double rate = count / timeout; System.out.println("exp4j\t\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); time = System.currentTimeMillis() + (1000 * timeout); double x, y; count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); count++; } rate = count / timeout; System.out.println("Java Math\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); if (engine == null) { System.err.println("Unable to instantiate javascript engine. skipping naive JS bench."); } else { time = System.currentTimeMillis() + (1000 * timeout); count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); engine.eval("Math.log(" + x + ") - " + y + "* (Math.sqrt(" + x + "^Math.cos(" + y + ")))"); count++; } rate = count / timeout; System.out.println("JSR 223(Javascript)\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); } } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canUpsertWithWriteConcern() throws Exception { /* when */ WriteResult writeResult = collection.update("{}").upsert().concern(WriteConcern.SAFE).with("{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); assertThat(writeResult.getLastConcern()).isEqualTo(WriteConcern.SAFE); }
#vulnerable code @Test public void canUpsertWithWriteConcern() throws Exception { WriteConcern writeConcern = spy(WriteConcern.SAFE); /* when */ WriteResult writeResult = collection.upsert("{}", "{$set:{name:'John'}}", writeConcern); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); verify(writeConcern).callGetLastError(); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canModifyAlreadySavedEntity() throws Exception { /* given */ People john = new People("John", "21 Jump Street"); collection.save(john); john.setAddress("new address"); /* when */ collection.save(john); /* then */ ObjectId johnId = john.getId(); People johnWithNewAddress = collection.findOne(johnId).as(People.class); assertThat(johnWithNewAddress.getId()).isEqualTo(johnId); assertThat(johnWithNewAddress.getAddress()).isEqualTo("new address"); }
#vulnerable code @Test public void canModifyAlreadySavedEntity() throws Exception { /* given */ String idAsString = collection.save(new People("John", "21 Jump Street")); ObjectId id = new ObjectId(idAsString); People people = collection.findOne(id).as(People.class); people.setAddress("new address"); /* when */ collection.save(people); /* then */ people = collection.findOne(id).as(People.class); assertThat(people.getId()).isEqualTo(id); assertThat(people.getAddress()).isEqualTo("new address"); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canFindOne() throws Exception { /* given */ String id = collection.save(new People("John", new Coordinate(1, 1))); /* when */ People result = collection.findOne("{name:#}", "John").as(People.class); /* then */ assertThat(result.getId()).isEqualTo(id); }
#vulnerable code @Test public void canFindOne() throws Exception { /* given */ String id = collection.save(this.people); /* when */ People people = collection.findOne("{name:#}", "John").as(People.class); /* then */ assertThat(people.getId()).isEqualTo(id); } #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 canFindOneWithObjectId() throws Exception { /* given */ Friend john = new Friend("John", "22 Wall Street Avenue"); collection.save(john); Friend foundFriend = collection.findOne(john.getId()).as(Friend.class); /* then */ assertThat(foundFriend).isNotNull(); assertThat(foundFriend.getId()).isEqualTo(john.getId()); }
#vulnerable code @Test public void canFindOneWithObjectId() throws Exception { /* given */ People john = new People("John", "22 Wall Street Avenue"); collection.save(john); People foundPeople = collection.findOne(john.getId()).as(People.class); /* then */ assertThat(foundPeople).isNotNull(); assertThat(foundPeople.getId()).isEqualTo(john.getId()); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canFindOne() throws Exception { /* given */ collection.save(new Friend("John", "22 Wall Street Avenue")); /* when */ Friend friend = collection.findOne("{name:'John'}").as(Friend.class); /* then */ assertThat(friend.getName()).isEqualTo("John"); }
#vulnerable code @Test public void canFindOne() throws Exception { /* given */ collection.save(new People("John", "22 Wall Street Avenue")); /* when */ People people = collection.findOne("{name:'John'}").as(People.class); /* then */ assertThat(people.getName()).isEqualTo("John"); } #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 canUpsert() throws Exception { /* when */ WriteResult writeResult = collection.update("{}").upsert().with("{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); }
#vulnerable code @Test public void canUpsert() throws Exception { /* when */ WriteResult writeResult = collection.upsert("{}", "{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String readFile(final String path) throws FileNotFoundException { try (Scanner scanner = new java.util.Scanner(new java.io.File(this.fileBase, path), "UTF-8")) { return scanner.useDelimiter("\\Z").next().toString(); } }
#vulnerable code @Override public String readFile(final String path) throws FileNotFoundException { return new java.util.Scanner(new java.io.File(this.fileBase, path), "UTF-8").useDelimiter("\\Z").next().toString(); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] classAsBytes(final String className) throws ClassNotFoundException { final URL resource = ClassUtils.class.getClassLoader().getResource( convertClassNameToFileName(className)); try(BufferedInputStream stream = new BufferedInputStream( resource.openStream())) { final byte[] result = new byte[resource.openConnection() .getContentLength()]; int i; int counter = 0; while ((i = stream.read()) != -1) { result[counter] = (byte) i; counter++; } return result; } catch (final IOException e) { throw new ClassNotFoundException("", e); } }
#vulnerable code public static byte[] classAsBytes(final String className) throws ClassNotFoundException { try { final URL resource = ClassUtils.class.getClassLoader().getResource( convertClassNameToFileName(className)); final BufferedInputStream stream = new BufferedInputStream( resource.openStream()); final byte[] result = new byte[resource.openConnection() .getContentLength()]; int i; int counter = 0; while ((i = stream.read()) != -1) { result[counter] = (byte) i; counter++; } stream.close(); return result; } catch (final IOException e) { throw new ClassNotFoundException("", e); } } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static EntityManager createEntityManager() { init(false); return PersistUtilHelper.getEntityManager(); }
#vulnerable code public static EntityManager createEntityManager() { init(false); return PersistUtilHelper.getEntityManager(); // return entityManagerFactory.createEntityManager(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void setValue(Integer value, boolean fireEvents) { try { checkRangeValue(value); setIntToRangeElement(VALUE, value); } catch(Exception e) { getLogger().log(Level.SEVERE, e.getMessage()); } super.setValue(value, fireEvents); }
#vulnerable code @Override public void setValue(Integer value, boolean fireEvents) { if (value == null) { GWT.log("Value must be null", new RuntimeException()); return; } if (value < getMin()) { GWT.log("Value must not be less than the minimum range value.", new RuntimeException()); return; } if (value > getMax()) { GWT.log("Value must not be greater than the maximum range value", new RuntimeException()); return; } setIntToRangeElement(VALUE, value); super.setValue(value, fireEvents); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void initialize(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); if (!isFixed()) { String style = activator.getAttribute("style"); if (alwaysShowActivator) { activator.setAttribute("style", style + "; display: block !important"); } else { activator.setAttribute("style", style + "; display: none !important"); } activator.removeClassName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException("Could not setup MaterialSideNav please ensure you have MaterialNavBar with an activator setup to match this widgets id."); } } SideNavType type = getType(); processType(type); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off("side-nav-closing"); element.on("side-nav-closing", e1 -> { onClosing(); return true; }); element.off("side-nav-closed"); element.on("side-nav-closed", e1 -> { onClosed(); return true; }); element.off("side-nav-opening"); element.on("side-nav-opening", e1 -> { onOpening(); return true; }); element.off("side-nav-opened"); element.on("side-nav-opened", e1 -> { onOpened(); return true; }); }
#vulnerable code protected void initialize(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); if (alwaysShowActivator || !isFixed()) { String style = activator.getAttribute("style"); activator.setAttribute("style", style + "; display: block !important"); activator.removeClassName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException("Could not setup MaterialSideNav please ensure you have MaterialNavBar with an activator setup to match this widgets id."); } } SideNavType type = getType(); processType(type); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off("side-nav-closing"); element.on("side-nav-closing", e1 -> { onClosing(); return true; }); element.off("side-nav-closed"); element.on("side-nav-closed", e1 -> { onClosed(); return true; }); element.off("side-nav-opening"); element.on("side-nav-opening", e1 -> { onOpening(); return true; }); element.off("side-nav-opened"); element.on("side-nav-opened", e1 -> { onOpened(); return true; }); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void add(Widget child) { super.add(wrap(child)); }
#vulnerable code @Override public void add(Widget child) { if(child instanceof MaterialImage) { child.getElement().getStyle().setProperty("border", "1px solid #e9e9e9"); child.getElement().getStyle().setProperty("textAlign", "center"); } boolean collapsible = child instanceof MaterialCollapsible; if(collapsible) { // Since the collapsible is separ ((MaterialCollapsible)child).addClearActiveHandler(new ClearActiveHandler() { @Override public void onClearActive(ClearActiveEvent event) { clearActive(); } }); } if(!(child instanceof ListItem)) { // Direct list item not collapsible final ListItem listItem = new ListItem(); if(child instanceof MaterialCollapsible) { listItem.getElement().getStyle().setBackgroundColor("transparent"); } if(child instanceof HasWaves) { listItem.setWaves(((HasWaves) child).getWaves()); ((HasWaves) child).setWaves(null); } listItem.add(child); child = listItem; } // Collapsible's should not be selectable final Widget finalChild = child; if(!collapsible) { // Active click handler finalChild.addDomHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { clearActive(); finalChild.addStyleName("active"); } }, ClickEvent.getType()); } child.getElement().getStyle().setDisplay(Style.Display.BLOCK); super.add(child); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); MaterialWidget navMenu = getNavMenu(); if (navMenu != null) { navMenu.setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { navMenu.setShowOn(ShowOn.SHOW_ON_LARGE); } else { navMenu.setHideOn(HideOn.HIDE_ON_LARGE); } navMenu.removeStyleName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); }
#vulnerable code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); getNavMenu().setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); } else { getNavMenu().setHideOn(HideOn.HIDE_ON_LARGE); } getNavMenu().removeStyleName(CssName.NAVMENU_PERMANENT); } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void applyOverlayType() { setShowOnAttach(false); if (overlayOpeningHandler == null) { overlayOpeningHandler = addOpeningHandler(event -> { Scheduler.get().scheduleDeferred(() -> $("#sidenav-overlay").css("visibility", "visible")); }); } $("header").css("paddingLeft", "0px"); $("main").css("paddingLeft", "0px"); }
#vulnerable code protected void applyOverlayType() { setShowOnAttach(false); getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); if (overlayOpeningHandler == null) { overlayOpeningHandler = addOpeningHandler(event -> { Scheduler.get().scheduleDeferred(() -> $("#sidenav-overlay").css("visibility", "visible")); }); } $("header").css("paddingLeft", "0px"); $("main").css("paddingLeft", "0px"); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); MaterialWidget navMenu = getNavMenu(); if (navMenu != null) { navMenu.setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { navMenu.setShowOn(ShowOn.SHOW_ON_LARGE); } else { navMenu.setHideOn(HideOn.HIDE_ON_LARGE); } navMenu.removeStyleName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); }
#vulnerable code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); getNavMenu().setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); } else { getNavMenu().setHideOn(HideOn.HIDE_ON_LARGE); } getNavMenu().removeStyleName(CssName.NAVMENU_PERMANENT); } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void writeToFile(String path) throws IOException { FileOutputStream out = null; try { out = new FileOutputStream(path); this.write(out); out.flush(); } finally { PoitlIOUtils.closeQuietlyMulti(this.doc, out); } }
#vulnerable code public void writeToFile(String path) throws IOException { FileOutputStream out = new FileOutputStream(path); this.write(out); this.close(); out.flush(); out.close(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void visit(InlineIterableTemplate iterableTemplate) { logger.info("Process InlineIterableTemplate:{}", iterableTemplate); super.visit((IterableTemplate) iterableTemplate); }
#vulnerable code @Override public void visit(InlineIterableTemplate iterableTemplate) { logger.info("Process InlineIterableTemplate:{}", iterableTemplate); BodyContainer bodyContainer = BodyContainerFactory.getBodyContainer(iterableTemplate); Object compute = renderDataCompute.compute(iterableTemplate.getStartMark().getTagName()); int times = conditionTimes(compute); if (TIMES_ONCE == times) { RenderDataCompute dataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(compute); new DocumentProcessor(this.template, dataCompute).process(iterableTemplate.getTemplates()); } else if (TIMES_N == times) { RunTemplate start = iterableTemplate.getStartMark(); RunTemplate end = iterableTemplate.getEndMark(); XWPFRun startRun = start.getRun(); XWPFRun endRun = end.getRun(); XWPFParagraph currentParagraph = (XWPFParagraph) startRun.getParent(); XWPFParagraphWrapper paragraphWrapper = new XWPFParagraphWrapper(currentParagraph); Integer startRunPos = start.getRunPos(); Integer endRunPos = end.getRunPos(); CTR endCtr = endRun.getCTR(); Iterable<?> model = (Iterable<?>) compute; Iterator<?> iterator = model.iterator(); while (iterator.hasNext()) { // copy position cursor int insertPostionCursor = end.getRunPos(); // copy content List<XWPFRun> runs = currentParagraph.getRuns(); List<XWPFRun> copies = new ArrayList<XWPFRun>(); for (int i = startRunPos + 1; i < endRunPos; i++) { insertPostionCursor = end.getRunPos(); XWPFRun xwpfRun = runs.get(i); XWPFRun insertNewRun = paragraphWrapper.insertNewRun(xwpfRun, insertPostionCursor); XWPFRun xwpfRun2 = paragraphWrapper.createRun(xwpfRun, (IRunBody)currentParagraph); paragraphWrapper.setAndUpdateRun(xwpfRun2, insertNewRun, insertPostionCursor); XmlCursor newCursor = endCtr.newCursor(); newCursor.toPrevSibling(); XmlObject object = newCursor.getObject(); XWPFRun copy = paragraphWrapper.createRun(object, (IRunBody)currentParagraph); copies.add(copy); paragraphWrapper.setAndUpdateRun(copy, xwpfRun2, insertPostionCursor); } // re-parse List<MetaTemplate> templates = template.getResolver().resolveXWPFRuns(copies); // render RenderDataCompute dataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(iterator.next()); new DocumentProcessor(this.template, dataCompute).process(templates); } // clear self iterable template for (int i = endRunPos - 1; i > startRunPos; i--) { paragraphWrapper.removeRun(i); } } else { XWPFParagraph currentParagraph = (XWPFParagraph) iterableTemplate.getStartRun().getParent(); XWPFParagraphWrapper paragraphWrapper = new XWPFParagraphWrapper(currentParagraph); Integer startRunPos = iterableTemplate.getStartMark().getRunPos(); Integer endRunPos = iterableTemplate.getEndMark().getRunPos(); for (int i = endRunPos - 1; i > startRunPos; i--) { paragraphWrapper.removeRun(i); } } bodyContainer.clearPlaceholder(iterableTemplate.getStartRun()); bodyContainer.clearPlaceholder(iterableTemplate.getEndRun()); } #location 65 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void doRender(ChartTemplate eleTemplate, ChartMultiSeriesRenderData data, XWPFTemplate template) throws Exception { XWPFChart chart = eleTemplate.getChart(); List<XDDFChartData> chartSeries = chart.getChartSeries(); validate(chartSeries, data); int totalSeriesCount = ensureSeriesCount(chart, chartSeries); int valueCol = 0; List<SeriesRenderData> usedSeriesDatas = new ArrayList<>(); for (XDDFChartData chartData : chartSeries) { int orignSize = chartData.getSeriesCount(); List<SeriesRenderData> currentSeriesData = null; if (chartSeries.size() <= 1) { // ignore combo type currentSeriesData = data.getSeriesDatas(); } else { currentSeriesData = obtainSeriesData(chartData.getClass(), data.getSeriesDatas()); } usedSeriesDatas.addAll(currentSeriesData); int currentSeriesSize = currentSeriesData.size(); XDDFDataSource<?> categoriesData = createCategoryDataSource(chart, data.getCategories()); for (int i = 0; i < currentSeriesSize; i++) { XDDFNumericalDataSource<? extends Number> valuesData = createValueDataSource(chart, currentSeriesData.get(i).getValues(), valueCol); XDDFChartData.Series currentSeries = null; if (i < orignSize) { currentSeries = chartData.getSeries(i); currentSeries.replaceData(categoriesData, valuesData); } else { // add series, should copy series with style currentSeries = chartData.addSeries(categoriesData, valuesData); processNewSeries(chartData, currentSeries); } String name = currentSeriesData.get(i).getName(); currentSeries.setTitle(name, chart.setSheetTitle(name, valueCol + VALUE_START_COL)); valueCol++; } // clear extra series removeExtraSeries(chartData, orignSize, currentSeriesSize); } XSSFSheet sheet = chart.getWorkbook().getSheetAt(0); updateCTTable(sheet, usedSeriesDatas); removeExtraSheetCell(sheet, data.getCategories().length, totalSeriesCount, usedSeriesDatas.size()); for (XDDFChartData chartData : chartSeries) { plot(chart, chartData); } chart.setTitleText(data.getChartTitle()); chart.setTitleOverlay(false); }
#vulnerable code @Override public void doRender(ChartTemplate eleTemplate, ChartMultiSeriesRenderData data, XWPFTemplate template) throws Exception { if (null == data) return; XWPFChart chart = eleTemplate.getChart(); List<XDDFChartData> chartSeries = chart.getChartSeries(); // validate combo if (chartSeries.size() >= 2) { long nullCount = data.getSeriesDatas().stream().filter(d -> null == d.getComboType()).count(); if (nullCount > 0) throw new RenderException("Combo chart must set comboType field of series!"); } // hack for poi 4.1.1+: repair seriesCount value, int totalSeriesCount = chartSeries.stream().mapToInt(XDDFChartData::getSeriesCount).sum(); Field field = ReflectionUtils.findField(XDDFChart.class, "seriesCount"); field.setAccessible(true); field.set(chart, totalSeriesCount); int valueCol = 0; List<SeriesRenderData> usedSeriesDatas = new ArrayList<>(); for (XDDFChartData chartData : chartSeries) { int orignSize = chartData.getSeriesCount(); List<SeriesRenderData> seriesDatas = null; if (chartSeries.size() <= 1) { // ignore combo type seriesDatas = data.getSeriesDatas(); } else { seriesDatas = obtainSeriesData(chartData.getClass(), data.getSeriesDatas()); } usedSeriesDatas.addAll(seriesDatas); int seriesSize = seriesDatas.size(); XDDFDataSource<?> categoriesData = createCategoryDataSource(chart, data.getCategories()); for (int i = 0; i < seriesSize; i++) { XDDFNumericalDataSource<? extends Number> valuesData = createValueDataSource(chart, seriesDatas.get(i).getValues(), valueCol); XDDFChartData.Series currentSeries = null; if (i < orignSize) { currentSeries = chartData.getSeries(i); currentSeries.replaceData(categoriesData, valuesData); } else { // add series, should copy series with style currentSeries = chartData.addSeries(categoriesData, valuesData); processNewSeries(chartData, currentSeries); } String name = seriesDatas.get(i).getName(); currentSeries.setTitle(name, chart.setSheetTitle(name, valueCol + VALUE_START_COL)); valueCol++; } // clear extra series removeExtraSeries(chartData, orignSize, seriesSize); } XSSFSheet sheet = chart.getWorkbook().getSheetAt(0); updateCTTable(sheet, usedSeriesDatas); removeExtraSheetCell(sheet, data.getCategories().length, totalSeriesCount, usedSeriesDatas.size()); for (XDDFChartData chartData : chartSeries) { plot(chart, chartData); } chart.setTitleText(data.getChartTitle()); chart.setTitleOverlay(false); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void simple() throws IOException { FontTools.availableFontNamesGraph(new File("fonts.png")); final Graph g = graph("ex7").directed() .with( graph().cluster() .nodeAttr().with(Style.FILLED, Color.WHITE) .graphAttr().with(Style.FILLED, Color.LIGHTGREY, Label.of("process #1")) .with(node("a0").link(node("a1").link(node("a2").link(node("a3"))))), graph("x").cluster() .nodeAttr().with(Style.FILLED) .graphAttr().with(Color.BLUE, Label.of("process #2")) .with(node("b0").link(node("b1").link(node("b2").link(node("b3"))))), node("start").with(Shape.mDiamond("", "")).link("a0", "b0"), node("a1").link("b3"), node("b2").link("a3"), node("a3").link("a0"), node("a3").link("end"), node("b3").link("end"), node("end").with(Shape.mSquare("", "")) ); Graphviz.fromGraph(g) // .scale(2) // .filter(new RoughFilter()) .render(Format.PNG) .toFile(new File("target/out.png")); Graphviz.fromGraph(g) // .scale(2) .filter(new RoughFilter().bowing(5).roughness(2).font("*serif","Comic Sans MS")) .render(Format.PNG) .toFile(new File("target/outf.png")); }
#vulnerable code @Test void simple() throws IOException { Graphviz.fromString("graph{a--b}") .scale(2) .filter(new RoughFilter()) .render(Format.PNG) .toFile(new File("target/out.png")); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void releaseEngine() { synchronized (Graphviz.class) { if (engine != null) { doReleaseEngine(engine); } if (engineQueue != null) { for (final GraphvizEngine engine : engineQueue) { doReleaseEngine(engine); } } } engine = null; engineQueue = null; }
#vulnerable code public static void releaseEngine() { if (engine != null) { try { engine.close(); } catch (Exception e) { throw new GraphvizException("Problem closing engine", e); } } engine = null; engineQueue = null; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void useDefaultEngines() { useEngine(AVAILABLE_ENGINES); }
#vulnerable code public static void useDefaultEngines() { useEngine(new GraphvizCmdLineEngine(), new GraphvizV8Engine(), new GraphvizServerEngine(), new GraphvizJdkEngine()); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void useDefaultEngines() { useEngine(AVAILABLE_ENGINES); }
#vulnerable code public static void useDefaultEngines() { useEngine(new GraphvizCmdLineEngine(), new GraphvizV8Engine(), new GraphvizServerEngine(), new GraphvizJdkEngine()); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void start(List<GraphvizEngine> engines) throws IOException { final String executable = SystemUtils.executableName("java"); final List<String> cmd = new ArrayList<>(Arrays.asList( System.getProperty("java.home") + "/bin/" + executable, "-cp", System.getProperty("java.class.path"), GraphvizServer.class.getName())); cmd.addAll(engines.stream().map(e -> e.getClass().getName()).collect(toList())); new ProcessBuilder(cmd).inheritIO().start(); }
#vulnerable code public static void start(List<GraphvizEngine> engines) throws IOException { final boolean windows = System.getProperty("os.name").contains("windows"); final String executable = windows ? "java.exe" : "java"; final List<String> cmd = new ArrayList<>(Arrays.asList( System.getProperty("java.home") + "/bin/" + executable, "-cp", System.getProperty("java.class.path"), GraphvizServer.class.getName())); cmd.addAll(engines.stream().map(e -> e.getClass().getName()).collect(toList())); new ProcessBuilder(cmd).inheritIO().start(); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = HttpClientPool.getInstance(poolSize).getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; }
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = HttpClientPool.getInstance(poolSize).getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 19 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void checkComponent() { if (downloader == null) { this.downloader = new HttpClientDownloader(); } if (pipelines.isEmpty()) { pipelines.add(new ConsolePipeline()); } downloader.setThread(threadNum); }
#vulnerable code protected void checkComponent() { if (downloader == null) { this.downloader = new HttpClientDownloader(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Ignore @Test public void testCookie() { Site site = Site.me().setDomain("www.diandian.com").addCookie("t", "yct7q7e6v319wpg4cpxqduu5m77lcgix"); HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Page download = httpClientDownloader.download(new Request("http://www.diandian.com"), site.toTask()); Assert.assertTrue(download.getHtml().toString().contains("flashsword30")); }
#vulnerable code @Ignore @Test public void testCookie() { Site site = Site.me().setDomain("www.diandian.com").addCookie("t", "yct7q7e6v319wpg4cpxqduu5m77lcgix"); HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Page download = httpClientDownloader.download(new Request("http://www.diandian.com"), site); Assert.assertTrue(download.getHtml().toString().contains("flashsword30")); } #location 7 #vulnerability type NULL_DEREFERENCE