input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Test public void testInputStreamContent() { InputStream inputStream = $.class.getResourceAsStream("/poem.txt"); InputStreamContentProvider inputStreamContentProvider = new InputStreamContentProvider(inputStream); MultiPartContentProvider multiPartProvider = new MultiPartContentProvider(); System.out.println(multiPartProvider.getContentType()); multiPartProvider.addFilePart("poetry", "poem.txt", inputStreamContentProvider, null); multiPartProvider.close(); multiPartProvider.setListener(() -> System.out.println("on content")); List<ByteBuffer> list = new ArrayList<>(); for (ByteBuffer buf : multiPartProvider) { list.add(buf); } String value = BufferUtils.toString(list); Assert.assertThat(value.length(), greaterThan(0)); System.out.println(multiPartProvider.getLength()); Assert.assertThat(multiPartProvider.getLength(), lessThan(0L)); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testInputStreamContent() { InputStream inputStream = $.class.getResourceAsStream("/poem.txt"); InputStreamContentProvider inputStreamContentProvider = new InputStreamContentProvider(inputStream); MultiPartContentProvider multiPartProvider = new MultiPartContentProvider(); System.out.println(multiPartProvider.getContentType()); multiPartProvider.addFilePart("poetry", "poem.txt", inputStreamContentProvider, null); multiPartProvider.close(); multiPartProvider.setListener(() -> System.out.println("on content")); List<ByteBuffer> list = new ArrayList<>(); for (ByteBuffer buf : multiPartProvider) { list.add(buf); } String value = $.buffer.toString(list); Assert.assertThat(value.length(), greaterThan(0)); System.out.println(multiPartProvider.getLength()); Assert.assertThat(multiPartProvider.getLength(), lessThan(0L)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean directUpgradeHTTP2(MetaData.Request request) { if (HttpMethod.PRI.is(request.getMethod())) { HTTP2ServerConnection http2ServerConnection = new HTTP2ServerConnection(config, tcpSession, secureSession, serverSessionListener); tcpSession.attachObject(http2ServerConnection); http2ServerConnection.getParser().directUpgrade(); upgradeHTTP2Successfully = true; return true; } else { return false; } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code HTTP1ServerConnection(HTTP2Configuration config, Session tcpSession, SecureSession secureSession, HTTP1ServerRequestHandler requestHandler, ServerSessionListener serverSessionListener) { super(config, secureSession, tcpSession, requestHandler, null); requestHandler.connection = this; this.serverSessionListener = serverSessionListener; this.serverRequestHandler = requestHandler; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void initializeHTTP2ClientConnection(final Session session, final HTTP2ClientContext context, final SSLSession sslSession) { final HTTP2ClientConnection connection = new HTTP2ClientConnection(config, session, sslSession, context.listener); Map<Integer, Integer> settings = context.listener.onPreface(connection.getHttp2Session()); if (settings == null) { settings = Collections.emptyMap(); } PrefaceFrame prefaceFrame = new PrefaceFrame(); SettingsFrame settingsFrame = new SettingsFrame(settings, false); SessionSPI sessionSPI = connection.getSessionSPI(); int windowDelta = config.getInitialSessionRecvWindow() - FlowControlStrategy.DEFAULT_WINDOW_SIZE; Callback callback = new Callback() { @Override public void succeeded() { context.promise.succeeded(connection); } @Override public void failed(Throwable x) { try { connection.close(); } catch (IOException e) { log.error("http2 connection initialization error", e); } context.promise.failed(x); } }; if (windowDelta > 0) { sessionSPI.updateRecvWindow(windowDelta); sessionSPI.frames(null, callback, prefaceFrame, settingsFrame, new WindowUpdateFrame(0, windowDelta)); } else { sessionSPI.frames(null, callback, prefaceFrame, settingsFrame); } } #location 34 #vulnerability type RESOURCE_LEAK
#fixed code private void initializeHTTP2ClientConnection(final Session session, final HTTP2ClientContext context, final SSLSession sslSession) { HTTP2ClientConnection.initialize(config, session, context, sslSession); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFieldType() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>>() { }, null); FieldGenericTypeBind extInfo = map.get("attrs"); System.out.println(extInfo.getField().getName()); System.out.println(extInfo.getField().getGenericType().getTypeName() + "|" + extInfo.getField().getGenericType().getClass()); System.out.println(extInfo.getType().getTypeName() + "|" + extInfo.getType().getClass()); Assert.assertThat(extInfo.getType().getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); ParameterizedType parameterizedType = (ParameterizedType) extInfo.getType(); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); parameterizedType = (ParameterizedType) extInfo.getField().getGenericType(); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testFieldType() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(reqRef); FieldGenericTypeBind extInfo = map.get("attrs"); System.out.println(extInfo.getField().getName()); System.out.println(extInfo.getField().getGenericType().getTypeName() + "|" + extInfo.getField().getGenericType().getClass()); System.out.println(extInfo.getType().getTypeName() + "|" + extInfo.getType().getClass()); Assert.assertThat(extInfo.getType().getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); ParameterizedType parameterizedType = (ParameterizedType) extInfo.getType(); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); parameterizedType = (ParameterizedType) extInfo.getField().getGenericType(); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") private Object getMapArg(ManagedMap<XmlManagedNode, XmlManagedNode> values, Class<?> setterParamType) { Map<Object, Object> m = null; if (VerifyUtils.isNotEmpty(values.getTypeName())) { try { m = (Map<Object, Object>) XmlApplicationContext.class.getClassLoader() .loadClass(values.getTypeName()) .newInstance(); } catch (Throwable t) { log.error("map inject error", t); } } else { m = (setterParamType == null ? new HashMap<>() : ConvertUtils.getMapObj(setterParamType)); log.debug("map ret [{}]", m.getClass().getName()); } for (XmlManagedNode o : values.keySet()) { Object k = getInjectArg(o, null); Object v = getInjectArg(values.get(o), null); m.put(k, v); } return m; } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @SuppressWarnings("unchecked") private Object getMapArg(ManagedMap<XmlManagedNode, XmlManagedNode> values, Class<?> setterParamType) { Map<Object, Object> m = null; if (VerifyUtils.isNotEmpty(values.getTypeName())) { try { m = (Map<Object, Object>) XmlApplicationContext.class.getClassLoader() .loadClass(values.getTypeName()) .newInstance(); } catch (Throwable t) { log.error("map inject error", t); } } else { m = (setterParamType == null ? new HashMap<>() : ConvertUtils.getMapObj(setterParamType)); if (m != null && log.isDebugEnabled()) { log.debug("map ret [{}]", m.getClass().getName()); } } if (m != null) { for (XmlManagedNode o : values.keySet()) { Object k = getInjectArg(o, null); Object v = getInjectArg(values.get(o), null); m.put(k, v); } } return m; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testResponseParse2() throws Exception { ByteBuffer buffer = BufferUtils .toBuffer("HTTP/1.1 204 No-Content\015\012" + "Header: value\015\012" + "\015\012" + "HTTP/1.1 200 Correct\015\012" + "Content-Length: 10\015\012" + "Content-Type: text/plain\015\012" + "\015\012" + "0123456789\015\012"); HttpParser.ResponseHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parser.parseNext(buffer); assertEquals("HTTP/1.1", _methodOrVersion); assertEquals("204", _uriOrStatus); assertEquals("No-Content", _versionOrReason); assertTrue(_headerCompleted); assertTrue(_messageCompleted); parser.reset(); init(); parser.parseNext(buffer); parser.atEOF(); assertEquals("HTTP/1.1", _methodOrVersion); assertEquals("200", _uriOrStatus); assertEquals("Correct", _versionOrReason); assertEquals(_content.length(), 10); assertTrue(_headerCompleted); assertTrue(_messageCompleted); } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testResponseParse2() throws Exception { ByteBuffer buffer = BufferUtils .toBuffer("HTTP/1.1 204 No-Content\015\012" + "Header: value\015\012" + "\015\012" + "HTTP/1.1 200 Correct\015\012" + "Content-Length: 10\015\012" + "Content-Type: text/plain\015\012" + "\015\012" + "0123456789\015\012"); HttpParser.ResponseHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parser.parseNext(buffer); assertEquals("HTTP/1.1", _methodOrVersion); assertEquals("204", _uriOrStatus); assertEquals("No-Content", _versionOrReason); assertTrue(_headerCompleted); assertTrue(_messageCompleted); parser.reset(); init(); parser.parseNext(buffer); parser.atEOF(); assertEquals("HTTP/1.1", _methodOrVersion); assertEquals("200", _uriOrStatus); assertEquals("Correct", _versionOrReason); assertEquals(_content.length(), 10); assertTrue(_headerCompleted); assertTrue(_messageCompleted); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn((short)3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Server receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Fields headers = stream.createFields(); headers.put("response", "ok"); stream.reply(Version.V3, (byte)0, headers); stream.sendLastData("the server has received messages".getBytes()); } }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Bar<List<String>>>() { }, null); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Car<List<String>>>() { }, null); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Par>() { }, null); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(barRef); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(carRef); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.Integer>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(parRef); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(sarRef); MethodGenericTypeBind list = getterMap.get("list"); System.out.println(list.getType().getTypeName()); Assert.assertThat(list.getType().getTypeName(), is("java.util.List<java.util.Map<java.lang.String, test.utils.lang.TestGenericTypeReference$Foo>>")); MethodGenericTypeBind sar = getterMap.get("sar"); Assert.assertThat(sar.getType().getTypeName(), is("java.lang.Integer")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Config load(String file) { Dom dom = new DefaultDom(); // 获得Xml文档对象 Document doc = dom.getDocument(file == null ? DEFAULT_CONFIG_FILE : file); // 得到根节点 Element root = dom.getRoot(doc); load(root, dom); return config; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public Config load(String file) { Dom dom = new DefaultDom(); Document doc = dom.getDocument(file == null ? DEFAULT_CONFIG_FILE : file); Element root = dom.getRoot(doc); load(root, dom); return config; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void initializeHTTP2ClientConnection(final Session session, final HTTP2ClientContext context, final SSLSession sslSession) { final HTTP2ClientConnection connection = new HTTP2ClientConnection(config, session, sslSession, context.listener); Map<Integer, Integer> settings = context.listener.onPreface(connection.getHttp2Session()); if (settings == null) { settings = Collections.emptyMap(); } PrefaceFrame prefaceFrame = new PrefaceFrame(); SettingsFrame settingsFrame = new SettingsFrame(settings, false); SessionSPI sessionSPI = connection.getSessionSPI(); int windowDelta = config.getInitialSessionRecvWindow() - FlowControlStrategy.DEFAULT_WINDOW_SIZE; Callback callback = new Callback() { @Override public void succeeded() { context.promise.succeeded(connection); } @Override public void failed(Throwable x) { try { connection.close(); } catch (IOException e) { log.error("http2 connection initialization error", e); } context.promise.failed(x); } }; if (windowDelta > 0) { sessionSPI.updateRecvWindow(windowDelta); sessionSPI.frames(null, callback, prefaceFrame, settingsFrame, new WindowUpdateFrame(0, windowDelta)); } else { sessionSPI.frames(null, callback, prefaceFrame, settingsFrame); } } #location 36 #vulnerability type RESOURCE_LEAK
#fixed code private void initializeHTTP2ClientConnection(final Session session, final HTTP2ClientContext context, final SSLSession sslSession) { HTTP2ClientConnection.initialize(config, session, context, sslSession); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Bar<List<String>>>() { }, null); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Car<List<String>>>() { }, null); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Par>() { }, null); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); } #location 36 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(barRef); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(carRef); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.Integer>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(parRef); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(sarRef); MethodGenericTypeBind list = getterMap.get("list"); System.out.println(list.getType().getTypeName()); Assert.assertThat(list.getType().getTypeName(), is("java.util.List<java.util.Map<java.lang.String, test.utils.lang.TestGenericTypeReference$Foo>>")); MethodGenericTypeBind sar = getterMap.get("sar"); Assert.assertThat(sar.getType().getTypeName(), is("java.lang.Integer")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test() { MultiPartContentProvider multiPartProvider = new MultiPartContentProvider(); System.out.println(multiPartProvider.getContentType()); multiPartProvider.addFieldPart("test1", new StringContentProvider("hello multi part1"), null); multiPartProvider.addFieldPart("test2", new StringContentProvider("hello multi part2"), null); multiPartProvider.close(); multiPartProvider.setListener(() -> System.out.println("on content")); List<ByteBuffer> list = new ArrayList<>(); for (ByteBuffer buf : multiPartProvider) { list.add(buf); } String value = BufferUtils.toString(list); System.out.println(value); System.out.println(multiPartProvider.getLength()); Assert.assertThat(multiPartProvider.getLength(), greaterThan(0L)); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void test() { MultiPartContentProvider multiPartProvider = new MultiPartContentProvider(); System.out.println(multiPartProvider.getContentType()); multiPartProvider.addFieldPart("test1", new StringContentProvider("hello multi part1"), null); multiPartProvider.addFieldPart("test2", new StringContentProvider("hello multi part2"), null); multiPartProvider.close(); multiPartProvider.setListener(() -> System.out.println("on content")); List<ByteBuffer> list = new ArrayList<>(); for (ByteBuffer buf : multiPartProvider) { list.add(buf); } String value = $.buffer.toString(list); System.out.println(value); System.out.println(multiPartProvider.getLength()); Assert.assertThat(multiPartProvider.getLength(), greaterThan(0L)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Server receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Fields headers = stream.createFields(); headers.put("response", "ok"); stream.reply(Version.V3, (byte)0, headers); stream.sendLastData("the server has received messages".getBytes()); } }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); try(SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false));) { clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMethodType() { Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>>() { }, null); MethodGenericTypeBind extInfo = getterMap.get("extInfo"); ParameterizedType parameterizedType = (ParameterizedType) extInfo.getType(); System.out.println(parameterizedType.getTypeName()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(extInfo.getMethodType(), is(MethodType.GETTER)); Map<String, MethodGenericTypeBind> setterMap = ReflectUtils.getGenericBeanSetterMethods( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>>() { }, null); extInfo = setterMap.get("extInfo"); parameterizedType = (ParameterizedType) extInfo.getType(); System.out.println(parameterizedType.getTypeName()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(extInfo.getMethodType(), is(MethodType.SETTER)); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testMethodType() { Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(reqRef); MethodGenericTypeBind extInfo = getterMap.get("extInfo"); ParameterizedType parameterizedType = (ParameterizedType) extInfo.getType(); System.out.println(parameterizedType.getTypeName()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(extInfo.getMethodType(), is(MethodType.GETTER)); Map<String, MethodGenericTypeBind> setterMap = ReflectUtils.getGenericBeanSetterMethods(reqRef); extInfo = setterMap.get("extInfo"); parameterizedType = (ParameterizedType) extInfo.getType(); System.out.println(parameterizedType.getTypeName()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(extInfo.getMethodType(), is(MethodType.SETTER)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Bar<List<String>>>() { }, null); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Car<List<String>>>() { }, null); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Par>() { }, null); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(barRef); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(carRef); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.Integer>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(parRef); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(sarRef); MethodGenericTypeBind list = getterMap.get("list"); System.out.println(list.getType().getTypeName()); Assert.assertThat(list.getType().getTypeName(), is("java.util.List<java.util.Map<java.lang.String, test.utils.lang.TestGenericTypeReference$Foo>>")); MethodGenericTypeBind sar = getterMap.get("sar"); Assert.assertThat(sar.getType().getTypeName(), is("java.lang.Integer")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn((short)3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); } #location 110 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Server receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Fields headers = stream.createFields(); headers.put("response", "ok"); stream.reply(Version.V3, (byte)0, headers); stream.sendLastData("the server has received messages".getBytes()); } }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPathContent() throws URISyntaxException, IOException { Path path = Paths.get($.class.getResource("/poem.txt").toURI()); System.out.println(path.toAbsolutePath()); PathContentProvider pathContentProvider = new PathContentProvider(path); MultiPartContentProvider multiPartProvider = new MultiPartContentProvider(); multiPartProvider.addFilePart("poetry", "poem.txt", pathContentProvider, null); multiPartProvider.close(); multiPartProvider.setListener(() -> System.out.println("on content")); List<ByteBuffer> list = new ArrayList<>(); for (ByteBuffer buf : multiPartProvider) { list.add(buf); } System.out.println(multiPartProvider.getLength()); Assert.assertThat(multiPartProvider.getLength(), greaterThan(0L)); Assert.assertThat(multiPartProvider.getLength(), is(BufferUtils.remaining(list))); } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testPathContent() throws URISyntaxException, IOException { Path path = Paths.get($.class.getResource("/poem.txt").toURI()); System.out.println(path.toAbsolutePath()); PathContentProvider pathContentProvider = new PathContentProvider(path); MultiPartContentProvider multiPartProvider = new MultiPartContentProvider(); multiPartProvider.addFilePart("poetry", "poem.txt", pathContentProvider, null); multiPartProvider.close(); multiPartProvider.setListener(() -> System.out.println("on content")); List<ByteBuffer> list = new ArrayList<>(); for (ByteBuffer buf : multiPartProvider) { list.add(buf); } System.out.println(multiPartProvider.getLength()); Assert.assertThat(multiPartProvider.getLength(), greaterThan(0L)); Assert.assertThat(multiPartProvider.getLength(), is($.buffer.remaining(list))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMultiParse() throws Exception { ByteBuffer buffer = BufferUtils.toBuffer("GET /mp HTTP/1.0\015\012" + "Connection: Keep-Alive\015\012" + "Header1: value1\015\012" + "Transfer-Encoding: chunked\015\012" + "\015\012" + "a;\015\012" + "0123456789\015\012" + "1a\015\012" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ\015\012" + "0\015\012" + "\015\012" + "POST /foo HTTP/1.0\015\012" + "Connection: Keep-Alive\015\012" + "Header2: value2\015\012" + "Content-Length: 0\015\012" + "\015\012" + "PUT /doodle HTTP/1.0\015\012" + "Connection: close\015\012" + "Header3: value3\015\012" + "Content-Length: 10\015\012" + "\015\012" + "0123456789\015\012"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parser.parseNext(buffer); assertEquals("GET", _methodOrVersion); assertEquals("/mp", _uriOrStatus); assertEquals("HTTP/1.0", _versionOrReason); assertEquals(2, _headers); assertEquals("Header1", _hdr[1]); assertEquals("value1", _val[1]); assertEquals("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", _content); parser.reset(); init(); parser.parseNext(buffer); assertEquals("POST", _methodOrVersion); assertEquals("/foo", _uriOrStatus); assertEquals("HTTP/1.0", _versionOrReason); assertEquals(2, _headers); assertEquals("Header2", _hdr[1]); assertEquals("value2", _val[1]); assertEquals(null, _content); parser.reset(); init(); parser.parseNext(buffer); parser.atEOF(); assertEquals("PUT", _methodOrVersion); assertEquals("/doodle", _uriOrStatus); assertEquals("HTTP/1.0", _versionOrReason); assertEquals(2, _headers); assertEquals("Header3", _hdr[1]); assertEquals("value3", _val[1]); assertEquals("0123456789", _content); } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testMultiParse() throws Exception { ByteBuffer buffer = BufferUtils.toBuffer("GET /mp HTTP/1.0\015\012" + "Connection: Keep-Alive\015\012" + "Header1: value1\015\012" + "Transfer-Encoding: chunked\015\012" + "\015\012" + "a;\015\012" + "0123456789\015\012" + "1a\015\012" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ\015\012" + "0\015\012" + "\015\012" + "POST /foo HTTP/1.0\015\012" + "Connection: Keep-Alive\015\012" + "Header2: value2\015\012" + "Content-Length: 0\015\012" + "\015\012" + "PUT /doodle HTTP/1.0\015\012" + "Connection: close\015\012" + "Header3: value3\015\012" + "Content-Length: 10\015\012" + "\015\012" + "0123456789\015\012"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parser.parseNext(buffer); assertEquals("GET", _methodOrVersion); assertEquals("/mp", _uriOrStatus); assertEquals("HTTP/1.0", _versionOrReason); assertEquals(2, _headers); assertEquals("Header1", _hdr[1]); assertEquals("value1", _val[1]); assertEquals("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", _content); parser.reset(); init(); parser.parseNext(buffer); assertEquals("POST", _methodOrVersion); assertEquals("/foo", _uriOrStatus); assertEquals("HTTP/1.0", _versionOrReason); assertEquals(2, _headers); assertEquals("Header2", _hdr[1]); assertEquals("value2", _val[1]); assertEquals(null, _content); parser.reset(); init(); parser.parseNext(buffer); parser.atEOF(); assertEquals("PUT", _methodOrVersion); assertEquals("/doodle", _uriOrStatus); assertEquals("HTTP/1.0", _versionOrReason); assertEquals(2, _headers); assertEquals("Header3", _hdr[1]); assertEquals("value3", _val[1]); assertEquals("0123456789", _content); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Server receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Fields headers = stream.createFields(); headers.put("response", "ok"); stream.reply(Version.V3, (byte)0, headers); stream.sendLastData("the server has received messages".getBytes()); } }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); try(SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false));) { clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean directUpgradeHTTP2(MetaData.Request request) { if (HttpMethod.PRI.is(request.getMethod())) { HTTP2ServerConnection http2ServerConnection = new HTTP2ServerConnection(config, tcpSession, secureSession, serverSessionListener); tcpSession.attachObject(http2ServerConnection); http2ServerConnection.getParser().directUpgrade(); upgradeHTTP2Successfully = true; return true; } else { return false; } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code HTTP1ServerConnection(HTTP2Configuration config, Session tcpSession, SecureSession secureSession, HTTP1ServerRequestHandler requestHandler, ServerSessionListener serverSessionListener) { super(config, secureSession, tcpSession, requestHandler, null); requestHandler.connection = this; this.serverSessionListener = serverSessionListener; this.serverRequestHandler = requestHandler; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testInputStreamContent() { InputStream inputStream = $.class.getResourceAsStream("/poem.txt"); InputStreamContentProvider inputStreamContentProvider = new InputStreamContentProvider(inputStream); MultiPartContentProvider multiPartProvider = new MultiPartContentProvider(); System.out.println(multiPartProvider.getContentType()); multiPartProvider.addFilePart("poetry", "poem.txt", inputStreamContentProvider, null); multiPartProvider.close(); multiPartProvider.setListener(() -> System.out.println("on content")); List<ByteBuffer> list = new ArrayList<>(); for (ByteBuffer buf : multiPartProvider) { list.add(buf); } String value = BufferUtils.toString(list); Assert.assertThat(value.length(), greaterThan(0)); System.out.println(multiPartProvider.getLength()); Assert.assertThat(multiPartProvider.getLength(), lessThan(0L)); } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testInputStreamContent() { InputStream inputStream = $.class.getResourceAsStream("/poem.txt"); InputStreamContentProvider inputStreamContentProvider = new InputStreamContentProvider(inputStream); MultiPartContentProvider multiPartProvider = new MultiPartContentProvider(); System.out.println(multiPartProvider.getContentType()); multiPartProvider.addFilePart("poetry", "poem.txt", inputStreamContentProvider, null); multiPartProvider.close(); multiPartProvider.setListener(() -> System.out.println("on content")); List<ByteBuffer> list = new ArrayList<>(); for (ByteBuffer buf : multiPartProvider) { list.add(buf); } String value = $.buffer.toString(list); Assert.assertThat(value.length(), greaterThan(0)); System.out.println(multiPartProvider.getLength()); Assert.assertThat(multiPartProvider.getLength(), lessThan(0L)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetLocationOfClass() throws Exception { // Classes from maven dependencies Assert.assertThat(TypeUtils.getLocationOfClass(Assert.class).toASCIIString(), Matchers.containsString("repository")); // Class from project dependencies Assert.assertThat(TypeUtils.getLocationOfClass(TypeUtils.class).toASCIIString(), Matchers.containsString("/classes/")); // Class from JVM core String expectedJavaBase = "/rt.jar"; if (JDK.IS_9) expectedJavaBase = "/java.base/"; Assert.assertThat(TypeUtils.getLocationOfClass(String.class).toASCIIString(), Matchers.containsString(expectedJavaBase)); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetLocationOfClass() throws Exception { // Class from project dependencies Assert.assertThat(TypeUtils.getLocationOfClass(TypeUtils.class).toASCIIString(), Matchers.containsString("/classes/")); // Class from JVM core String expectedJavaBase = "/rt.jar"; if (JDK.IS_9) expectedJavaBase = "/java.base/"; Assert.assertThat(TypeUtils.getLocationOfClass(String.class).toASCIIString(), Matchers.containsString(expectedJavaBase)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Throwable { FileInputStream in = null; ByteArrayOutputStream out = null; try { in = new FileInputStream(new File("/Users/qiupengtao", "fireflykeys")); out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; for (int i = 0; (i = in.read(buf)) != -1;) { byte[] temp = new byte[i]; System.arraycopy(buf, 0, temp, 0, i); out.write(temp); } byte[] ret = out.toByteArray(); // System.out.println(ret.length); System.out.println(Arrays.toString(ret)); } finally { in.close(); out.close(); } } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) throws Throwable{ Certificate[] certificates = getCertificates("fireflySSLkeys.jks", "fireflySSLkeys"); for(Certificate certificate : certificates) { System.out.println(certificate); } certificates = getCertificates("fireflykeys", "fireflysource"); for(Certificate certificate : certificates) { System.out.println(certificate); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Bar<List<String>>>() { }, null); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Car<List<String>>>() { }, null); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Par>() { }, null); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(barRef); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(carRef); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.Integer>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(parRef); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(sarRef); MethodGenericTypeBind list = getterMap.get("list"); System.out.println(list.getType().getTypeName()); Assert.assertThat(list.getType().getTypeName(), is("java.util.List<java.util.Map<java.lang.String, test.utils.lang.TestGenericTypeReference$Foo>>")); MethodGenericTypeBind sar = getterMap.get("sar"); Assert.assertThat(sar.getType().getTypeName(), is("java.lang.Integer")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Word2VecModel fromBinFile(File file, ByteOrder byteOrder) throws IOException { try (FileInputStream fis = new FileInputStream(file);) { DataInput in = (byteOrder == ByteOrder.BIG_ENDIAN) ? new DataInputStream(fis) : new SwappedDataInputStream(fis); StringBuilder sb = new StringBuilder(); char c = (char) in.readByte(); while (c != '\n') { sb.append(c); c = (char) in.readByte(); } String firstLine = sb.toString(); int index = firstLine.indexOf(' '); Preconditions.checkState(index != -1, "Expected a space in the first line of file '%s': '%s'", file.getAbsolutePath(), firstLine); int vocabSize = Integer.parseInt(firstLine.substring(0, index)); int layerSize = Integer.parseInt(firstLine.substring(index + 1)); List<String> vocabs = Lists.newArrayList(); List<Double> vectors = Lists.newArrayList(); for (int lineno = 0; lineno < vocabSize; lineno++) { sb = new StringBuilder(); c = (char) in.readByte(); while (c != ' ') { // ignore newlines in front of words (some binary files have newline, // some don't) if (c != '\n') { sb.append(c); } c = (char) in.readByte(); } vocabs.add(sb.toString()); for (int i = 0; i < layerSize; i++) { vectors.add((double) in.readFloat()); } } return fromThrift(new Word2VecModelThrift() .setLayerSize(layerSize) .setVocab(vocabs) .setVectors(vectors)); } } #location 44 #vulnerability type RESOURCE_LEAK
#fixed code public static Word2VecModel fromBinFile(File file, ByteOrder byteOrder) throws IOException { try (FileInputStream fis = new FileInputStream(file);) { final FileChannel channel = fis.getChannel(); final long oneGB = 1024 * 1024 * 1024; MappedByteBuffer buffer = channel.map( FileChannel.MapMode.READ_ONLY, 0, Math.min(channel.size(), Integer.MAX_VALUE)); buffer.order(byteOrder); int bufferCount = 1; // Java's NIO only allows memory-mapping up to 2GB. To work around this problem, we re-map // every gigabyte. To calculate offsets correctly, we have to keep track how many gigabytes // we've already skipped. That's what this is for. StringBuilder sb = new StringBuilder(); char c = (char)buffer.get(); while (c != '\n') { sb.append(c); c = (char)buffer.get(); } String firstLine = sb.toString(); int index = firstLine.indexOf(' '); Preconditions.checkState(index != -1, "Expected a space in the first line of file '%s': '%s'", file.getAbsolutePath(), firstLine); final int vocabSize = Integer.parseInt(firstLine.substring(0, index)); final int layerSize = Integer.parseInt(firstLine.substring(index + 1)); logger.info( String.format("Loading %d vectors with dimensionality %d", vocabSize, layerSize)); List<String> vocabs = new ArrayList<String>(vocabSize); double vectors[] = new double[vocabSize * layerSize]; long lastLogMessage = System.currentTimeMillis(); final float[] floats = new float[layerSize]; for (int lineno = 0; lineno < vocabSize; lineno++) { // read vocab sb.setLength(0); c = (char)buffer.get(); while (c != ' ') { // ignore newlines in front of words (some binary files have newline, // some don't) if (c != '\n') { sb.append(c); } c = (char)buffer.get(); } vocabs.add(sb.toString()); // read vector final FloatBuffer floatBuffer = buffer.asFloatBuffer(); floatBuffer.get(floats); for(int i = 0; i < floats.length; ++i) { vectors[lineno * layerSize + i] = floats[i]; } buffer.position(buffer.position() + 4 * layerSize); // print log final long now = System.currentTimeMillis(); if(now - lastLogMessage > 1000) { final double percentage = ((double)(lineno + 1) / (double)vocabSize) * 100.0; logger.info( String.format("Loaded %d/%d vectors (%f%%)", lineno + 1, vocabSize, percentage)); lastLogMessage = now; } // remap file if(buffer.position() > oneGB) { final int newPosition = (int)(buffer.position() - oneGB); final long size = Math.min(channel.size() - oneGB * bufferCount, Integer.MAX_VALUE); logger.debug( String.format( "Remapping for GB number %d. Start: %d, size: %d", bufferCount, oneGB * bufferCount, size)); buffer = channel.map( FileChannel.MapMode.READ_ONLY, oneGB * bufferCount, size); buffer.order(byteOrder); buffer.position(newPosition); bufferCount += 1; } } return new Word2VecModel(vocabs, layerSize, vectors); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Word2VecModel fromBinFile(File file, ByteOrder byteOrder) throws IOException { try (FileInputStream fis = new FileInputStream(file);) { DataInput in = (byteOrder == ByteOrder.BIG_ENDIAN) ? new DataInputStream(fis) : new SwappedDataInputStream(fis); StringBuilder sb = new StringBuilder(); char c = (char) in.readByte(); while (c != '\n') { sb.append(c); c = (char) in.readByte(); } String firstLine = sb.toString(); int index = firstLine.indexOf(' '); Preconditions.checkState(index != -1, "Expected a space in the first line of file '%s': '%s'", file.getAbsolutePath(), firstLine); int vocabSize = Integer.parseInt(firstLine.substring(0, index)); int layerSize = Integer.parseInt(firstLine.substring(index + 1)); List<String> vocabs = Lists.newArrayList(); List<Double> vectors = Lists.newArrayList(); for (int lineno = 0; lineno < vocabSize; lineno++) { sb = new StringBuilder(); c = (char) in.readByte(); while (c != ' ') { // ignore newlines in front of words (some binary files have newline, // some don't) if (c != '\n') { sb.append(c); } c = (char) in.readByte(); } vocabs.add(sb.toString()); for (int i = 0; i < layerSize; i++) { vectors.add((double) in.readFloat()); } } return fromThrift(new Word2VecModelThrift() .setLayerSize(layerSize) .setVocab(vocabs) .setVectors(vectors)); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public static Word2VecModel fromBinFile(File file, ByteOrder byteOrder) throws IOException { try (FileInputStream fis = new FileInputStream(file);) { final FileChannel channel = fis.getChannel(); final long oneGB = 1024 * 1024 * 1024; MappedByteBuffer buffer = channel.map( FileChannel.MapMode.READ_ONLY, 0, Math.min(channel.size(), Integer.MAX_VALUE)); buffer.order(byteOrder); int bufferCount = 1; // Java's NIO only allows memory-mapping up to 2GB. To work around this problem, we re-map // every gigabyte. To calculate offsets correctly, we have to keep track how many gigabytes // we've already skipped. That's what this is for. StringBuilder sb = new StringBuilder(); char c = (char)buffer.get(); while (c != '\n') { sb.append(c); c = (char)buffer.get(); } String firstLine = sb.toString(); int index = firstLine.indexOf(' '); Preconditions.checkState(index != -1, "Expected a space in the first line of file '%s': '%s'", file.getAbsolutePath(), firstLine); final int vocabSize = Integer.parseInt(firstLine.substring(0, index)); final int layerSize = Integer.parseInt(firstLine.substring(index + 1)); logger.info( String.format("Loading %d vectors with dimensionality %d", vocabSize, layerSize)); List<String> vocabs = new ArrayList<String>(vocabSize); double vectors[] = new double[vocabSize * layerSize]; long lastLogMessage = System.currentTimeMillis(); final float[] floats = new float[layerSize]; for (int lineno = 0; lineno < vocabSize; lineno++) { // read vocab sb.setLength(0); c = (char)buffer.get(); while (c != ' ') { // ignore newlines in front of words (some binary files have newline, // some don't) if (c != '\n') { sb.append(c); } c = (char)buffer.get(); } vocabs.add(sb.toString()); // read vector final FloatBuffer floatBuffer = buffer.asFloatBuffer(); floatBuffer.get(floats); for(int i = 0; i < floats.length; ++i) { vectors[lineno * layerSize + i] = floats[i]; } buffer.position(buffer.position() + 4 * layerSize); // print log final long now = System.currentTimeMillis(); if(now - lastLogMessage > 1000) { final double percentage = ((double)(lineno + 1) / (double)vocabSize) * 100.0; logger.info( String.format("Loaded %d/%d vectors (%f%%)", lineno + 1, vocabSize, percentage)); lastLogMessage = now; } // remap file if(buffer.position() > oneGB) { final int newPosition = (int)(buffer.position() - oneGB); final long size = Math.min(channel.size() - oneGB * bufferCount, Integer.MAX_VALUE); logger.debug( String.format( "Remapping for GB number %d. Start: %d, size: %d", bufferCount, oneGB * bufferCount, size)); buffer = channel.map( FileChannel.MapMode.READ_ONLY, oneGB * bufferCount, size); buffer.order(byteOrder); buffer.position(newPosition); bufferCount += 1; } } return new Word2VecModel(vocabs, layerSize, vectors); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Word2VecModel fromBinFile(File file, ByteOrder byteOrder) throws IOException { try (FileInputStream fis = new FileInputStream(file);) { DataInput in = (byteOrder == ByteOrder.BIG_ENDIAN) ? new DataInputStream(fis) : new SwappedDataInputStream(fis); StringBuilder sb = new StringBuilder(); char c = (char) in.readByte(); while (c != '\n') { sb.append(c); c = (char) in.readByte(); } String firstLine = sb.toString(); int index = firstLine.indexOf(' '); Preconditions.checkState(index != -1, "Expected a space in the first line of file '%s': '%s'", file.getAbsolutePath(), firstLine); int vocabSize = Integer.parseInt(firstLine.substring(0, index)); int layerSize = Integer.parseInt(firstLine.substring(index + 1)); List<String> vocabs = Lists.newArrayList(); List<Double> vectors = Lists.newArrayList(); for (int lineno = 0; lineno < vocabSize; lineno++) { sb = new StringBuilder(); c = (char) in.readByte(); while (c != ' ') { // ignore newlines in front of words (some binary files have newline, // some don't) if (c != '\n') { sb.append(c); } c = (char) in.readByte(); } vocabs.add(sb.toString()); for (int i = 0; i < layerSize; i++) { vectors.add((double) in.readFloat()); } } return fromThrift(new Word2VecModelThrift() .setLayerSize(layerSize) .setVocab(vocabs) .setVectors(vectors)); } } #location 44 #vulnerability type RESOURCE_LEAK
#fixed code public static Word2VecModel fromBinFile(File file, ByteOrder byteOrder) throws IOException { try (FileInputStream fis = new FileInputStream(file);) { final FileChannel channel = fis.getChannel(); final long oneGB = 1024 * 1024 * 1024; MappedByteBuffer buffer = channel.map( FileChannel.MapMode.READ_ONLY, 0, Math.min(channel.size(), Integer.MAX_VALUE)); buffer.order(byteOrder); int bufferCount = 1; // Java's NIO only allows memory-mapping up to 2GB. To work around this problem, we re-map // every gigabyte. To calculate offsets correctly, we have to keep track how many gigabytes // we've already skipped. That's what this is for. StringBuilder sb = new StringBuilder(); char c = (char)buffer.get(); while (c != '\n') { sb.append(c); c = (char)buffer.get(); } String firstLine = sb.toString(); int index = firstLine.indexOf(' '); Preconditions.checkState(index != -1, "Expected a space in the first line of file '%s': '%s'", file.getAbsolutePath(), firstLine); final int vocabSize = Integer.parseInt(firstLine.substring(0, index)); final int layerSize = Integer.parseInt(firstLine.substring(index + 1)); logger.info( String.format("Loading %d vectors with dimensionality %d", vocabSize, layerSize)); List<String> vocabs = new ArrayList<String>(vocabSize); double vectors[] = new double[vocabSize * layerSize]; long lastLogMessage = System.currentTimeMillis(); final float[] floats = new float[layerSize]; for (int lineno = 0; lineno < vocabSize; lineno++) { // read vocab sb.setLength(0); c = (char)buffer.get(); while (c != ' ') { // ignore newlines in front of words (some binary files have newline, // some don't) if (c != '\n') { sb.append(c); } c = (char)buffer.get(); } vocabs.add(sb.toString()); // read vector final FloatBuffer floatBuffer = buffer.asFloatBuffer(); floatBuffer.get(floats); for(int i = 0; i < floats.length; ++i) { vectors[lineno * layerSize + i] = floats[i]; } buffer.position(buffer.position() + 4 * layerSize); // print log final long now = System.currentTimeMillis(); if(now - lastLogMessage > 1000) { final double percentage = ((double)(lineno + 1) / (double)vocabSize) * 100.0; logger.info( String.format("Loaded %d/%d vectors (%f%%)", lineno + 1, vocabSize, percentage)); lastLogMessage = now; } // remap file if(buffer.position() > oneGB) { final int newPosition = (int)(buffer.position() - oneGB); final long size = Math.min(channel.size() - oneGB * bufferCount, Integer.MAX_VALUE); logger.debug( String.format( "Remapping for GB number %d. Start: %d, size: %d", bufferCount, oneGB * bufferCount, size)); buffer = channel.map( FileChannel.MapMode.READ_ONLY, oneGB * bufferCount, size); buffer.order(byteOrder); buffer.position(newPosition); bufferCount += 1; } } return new Word2VecModel(vocabs, layerSize, vectors); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(final String... args) throws IOException, ExecutionException, InterruptedException { final String project = Util.defaultProject(); GoogleCredential credential; // Use credentials from file if available try { credential = GoogleCredential .fromStream(new FileInputStream("credentials.json")) .createScoped(PubsubScopes.all()); } catch (IOException e) { credential = GoogleCredential.getApplicationDefault() .createScoped(PubsubScopes.all()); } final Pubsub pubsub = Pubsub.builder() .credential(credential) .compressionLevel(Deflater.BEST_SPEED) .enabledCipherSuites(Util.nonGcmCiphers()) .build(); LoggingConfigurator.configureDefaults("benchmark", WARN); final String subscription = System.getenv("GOOGLE_PUBSUB_SUBSCRIPTION"); if (subscription == null) { System.err.println("Please specify a subscription using the GOOGLE_PUBSUB_SUBSCRIPTION environment variable."); System.exit(1); } System.out.println("Consuming from GOOGLE_PUBSUB_SUBSCRIPTION='" + subscription + "'"); final ProgressMeter meter = new ProgressMeter(); final ProgressMeter.Metric receives = meter.group("operations").metric("receives", "messages"); final Puller puller = Puller.builder() .pubsub(pubsub) .batchSize(1000) .concurrency(PULLER_CONCURRENCY) .project(project) .subscription(subscription) .messageHandler(new Handler(receives)) .build(); while (true) { Thread.sleep(1000); } } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(final String... args) throws IOException, ExecutionException, InterruptedException { final String project = Util.defaultProject(); GoogleCredential credential; // Use credentials from file if available try { credential = GoogleCredential .fromStream(new FileInputStream("credentials.json")) .createScoped(PubsubScopes.all()); } catch (IOException e) { credential = GoogleCredential.getApplicationDefault() .createScoped(PubsubScopes.all()); } final Pubsub pubsub = Pubsub.builder() .credential(credential) .compressionLevel(Deflater.BEST_SPEED) .enabledCipherSuites(Util.nonGcmCiphers()) .build(); LoggingConfigurator.configureDefaults("benchmark", WARN); System.setProperty("https.cipherSuites", Joiner.on(',').join(Util.nonGcmCiphers())); final String subscription = System.getenv("GOOGLE_PUBSUB_SUBSCRIPTION"); if (subscription == null) { System.err.println("Please specify a subscription using the GOOGLE_PUBSUB_SUBSCRIPTION environment variable."); System.exit(1); } System.out.println("Consuming from GOOGLE_PUBSUB_SUBSCRIPTION='" + subscription + "'"); final ProgressMeter meter = new ProgressMeter(); final ProgressMeter.Metric receives = meter.group("operations").metric("receives", "messages"); final Puller puller = Puller.builder() .pubsub(pubsub) .batchSize(1000) .concurrency(PULLER_CONCURRENCY) .project(project) .subscription(subscription) .messageHandler(new Handler(receives)) .build(); while (true) { Thread.sleep(1000); System.out.println("outstanding messages: " + puller.outstandingMessages()); System.out.println("outstanding requests: " + puller.outstandingRequests()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Mono<Payload> requestResponse(Payload payload) { List<String> metadata = getRoutingMetadata(payload); RSocket service = findRSocket(metadata); if (service != null) { return service.requestResponse(payload); } MonoProcessor<RSocket> processor = MonoProcessor.create(); this.registry.pendingRequest(metadata, processor); return processor .log("pending-request") .flatMap(rSocket -> rSocket.requestResponse(payload)); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Mono<Payload> requestResponse(Payload payload) { RSocket service = findRSocket(payload); return service.requestResponse(payload); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Mono<RSocket> accept(ConnectionSetupPayload setup, RSocket sendingSocket) { if (setup.hasMetadata()) { // and setup.metadataMimeType() is Announcement metadata String annoucementMetadata = Metadata.decodeAnnouncement(setup.sliceMetadata()); List<String> tags = Collections.singletonList(annoucementMetadata); registry.register(tags, sendingSocket); List<MonoProcessor<RSocket>> processors = this.registry.getPendingRequests(tags); if (!CollectionUtils.isEmpty(processors)) { processors.forEach(processor -> { processor.log("resume-pending-request"); processor.onNext(sendingSocket); processor.onComplete(); }); } } return Mono.just(proxyRSocket); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Mono<RSocket> accept(ConnectionSetupPayload setup, RSocket sendingSocket) { if (setup.hasMetadata()) { // and setup.metadataMimeType() is Announcement metadata String annoucementMetadata = Metadata.decodeAnnouncement(setup.sliceMetadata()); List<String> tags = Collections.singletonList(annoucementMetadata); registry.register(tags, sendingSocket); } return Mono.just(proxyRSocket); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private RSocket findRSocket(List<String> tags) { if (tags == null) return null; List<RSocket> rsockets = registry.getRegistered(tags); if (CollectionUtils.isEmpty(rsockets)) { log.debug("Unable to find destination RSocket for " + tags); return null; } // TODO: deal with connecting to cluster? // TODO: load balancing RSocket rsocket = rsockets.get(0); // if not connected previously, initialize connection return rsocket; } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code private RSocket findRSocket(List<String> tags) { if (tags == null) return null; RSocket rsocket = registry.getRegistered(tags); if (rsocket == null) { log.debug("Unable to find destination RSocket for " + tags); } // TODO: deal with connecting to cluster? return rsocket; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Flux<Payload> requestStream(Payload payload) { List<String> metadata = getRoutingMetadata(payload); RSocket service = findRSocket(metadata); if (service != null) { return service.requestStream(payload); } MonoProcessor<RSocket> processor = MonoProcessor.create(); this.registry.pendingRequest(metadata, processor); return processor .log("pending-request") .flatMapMany(rSocket -> rSocket.requestStream(payload)); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Flux<Payload> requestStream(Payload payload) { RSocket service = findRSocket(payload); return service.requestStream(payload); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { Map<String, String> weights = getWeights(exchange); for (String group : groupWeights.keySet()) { GroupWeightConfig config = groupWeights.get(group); if (config == null) { if (log.isDebugEnabled()) { log.debug("No GroupWeightConfig found for group: " + group); } continue; // nothing we can do, but this is odd } double r = this.random.nextDouble(); synchronized (config) { List<Double> ranges = config.ranges; if (log.isTraceEnabled()) { log.trace("Weight for group: " + group + ", ranges: " + ranges + ", r: " + r); } for (int i = 0; i < ranges.size() - 1; i++) { if (r >= ranges.get(i) && r < ranges.get(i + 1)) { String routeId = config.rangeIndexes.get(i); weights.put(group, routeId); break; } } } } if (log.isTraceEnabled()) { log.trace("Weights attr: " + weights); } return chain.filter(exchange); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { Map<String, String> weights = getWeights(exchange); for (String group : groupWeights.keySet()) { GroupWeightConfig config = groupWeights.get(group); if (config == null) { if (log.isDebugEnabled()) { log.debug("No GroupWeightConfig found for group: " + group); } continue; // nothing we can do, but this is odd } double r = this.random.nextDouble(); List<Double> ranges = config.ranges; if (log.isTraceEnabled()) { log.trace("Weight for group: " + group + ", ranges: " + ranges + ", r: " + r); } for (int i = 0; i < ranges.size() - 1; i++) { if (r >= ranges.get(i) && r < ranges.get(i + 1)) { String routeId = config.rangeIndexes.get(i); weights.put(group, routeId); break; } } } if (log.isTraceEnabled()) { log.trace("Weights attr: " + weights); } return chain.filter(exchange); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Flux<Payload> requestChannel(Payload payload, Publisher<Payload> payloads) { GatewayExchange exchange = GatewayExchange.fromPayload(REQUEST_CHANNEL, payload); Tags tags = getTags(exchange); Tags responderTags = tags.and("source", "responder"); return findRSocketOrCreatePending(exchange) .flatMapMany(rSocket -> { Tags requesterTags = tags.and("source", "requester"); Flux<Payload> flux = Flux.from(payloads) .doOnNext(s -> count("forward.request.channel.payload", requesterTags)) .doOnError(t -> count("forward.request.channel.error", requesterTags)) .doFinally(s -> count("forward.request.channel", requesterTags)); if (rSocket instanceof ResponderRSocket) { ResponderRSocket socket = (ResponderRSocket) rSocket; return socket.requestChannel(payload, flux) .log(GatewayRSocket.class.getName()+".request-channel", Level.FINE); } return rSocket.requestChannel(flux); }) .doOnNext(s -> count("forward.request.channel.payload", responderTags)) .doOnError(t -> count("forward.request.channel.error", responderTags)) .doFinally(s -> count("forward.request.channel", responderTags)); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Flux<Payload> requestChannel(Payload payload, Publisher<Payload> payloads) { GatewayExchange exchange = createExchange(REQUEST_CHANNEL, payload); Tags responderTags = Tags.of("source", "responder"); return findRSocketOrCreatePending(exchange) .flatMapMany(rSocket -> { Tags requesterTags = Tags.of("source", "requester"); Flux<Payload> flux = Flux.from(payloads) .doOnNext(s -> count(exchange, "payload", requesterTags)) .doOnError(t -> count(exchange, "error", requesterTags)) .doFinally(s -> count(exchange, requesterTags)); if (rSocket instanceof ResponderRSocket) { ResponderRSocket socket = (ResponderRSocket) rSocket; return socket.requestChannel(payload, flux) .log(GatewayRSocket.class.getName()+".request-channel", Level.FINE); } return rSocket.requestChannel(flux); }) .doOnNext(s -> count(exchange, "payload", responderTags)) .doOnError(t -> count(exchange, "error", responderTags)) .doFinally(s -> count(exchange, responderTags)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Flux<Payload> requestStream(Payload payload) { GatewayExchange exchange = GatewayExchange.fromPayload(REQUEST_STREAM, payload); Tags tags = getTags(exchange); return findRSocketOrCreatePending(exchange) .flatMapMany(rSocket -> rSocket.requestStream(payload)) // S N E F //TODO: move tagnames to enum .doOnNext(s -> count("forward.request.stream.payload", tags)) .doOnError(t -> count("forward.request.stream.error", tags)) .doFinally(s -> count("forward.request.stream", tags)); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Flux<Payload> requestStream(Payload payload) { GatewayExchange exchange = createExchange(REQUEST_STREAM, payload); return findRSocketOrCreatePending(exchange) .flatMapMany(rSocket -> rSocket.requestStream(payload)) // S N E F .doOnNext(s -> count(exchange, "payload")) .doOnError(t -> count(exchange, "error")) .doFinally(s -> count(exchange, Tags.empty())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Mono<Void> fireAndForget(Payload payload) { GatewayExchange exchange = GatewayExchange.fromPayload(FIRE_AND_FORGET, payload); Tags tags = getTags(exchange); return findRSocketOrCreatePending(exchange) .flatMap(rSocket -> rSocket.fireAndForget(payload)) .doOnError(t -> count("forward.request.fnf.error", tags)) .doFinally(s -> count("forward.request.fnf", tags)); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Mono<Void> fireAndForget(Payload payload) { GatewayExchange exchange = createExchange(FIRE_AND_FORGET, payload); return findRSocketOrCreatePending(exchange) .flatMap(rSocket -> rSocket.fireAndForget(payload)) .doOnError(t -> count(exchange, "error")) .doFinally(s -> count(exchange, "")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Mono<Payload> requestResponse(Payload payload) { AtomicReference<Timer.Sample> timer = new AtomicReference<>(); GatewayExchange exchange = GatewayExchange.fromPayload(REQUEST_RESPONSE, payload); Tags tags = getTags(exchange); return findRSocketOrCreatePending(exchange) .flatMap(rSocket -> rSocket.requestResponse(payload)) .doOnSubscribe(s -> timer.set(Timer.start(meterRegistry))) .doOnError(t -> count("forward.request.response.error", tags)) .doFinally(s -> timer.get().stop(meterRegistry.timer("forward.request.response", tags))); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Mono<Payload> requestResponse(Payload payload) { AtomicReference<Timer.Sample> timer = new AtomicReference<>(); GatewayExchange exchange = createExchange(REQUEST_RESPONSE, payload); return findRSocketOrCreatePending(exchange) .flatMap(rSocket -> rSocket.requestResponse(payload)) .doOnSubscribe(s -> timer.set(Timer.start(meterRegistry))) .doOnError(t -> count(exchange, "error")) .doFinally(s -> timer.get().stop(meterRegistry.timer(getMetricName(exchange), exchange.getTags()))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Mono<Void> fireAndForget(Payload payload) { List<String> metadata = getRoutingMetadata(payload); RSocket service = findRSocket(metadata); if (service != null) { return service.fireAndForget(payload); } //TODO: handle concurrency issues MonoProcessor<RSocket> processor = MonoProcessor.create(); this.registry.pendingRequest(metadata, processor); return processor .log("pending-request") .flatMap(rSocket -> rSocket.fireAndForget(payload)); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Mono<Void> fireAndForget(Payload payload) { RSocket service = findRSocket(payload); return service.fireAndForget(payload); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void displayJSON (HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/plain"); try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(response.getOutputStream())); JSONArray out = new JSONArray(); for (JSONObject district : districts) { out.put(district); } writer.write(out.toString()); } catch (IOException e) { e.printStackTrace(); } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code private void displayJSON (HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/plain"); try { ServletOutputStream out = response.getOutputStream(); out.println("["); for (JSONObject district : districts) { out.println(district.toString()); } out.println("]"); out.flush(); } catch (IOException e) { e.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws IOException { IngestReader ir = new IngestReader(); if(args.length == 2) { String command = args[0]; String p1 = args[1]; if(command.equals("-gx")) { ir.generateXml(p1); } else if(command.equals("-b")) { ir.indexSenateObject((Bill)ir.loadObject(p1, Bill.class)); } else if(command.equals("-c")) { ir.indexSenateObject((Calendar)ir.loadObject(p1, Calendar.class)); } else if(command.equals("-a")) { ir.indexSenateObject((Agenda)ir.loadObject(p1, Agenda.class)); } else if(command.equals("-t")) { ir.indexSenateObject((Transcript)ir.loadObject(p1, Transcript.class)); } else if(command.equals("-it")) { ir.handleTranscript(p1); } else { System.err.println("bad command"); } } else if(args.length == 3){ String command = args[0]; String p1 = args[1]; String p2 = args[2]; if(command.equals("-i")) { WRITE_DIRECTORY = p1; ir.handlePath(p2); } else if(command.equals("-fc")) { ir.fixCalendarBills(p1, p2); } else if(command.equals("-fa")) { ir.fixAgendaBills(p1, p2); } else { System.err.println("bad command"); } } else { System.err.println("appropriate usage is:\n" + "\t-i <json directory> <sobi directory> (to create index)\n" + "\t-gx <sobi directory> (to generate agenda and calendar xml from sobi)\n" + "\t-fc <year> <calendar directory> (to fix calendar bills)\n" + "\t-fa <year> <agenda directory> (to fix agenda bills)\n" + "\t-b <bill json path> (to reindex single bill)\n" + "\t-c <calendar json path> (to reindex single calendar)\n" + "\t-a <agenda json path> (to reindex single agenda)\n" + "\t-t <transcript json path> (to reindex single transcript)" + "\t-it <transcript sobi path> (to reindex single agenda)\n"); } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) throws IOException { IngestReader ir = new IngestReader(); if(args.length == 2) { String command = args[0]; String p1 = args[1]; if(command.equals("-gx")) { ir.generateXml(p1); } else if(command.equals("-b")) { ir.writeBills(new ArrayList<Bill>(Arrays.asList((Bill)ir.loadObject(p1, Bill.class))), false); } else if(command.equals("-c")) { ir.indexSenateObject((Calendar)ir.loadObject(p1, Calendar.class)); } else if(command.equals("-a")) { ir.indexSenateObject((Agenda)ir.loadObject(p1, Agenda.class)); } else if(command.equals("-t")) { ir.indexSenateObject((Transcript)ir.loadObject(p1, Transcript.class)); } else if(command.equals("-it")) { ir.handleTranscript(p1); } else { System.err.println("bad command"); } } else if(args.length == 3){ String command = args[0]; String p1 = args[1]; String p2 = args[2]; if(command.equals("-i")) { WRITE_DIRECTORY = p1; ir.handlePath(p2); } else if(command.equals("-fc")) { ir.fixCalendarBills(p1, p2); } else if(command.equals("-fa")) { ir.fixAgendaBills(p1, p2); } else { System.err.println("bad command"); } } else { System.err.println("appropriate usage is:\n" + "\t-i <json directory> <sobi directory> (to create index)\n" + "\t-gx <sobi directory> (to generate agenda and calendar xml from sobi)\n" + "\t-fc <year> <calendar directory> (to fix calendar bills)\n" + "\t-fa <year> <agenda directory> (to fix agenda bills)\n" + "\t-b <bill json path> (to reindex single bill)\n" + "\t-c <calendar json path> (to reindex single calendar)\n" + "\t-a <agenda json path> (to reindex single agenda)\n" + "\t-t <transcript json path> (to reindex single transcript)" + "\t-it <transcript sobi path> (to reindex single agenda)\n"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { SearchEngine2 engine = new SearchEngine2(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String line = null; System.out.print("openlegLuceneConsole> "); while (!(line = reader.readLine()).equals("quit")) { if (line.startsWith("index ")) { String cmd = line.substring(line.indexOf(" ")+1); StringTokenizer st = new StringTokenizer(cmd); String iType = st.nextToken(); int start = 1; int max = 1000000; int pageSize = 10; if (st.hasMoreTokens()) start = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) max = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) pageSize = Integer.parseInt(st.nextToken()); engine.indexSenateData(iType, start, max, pageSize, new LuceneSerializer[]{new XmlSerializer(), new JsonSerializer()}); } else if (line.startsWith("optimize")) engine.optimize(); else if (line.startsWith("delete")) { StringTokenizer cmd = new StringTokenizer(line.substring(line.indexOf(" ")+1)," "); String type = cmd.nextToken(); String id = cmd.nextToken(); engine.deleteSenateObjectById(type, id); } else if (line.startsWith("create")) engine.createIndex(); else engine.search(line, "xml", 1, 10, null, false); System.out.print("openleg search > "); } System.out.println("Exiting Search Engine"); } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws Exception { SearchEngine2 engine = SearchEngine2.getInstance(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String line = null; System.out.print("openlegLuceneConsole> "); while (!(line = reader.readLine()).equals("quit")) { if (line.startsWith("index ")) { String cmd = line.substring(line.indexOf(" ")+1); StringTokenizer st = new StringTokenizer(cmd); String iType = st.nextToken(); int start = 1; int max = 1000000; int pageSize = 10; if (st.hasMoreTokens()) start = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) max = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) pageSize = Integer.parseInt(st.nextToken()); engine.indexSenateData(iType, start, max, pageSize, new LuceneSerializer[]{new XmlSerializer(), new JsonSerializer()}); } else if (line.startsWith("optimize")) engine.optimize(); else if (line.startsWith("delete")) { StringTokenizer cmd = new StringTokenizer(line.substring(line.indexOf(" ")+1)," "); String type = cmd.nextToken(); String id = cmd.nextToken(); engine.deleteSenateObjectById(type, id); } else if (line.startsWith("create")) engine.createIndex(); else engine.search(line, "xml", 1, 10, null, false); System.out.print("openleg search > "); } System.out.println("Exiting Search Engine"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void init() throws ServletException { super.init(); try { districts = new ArrayList<JSONObject>(); for (int i = 1; i <= 62; i++) { String jsonPath = DISTRICT_JSON_FOLDER_PATH + "sd" + i + ".json"; logger.info("loading: " + jsonPath); InputStream is = getServletContext().getResourceAsStream(jsonPath); // InputStream is = ClassLoader //.getSystemResourceAsStream(DISTRICT_JSON_FOLDER_PATH + "sd" + i + ".json"); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer jsonb = new StringBuffer(); while ((line = reader.readLine())!=null) { jsonb.append(line); } JSONObject jsono = new JSONObject(jsonb.toString()); JSONObject jSenator = jsono.getJSONObject("senator"); String senatorName = jSenator.getString("name"); senatorName = senatorName.replace("�","e"); jSenator.put("name", senatorName); String senatorKey = jSenator.getString("url"); senatorKey = senatorKey.substring(senatorKey.lastIndexOf('/')+1); senatorKey = senatorKey.replace("-jr", ""); senatorKey = senatorKey.replace("-sr", ""); String[] senatorKeyParts =senatorKey.split("-"); if (senatorName.contains("-")) { senatorKey = senatorKeyParts[senatorKeyParts.length-2] + '-' + senatorKeyParts[senatorKeyParts.length-1]; } else { senatorKey = senatorKeyParts[senatorKeyParts.length-1]; } jSenator.put("key", senatorKey); districts.add(jsono); logger.info(jsono.get("district")); logger.info(jsono.getJSONObject("senator").get("name")); } Collections.sort(districts, new byLastName()); } catch (Exception e) { logger.error("error loading json district files",e); } } #location 69 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void init() throws ServletException { super.init(); String rootPath = this.getServletContext().getRealPath("/"); String encoding = "latin1";//"UTF-8"; try { districts = new ArrayList<JSONObject>(); for (int i = 1; i <= 62; i++) { String jsonPath = DISTRICT_JSON_FOLDER_PATH + "sd" + i + ".json"; URL jsonUrl = getServletContext().getResource(jsonPath); //jsonPath = rootPath + '/' + jsonPath; StringBuilder jsonb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(jsonUrl.openStream(),encoding)); //BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(jsonPath), encoding)); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1){ jsonb.append(buf, 0, numRead); buf = new char[1024]; } reader.close(); JSONObject jsono = new JSONObject(jsonb.toString()); JSONObject jSenator = jsono.getJSONObject("senator"); String senatorName = jSenator.getString("name"); jSenator.put("name", senatorName); String senatorKey = jSenator.getString("url"); senatorKey = senatorKey.substring(senatorKey.lastIndexOf('/')+1); senatorKey = senatorKey.replace("-jr", ""); senatorKey = senatorKey.replace("-sr", ""); String[] senatorKeyParts =senatorKey.split("-"); if (senatorName.contains("-")) { senatorKey = senatorKeyParts[senatorKeyParts.length-2] + '-' + senatorKeyParts[senatorKeyParts.length-1]; } else { senatorKey = senatorKeyParts[senatorKeyParts.length-1]; } jSenator.put("key", senatorKey); districts.add(jsono); logger.info(jsono.get("district")); logger.info(jsono.getJSONObject("senator").get("name")); } Collections.sort(districts, new byLastName()); } catch (Exception e) { logger.error("error loading json district files",e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws IOException { IngestReader ir = new IngestReader(); try { if(args.length < 2) { throw new IngestException(); } String command = args[0]; if(args.length == 2) { if(command.equals("-gx")) { XmlHelper.generateXml(args[1]); } else if(command.equals("-b")) { //In the case of bills, we also need to make sure we reindex all ammended versions Bill bill = (Bill)ir.loadObject(args[1], Bill.class); if(ir.reindexAmendedVersions((Bill)bill)) bill.setLuceneActive(false); ir.indexSenateObject(bill); } else if(command.equals("-c")) { ir.indexSenateObject(ir.loadObject(args[1], Calendar.class)); } else if(command.equals("-a")) { ir.indexSenateObject(ir.loadObject(args[1], Agenda.class)); } else if(command.equals("-t")) { ir.indexSenateObject(ir.loadObject(args[1], Transcript.class)); } else { throw new IngestException(); } } else if(args.length == 3){ if(command.equals("-i")) { WRITE_DIRECTORY = args[1]; ir.processPath(args[2]); } else if(command.equals("-it")) { //Processes, writes, and indexes a directory of transcripts WRITE_DIRECTORY = args[1]; ir.handleTranscript(new File(args[2])); } else { throw new IngestException(); } } else if(args.length == 5) { if(command.equals("-pull")) { ir.pullSobis(args[1], args[2], args[3], args[4]); } else { throw new IngestException(); } } } catch(IngestException e) { System.err.println("appropriate usage is:\n" + "\t-i <json directory> <sobi directory> (to create index)\n" + "\t-gx <sobi directory> (to generate agenda and calendar xml from sobi)\n" + "\t-b <bill json path> (to reindex single bill)\n" + "\t-c <calendar json path> (to reindex single calendar)\n" + "\t-a <agenda json path> (to reindex single agenda)\n" + "\t-t <transcript json path> (to reindex single transcript)" + "\t-it <transcript sobi path> (to reindex dir of transcripts)\n" + "\t-pull <sobi directory> <output directory> <id> <year> (get an objects referencing sobis)"); } } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) throws IOException { IngestReader ir = new IngestReader(); try { if(args.length < 2) { throw new IngestException(); } String command = args[0]; if(args.length == 2) { if(command.equals("-gx")) { XmlHelper.generateXml(args[1]); } else if(command.equals("-b")) { //In the case of bills, we also need to make sure we reindex all ammended versions Bill bill = (Bill)ir.loadObject(args[1], Bill.class); if(ir.reindexAmendedVersions((Bill)bill)) bill.setLuceneActive(false); ir.indexSenateObject(bill); } else if(command.equals("-c")) { ir.indexSenateObject(ir.loadObject(args[1], Calendar.class)); } else if(command.equals("-a")) { ir.indexSenateObject(ir.loadObject(args[1], Agenda.class)); } else if(command.equals("-t")) { ir.indexSenateObject(ir.loadObject(args[1], Transcript.class)); } else { throw new IngestException(); } } else if(args.length == 3){ if(command.equals("-i")) { WRITE_DIRECTORY = args[1]; ir.processPath(args[2]); } else if(command.equals("-it")) { //Processes, writes, and indexes a directory of transcripts WRITE_DIRECTORY = args[1]; ir.handleTranscript(new File(args[2])); } else if(command.equals("-bulk")) { ir.bulkIndexJsonDirectory(ir.getIngestType(args[1]).clazz(),args[2]); } else { throw new IngestException(); } } else if(args.length == 5) { if(command.equals("-pull")) { ir.pullSobis(args[1], args[2], args[3], args[4]); } else { throw new IngestException(); } } } catch(IngestException e) { System.err.println("appropriate usage is:\n" + "\t-i <json directory> <sobi directory> (to create index)\n" + "\t-gx <sobi directory> (to generate agenda and calendar xml from sobi)\n" + "\t-b <bill json path> (to reindex single bill)\n" + "\t-c <calendar json path> (to reindex single calendar)\n" + "\t-a <agenda json path> (to reindex single agenda)\n" + "\t-t <transcript json path> (to reindex single transcript)" + "\t-it <transcript sobi path> (to reindex dir of transcripts)\n" + "\t-pull <sobi directory> <output directory> <id> <year> (get an objects referencing sobis)" + "\t-bulk <object type> <json directory> (bulk index directory ofjson objects)"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void handleAPIv1 (String format, String type, String key, int pageIdx, int pageSize, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String viewPath = ""; String searchString = ""; String originalType = type; String sFormat = "json"; String sortField = "when"; boolean sortOrder = true; if(type != null) { if(type.contains("bill")) { sortField = "sortindex"; sortOrder = false; } else if(type.contains("meeting")) { sortField = "sortindex"; } } SenateResponse sr = null; if (type.equalsIgnoreCase("sponsor")) { String filter = req.getParameter("filter"); key = "sponsor:\"" + key + (filter != null ? " AND " + filter : ""); type = "bills"; } else if (type.equalsIgnoreCase("committee")) { key = "committee:\"" + key + "\" AND oid:s*-" + SessionYear.getSessionYear(); type = "bills"; } key = key.trim(); if (pageSize > MAX_PAGE_SIZE) throw new ServletException ("The maximum page size is " + MAX_PAGE_SIZE); //now calculate start, end idx based on pageIdx and pageSize int start = (pageIdx - 1) * pageSize; int end = start + pageSize; logger.info("request: key=" + key + ";type=" + type + ";format=" + format + ";paging=" + start + "/" + end); try { /* * construct query with "otype:<type>" if type present */ if (type != null) { /* * for searches * * applicable to: bills, calendars, meetings, transcripts, actions, votes */ if (type.endsWith("s")) { type = type.substring(0,type.length()-1); searchString = "otype:" + type; if (key != null && key.length() > 0) searchString += " AND " + key; } /* * for individual documents * * applicable to: bill, calendar, meeting, transcript */ else { searchString ="otype:" + type; if (key != null && key.length() > 0) { if (type.equals("bill") && key.indexOf("-") == -1) key += "-" + DEFAULT_SESSION_YEAR; key = key.replace(" ","+"); searchString += " AND oid:" + key; } } } else { searchString = key; } req.setAttribute("sortField", sortField); req.setAttribute("sortOrder", Boolean.toString(sortOrder)); req.setAttribute("type", type); req.setAttribute("term", searchString); req.setAttribute("format", format); req.setAttribute("key", key); req.setAttribute(PAGE_IDX,pageIdx+""); req.setAttribute(PAGE_SIZE,pageSize+""); /* * applicable to: bills * * only return bills with "year:<currentSessionYear>" */ if(originalType.equals("bills")) { sr = searchEngine.search(ApiHelper.dateReplace(searchString) + " AND year:" + SessionYear.getSessionYear() + " AND active:true", sFormat,start,pageSize,sortField,sortOrder); } /* * applicable to: calendars, meetings, transcripts * * only want current session documents as defined by the time * frame between DATE_START and DATE_END */ else if(originalType.endsWith("s")) { sr = searchEngine.search(ApiHelper.dateReplace(searchString) + " AND when:[" + DATE_START + " TO " + DATE_END + "]" + " AND active:true", sFormat,start,pageSize,sortField,sortOrder); } /* * applicable to: individual documents * * attempting to access a document by id doesn't * doesn't require any special formatting */ else { sr = searchEngine.search(ApiHelper.dateReplace(searchString),sFormat,start,pageSize,sortField,sortOrder); } logger.info("got search results: " + sr.getResults().size()); if (sr.getResults().size()==0) { resp.sendError(404); return; } else if (sr.getResults().size()==1 && format.matches("(html(\\-print)?|mobile|lrs\\-print)")) { Result result = sr.getResults().get(0); /* if not an exact match on the oid it's likely * the correct id, just the wrong case */ if (!result.getOid().equals(key)) { if(format.equals("html")) resp.sendRedirect("/legislation/" + result.getOtype() + "/" + result.getOid()); else resp.sendRedirect("/legislation/api/1.0/" + format + "/" + result.getOtype() + "/" + result.getOid()); return; } String jsonData = result.getData(); req.setAttribute("active", result.getActive()); jsonData = jsonData.substring(jsonData.indexOf(":")+1); jsonData = jsonData.substring(0,jsonData.lastIndexOf("}")); /* Jackson ObjectMaper will deserialize our json in to an object, * we need to know what sort of an object that is */ String className = "gov.nysenate.openleg.model.bill." + type.substring(0,1).toUpperCase() + type.substring(1); /* * for bills we populate other relevant data, such as * votes, calendars, meetings, sameas bills, older versions, etc. */ if (type.equals("bill")) { String billQueryId = key; String sessionYear = DEFAULT_SESSION_YEAR; /* default behavior to maintain previous permalinks * is if key=S1234 to transform to S1234-2009 * in line with our new bill oid format <billno>-<sessYear> */ String[] billParts = billQueryId.split("-"); billQueryId = billParts[0]; if (billParts.length > 1) sessionYear = billParts[1]; /* turns S1234A in to S1234 */ String billWildcard = billQueryId; if (!Character.isDigit(billWildcard.charAt(billWildcard.length()-1))) billWildcard = billWildcard.substring(0,billWildcard.length()-1); //get BillEvents for this //otype:action AND billno:((S1234-2011 OR [S1234A-2011 TO S1234Z-2011) AND S1234*-2011) String rType = "action"; String rQuery = null; rQuery = billWildcard + "-" + sessionYear; logger.info(rQuery); rQuery = "billno:((" + rQuery + " OR [" + billWildcard + "A-" + sessionYear + " TO " + billWildcard + "Z-" + sessionYear + "]) AND " + billWildcard + "*-" + sessionYear + ")"; ArrayList<SearchResult> relatedActions = ApiHelper.getRelatedSenateObjects(rType,rQuery); Hashtable<String,SearchResult> uniqResults = new Hashtable<String,SearchResult>(); for (SearchResult rResult: relatedActions) { BillEvent rAction = (BillEvent)rResult.getObject(); uniqResults.put(rAction.getEventDate().toGMTString()+'-'+rResult.getTitle().toUpperCase(), rResult); } ArrayList<SearchResult> list = Collections.list(uniqResults.elements()); Collections.sort(list); req.setAttribute("related-" + rType, list); //get older bills (e.g. for S1234A get S1234) //otype:meeting AND oid:((S1234-2011 OR [S1234A-2011 TO S1234Z-2011) AND S1234*-2011) rType = "bill"; rQuery = billWildcard + "-" + sessionYear; logger.info(rQuery); rQuery = "oid:((" + rQuery + " OR [" + billWildcard + "A-" + sessionYear + " TO " + billWildcard + "Z-" + sessionYear + "]) AND " + billWildcard + "*-" + sessionYear + ")"; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects (rType,rQuery)); //get Meetings //otype:meeting AND bills:"S67005-2011" rType = "meeting"; rQuery = "bills:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); //get calendars //otype:calendar AND bills:"S337A-2011" rType = "calendar"; rQuery = "bills:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); //get votes //otype:vote AND billno:"A11597-2011" rType = "vote"; rQuery = "billno:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); } else if (type.equals("calendar")) { className = "gov.nysenate.openleg.model.calendar.Calendar"; } else if (type.equals("meeting")) { className = "gov.nysenate.openleg.model.committee.Meeting"; } else if(type.equals("transcript")) { className = "gov.nysenate.openleg.model.transcript.Transcript"; } Object resultObj = null; try { resultObj = ApiHelper.getMapper().readValue(jsonData, Class.forName(className)); } catch (Exception e) { logger.warn("error binding className", e); } req.setAttribute(type, resultObj); viewPath = "/views/" + type + "-" + format + ".jsp"; } else { /* all non html/print bill views go here */ if (type.equals("bill") && (!format.equals("html"))) { viewPath = "/views/bills-" + format + ".jsp"; ArrayList<SearchResult> searchResults = ApiHelper.buildSearchResultList(sr); ArrayList<Bill> bills = new ArrayList<Bill>(); for (SearchResult result : searchResults) { bills.add((Bill)result.getObject()); } req.setAttribute("bills", bills); } /* all calendar, meeting, transcript multi views go here */ else { viewPath = "/views/" + "search" + "-" + format + ".jsp"; SearchResultSet srs = new SearchResultSet(); srs.setTotalHitCount((Integer)sr.getMetadata().get("totalresults")); srs.setResults(ApiHelper.buildSearchResultList(sr)); req.setAttribute("results", srs); } } } catch (Exception e) { logger.warn("search controller didn't work for: " + req.getRequestURI(),e); e.printStackTrace(); } try { logger.info("routing to search controller:" + viewPath); getServletContext().getRequestDispatcher(viewPath).forward(req, resp); } catch (Exception e) { logger.warn("search controller didn't work for: " + req.getRequestURI(),e); } } #location 293 #vulnerability type NULL_DEREFERENCE
#fixed code public void handleAPIv1 (String format, String type, String key, int pageIdx, int pageSize, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String urlPath = "/legislation/" + type + "/" + ((key != null && !key.matches("\\s*")) ? key + "/" :""); if (type.equalsIgnoreCase("sponsor")) { String filter = req.getParameter("filter"); key = "sponsor:\"" + key + "\""; if(filter != null) { req.setAttribute("filter", filter); key += (filter != null ? " AND " + filter : ""); } type = "bills"; } else if (type.equalsIgnoreCase("committee")) { key = "committee:\"" + key + "\""; type = "bills"; } String originalType = type; String viewPath = ""; String searchString = ""; String sFormat = "json"; String sortField = "when"; boolean sortOrder = true; if(type != null) { if(type.contains("bill")) { sortField = "sortindex"; sortOrder = false; } else if(type.contains("meeting")) { sortField = "sortindex"; } } SenateResponse sr = null; key = key.trim(); if (pageSize > MAX_PAGE_SIZE) throw new ServletException ("The maximum page size is " + MAX_PAGE_SIZE); //now calculate start, end idx based on pageIdx and pageSize int start = (pageIdx - 1) * pageSize; int end = start + pageSize; logger.info("request: key=" + key + ";type=" + type + ";format=" + format + ";paging=" + start + "/" + end); try { /* * construct query with "otype:<type>" if type present */ if (type != null) { /* * for searches * * applicable to: bills, calendars, meetings, transcripts, actions, votes */ if (type.endsWith("s")) { type = type.substring(0,type.length()-1); searchString = "otype:" + type; if (key != null && key.length() > 0) searchString += " AND " + key; } /* * for individual documents * * applicable to: bill, calendar, meeting, transcript */ else { searchString ="otype:" + type; if (key != null && key.length() > 0) { if (type.equals("bill") && key.indexOf("-") == -1) key += "-" + DEFAULT_SESSION_YEAR; key = key.replace(" ","+"); searchString += " AND oid:" + key; } } } else { searchString = key; } /* * applicable to: bills * * only return bills with "year:<currentSessionYear>" */ if(originalType.equals("bills")) { req.setAttribute("urlPath", urlPath); searchString = ApiHelper.dateReplace(searchString) + " AND year:" + SessionYear.getSessionYear() + " AND active:true"; } /* * applicable to: calendars, meetings, transcripts * * only want current session documents as defined by the time * frame between DATE_START and DATE_END */ else if(originalType.endsWith("s")) { req.setAttribute("urlPath", urlPath); searchString = ApiHelper.dateReplace(searchString) + " AND when:[" + DATE_START + " TO " + DATE_END + "]" + " AND active:true"; } /* * applicable to: individual documents * * attempting to access a document by id doesn't * doesn't require any special formatting */ else { searchString = ApiHelper.dateReplace(searchString); } req.setAttribute("sortField", sortField); req.setAttribute("sortOrder", Boolean.toString(sortOrder)); req.setAttribute("type", type); req.setAttribute("term", searchString); req.setAttribute("format", format); req.setAttribute("key", key); req.setAttribute(PAGE_IDX,pageIdx+""); req.setAttribute(PAGE_SIZE,pageSize+""); sr = searchEngine.search(searchString,sFormat,start,pageSize,sortField,sortOrder); logger.info("got search results: " + sr.getResults().size()); if (sr.getResults().size()==0) { resp.sendError(404); return; } else if (sr.getResults().size()==1 && format.matches("(html(\\-print)?|mobile|lrs\\-print)")) { Result result = sr.getResults().get(0); /* if not an exact match on the oid it's likely * the correct id, just the wrong case */ if (!result.getOid().equals(key)) { if(format.equals("html")) resp.sendRedirect("/legislation/" + result.getOtype() + "/" + result.getOid()); else resp.sendRedirect("/legislation/api/1.0/" + format + "/" + result.getOtype() + "/" + result.getOid()); return; } String jsonData = result.getData(); req.setAttribute("active", result.getActive()); jsonData = jsonData.substring(jsonData.indexOf(":")+1); jsonData = jsonData.substring(0,jsonData.lastIndexOf("}")); /* Jackson ObjectMaper will deserialize our json in to an object, * we need to know what sort of an object that is */ String className = "gov.nysenate.openleg.model.bill." + type.substring(0,1).toUpperCase() + type.substring(1); /* * for bills we populate other relevant data, such as * votes, calendars, meetings, sameas bills, older versions, etc. */ if (type.equals("bill")) { String billQueryId = key; String sessionYear = DEFAULT_SESSION_YEAR; /* default behavior to maintain previous permalinks * is if key=S1234 to transform to S1234-2009 * in line with our new bill oid format <billno>-<sessYear> */ String[] billParts = billQueryId.split("-"); billQueryId = billParts[0]; if (billParts.length > 1) sessionYear = billParts[1]; /* turns S1234A in to S1234 */ String billWildcard = billQueryId; if (!Character.isDigit(billWildcard.charAt(billWildcard.length()-1))) billWildcard = billWildcard.substring(0,billWildcard.length()-1); //get BillEvents for this //otype:action AND billno:((S1234-2011 OR [S1234A-2011 TO S1234Z-2011) AND S1234*-2011) String rType = "action"; String rQuery = null; rQuery = billWildcard + "-" + sessionYear; logger.info(rQuery); rQuery = "billno:((" + rQuery + " OR [" + billWildcard + "A-" + sessionYear + " TO " + billWildcard + "Z-" + sessionYear + "]) AND " + billWildcard + "*-" + sessionYear + ")"; ArrayList<SearchResult> relatedActions = ApiHelper.getRelatedSenateObjects(rType,rQuery); Hashtable<String,SearchResult> uniqResults = new Hashtable<String,SearchResult>(); for (SearchResult rResult: relatedActions) { BillEvent rAction = (BillEvent)rResult.getObject(); uniqResults.put(rAction.getEventDate().toGMTString()+'-'+rResult.getTitle().toUpperCase(), rResult); } ArrayList<SearchResult> list = Collections.list(uniqResults.elements()); Collections.sort(list); req.setAttribute("related-" + rType, list); //get older bills (e.g. for S1234A get S1234) //otype:meeting AND oid:((S1234-2011 OR [S1234A-2011 TO S1234Z-2011) AND S1234*-2011) rType = "bill"; rQuery = billWildcard + "-" + sessionYear; logger.info(rQuery); rQuery = "oid:((" + rQuery + " OR [" + billWildcard + "A-" + sessionYear + " TO " + billWildcard + "Z-" + sessionYear + "]) AND " + billWildcard + "*-" + sessionYear + ")"; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects (rType,rQuery)); //get Meetings //otype:meeting AND bills:"S67005-2011" rType = "meeting"; rQuery = "bills:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); //get calendars //otype:calendar AND bills:"S337A-2011" rType = "calendar"; rQuery = "bills:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); //get votes //otype:vote AND billno:"A11597-2011" rType = "vote"; rQuery = "billno:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); } else if (type.equals("calendar")) { className = "gov.nysenate.openleg.model.calendar.Calendar"; } else if (type.equals("meeting")) { className = "gov.nysenate.openleg.model.committee.Meeting"; } else if(type.equals("transcript")) { className = "gov.nysenate.openleg.model.transcript.Transcript"; } Object resultObj = null; try { resultObj = ApiHelper.getMapper().readValue(jsonData, Class.forName(className)); } catch (Exception e) { logger.warn("error binding className", e); } req.setAttribute(type, resultObj); viewPath = "/views/" + type + "-" + format + ".jsp"; } else { /* all non html/print bill views go here */ if (type.equals("bill") && (!format.equals("html"))) { viewPath = "/views/bills-" + format + ".jsp"; ArrayList<SearchResult> searchResults = ApiHelper.buildSearchResultList(sr); ArrayList<Bill> bills = new ArrayList<Bill>(); for (SearchResult result : searchResults) { bills.add((Bill)result.getObject()); } req.setAttribute("bills", bills); } /* all calendar, meeting, transcript multi views go here */ else { viewPath = "/views/" + "search" + "-" + format + ".jsp"; SearchResultSet srs = new SearchResultSet(); srs.setTotalHitCount((Integer)sr.getMetadata().get("totalresults")); srs.setResults(ApiHelper.buildSearchResultList(sr)); req.setAttribute("results", srs); } } } catch (Exception e) { logger.warn("search controller didn't work for: " + req.getRequestURI(),e); e.printStackTrace(); } try { logger.info("routing to search controller:" + viewPath); getServletContext().getRequestDispatcher(viewPath).forward(req, resp); } catch (Exception e) { logger.warn("search controller didn't work for: " + req.getRequestURI(),e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("reset")!=null) searchEngine.closeSearcher(); String search = request.getParameter("search"); String term = request.getParameter("term"); String type = request.getParameter("type"); String full = request.getParameter("full"); String memo = request.getParameter("memo"); String status = request.getParameter("status"); String sponsor = request.getParameter("sponsor"); String cosponsors = request.getParameter("cosponsors"); String sameas = request.getParameter("sameas"); String committee = request.getParameter("committee"); String location = request.getParameter("location"); String session = request.getParameter("session"); if(search != null) { request.setAttribute("search", search); term = search; } String tempTerm = null; if((tempTerm = BillCleaner.getDesiredBillNumber(term)) != null) { term = "oid:" + tempTerm; type = "bill"; } String sortField = request.getParameter("sort"); boolean sortOrder = false; if (request.getParameter("sortOrder")!=null) sortOrder = Boolean.parseBoolean(request.getParameter("sortOrder")); Date startDate = null; Date endDate = null; try { if (request.getParameter("startdate")!=null && (!request.getParameter("startdate").equals("mm/dd/yyyy"))) startDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("startdate")); } catch (java.text.ParseException e1) { logger.warn(e1); } try { if (request.getParameter("enddate")!=null && (!request.getParameter("enddate").equals("mm/dd/yyyy"))) { endDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("enddate")); Calendar cal = Calendar.getInstance(); cal.setTime(endDate); cal.set(Calendar.HOUR, 11); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); endDate = cal.getTime(); } } catch (java.text.ParseException e1) { logger.warn(e1); } String format = "html"; if (request.getParameter("format")!=null) format = request.getParameter("format"); int pageIdx = 1; int pageSize = 20; if (request.getParameter("pageIdx") != null) pageIdx = Integer.parseInt(request.getParameter("pageIdx")); if (request.getParameter("pageSize") != null) pageSize = Integer.parseInt(request.getParameter("pageSize")); //now calculate start, end idx based on pageIdx and pageSize int start = (pageIdx - 1) * pageSize; SearchResultSet srs; StringBuilder searchText = new StringBuilder(); if (term != null) searchText.append(term); try { if (type != null && type.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("otype:"); searchText.append(type.equals("res") ? "bill AND oid:r*":type); } if(session != null && session.length() > 0) { if(searchText.length() > 0) searchText.append(" AND "); searchText.append("year:" + session); } if (full != null && full.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("(full:\""); searchText.append(full); searchText.append("\""); searchText.append(" OR "); searchText.append("osearch:\""); searchText.append(full); searchText.append("\")"); } if (memo != null && memo.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("memo:\""); searchText.append(memo); searchText.append("\""); } if (status != null && status.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("status:\""); searchText.append(status); searchText.append("\""); } if (sponsor != null && sponsor.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sponsor:\""); searchText.append(sponsor); searchText.append("\""); } if (cosponsors != null && cosponsors.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("cosponsors:\""); searchText.append(cosponsors); searchText.append("\""); } if (sameas != null && sameas.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sameas:"); searchText.append(sameas); } if (committee != null && committee.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("committee:\""); searchText.append(committee); searchText.append("\""); } if (location != null && location.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("location:\""); searchText.append(location); searchText.append("\""); } if (startDate != null && endDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); searchText.append(endDate.getTime()); searchText.append("]"); } else if (startDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); cal.set(Calendar.HOUR, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); startDate = cal.getTime(); searchText.append(startDate.getTime()); searchText.append("]"); } term = searchText.toString(); term = BillCleaner.billFormat(term); request.setAttribute("term", term); request.setAttribute("type", type); //default behavior is to return only active bills, so if a user searches //s1234 and s1234a is available then s1234a should be returned if(sortField == null && (((search != null && search.contains("otype:bill")) || (term != null && term.contains("otype:bill"))) || (type != null && type.equals("bill")))) { sortField = "sortindex"; sortOrder = false; type = "bill"; } if (sortField!=null && !sortField.equals("")) { request.setAttribute("sortField", sortField); request.setAttribute("sortOrder",Boolean.toString(sortOrder)); } else { sortField = "when"; sortOrder = true; request.setAttribute("sortField", sortField); request.setAttribute("sortOrder", Boolean.toString(sortOrder)); } request.setAttribute(OpenLegConstants.PAGE_IDX,pageIdx+""); request.setAttribute(OpenLegConstants.PAGE_SIZE,pageSize+""); srs = null; if (term.length() == 0) { response.sendError(404); return; } String searchFormat = "json"; SenateResponse sr = null; if(term != null && !term.contains("year:") && !term.contains("when:") && !term.contains("oid:")) { if(type != null && type.equals("bill")) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } else { sr = searchEngine.search(term + " AND when:[" + DATE_START + " TO " + DATE_END + "]",searchFormat,start,pageSize,sortField,sortOrder); if(sr.getResults().isEmpty()) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } } } else { sr = searchEngine.search(term,searchFormat,start,pageSize,sortField,sortOrder); } srs = new SearchResultSet(); srs.setTotalHitCount((Integer)sr.getMetadata().get("totalresults")); srs.setResults(ApiHelper.buildSearchResultList(sr)); if (srs != null) { if (srs.getResults().size() == 0) { response.sendError(404); } else { request.setAttribute("results", srs); String viewPath = "/views/search-" + format + DOT_JSP; getServletContext().getRequestDispatcher(viewPath).forward(request, response); } } else { logger.error("Search Error: " + request.getRequestURI()); response.sendError(500); } } catch (Exception e) { logger.error("Search Error: " + request.getRequestURI(),e); e.printStackTrace(); response.sendError(500); } } #location 270 #vulnerability type NULL_DEREFERENCE
#fixed code public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("reset")!=null) searchEngine.closeSearcher(); String search = request.getParameter("search"); String term = request.getParameter("term"); String type = request.getParameter("type"); String full = request.getParameter("full"); String memo = request.getParameter("memo"); String status = request.getParameter("status"); String sponsor = request.getParameter("sponsor"); String cosponsors = request.getParameter("cosponsors"); String sameas = request.getParameter("sameas"); String committee = request.getParameter("committee"); String location = request.getParameter("location"); String session = request.getParameter("session"); if(search != null) { request.setAttribute("search", search); term = search; } String tempTerm = null; if((tempTerm = BillCleaner.getDesiredBillNumber(term)) != null) { term = "oid:" + tempTerm; type = "bill"; System.out.println("!! " + tempTerm); } String sortField = request.getParameter("sort"); boolean sortOrder = false; if (request.getParameter("sortOrder")!=null) sortOrder = Boolean.parseBoolean(request.getParameter("sortOrder")); Date startDate = null; Date endDate = null; try { if (request.getParameter("startdate")!=null && (!request.getParameter("startdate").equals("mm/dd/yyyy"))) startDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("startdate")); } catch (java.text.ParseException e1) { logger.warn(e1); } try { if (request.getParameter("enddate")!=null && (!request.getParameter("enddate").equals("mm/dd/yyyy"))) { endDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("enddate")); Calendar cal = Calendar.getInstance(); cal.setTime(endDate); cal.set(Calendar.HOUR, 11); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); endDate = cal.getTime(); } } catch (java.text.ParseException e1) { logger.warn(e1); } String format = "html"; if (request.getParameter("format")!=null) format = request.getParameter("format"); int pageIdx = 1; int pageSize = 20; if (request.getParameter("pageIdx") != null) pageIdx = Integer.parseInt(request.getParameter("pageIdx")); if (request.getParameter("pageSize") != null) pageSize = Integer.parseInt(request.getParameter("pageSize")); //now calculate start, end idx based on pageIdx and pageSize int start = (pageIdx - 1) * pageSize; SearchResultSet srs; StringBuilder searchText = new StringBuilder(); if (term != null) searchText.append(term); try { if (type != null && type.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("otype:"); searchText.append(type.equals("res") ? "bill AND oid:r*":type); } if(session != null && session.length() > 0) { if(searchText.length() > 0) searchText.append(" AND "); searchText.append("year:" + session); } if (full != null && full.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("(full:\""); searchText.append(full); searchText.append("\""); searchText.append(" OR "); searchText.append("osearch:\""); searchText.append(full); searchText.append("\")"); } if (memo != null && memo.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("memo:\""); searchText.append(memo); searchText.append("\""); } if (status != null && status.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("status:\""); searchText.append(status); searchText.append("\""); } if (sponsor != null && sponsor.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sponsor:\""); searchText.append(sponsor); searchText.append("\""); } if (cosponsors != null && cosponsors.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("cosponsors:\""); searchText.append(cosponsors); searchText.append("\""); } if (sameas != null && sameas.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sameas:"); searchText.append(sameas); } if (committee != null && committee.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("committee:\""); searchText.append(committee); searchText.append("\""); } if (location != null && location.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("location:\""); searchText.append(location); searchText.append("\""); } if (startDate != null && endDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); searchText.append(endDate.getTime()); searchText.append("]"); } else if (startDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); cal.set(Calendar.HOUR, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); startDate = cal.getTime(); searchText.append(startDate.getTime()); searchText.append("]"); } term = searchText.toString(); term = BillCleaner.billFormat(term); request.setAttribute("term", term); request.setAttribute("type", type); //default behavior is to return only active bills, so if a user searches //s1234 and s1234a is available then s1234a should be returned if(sortField == null && (((search != null && search.contains("otype:bill")) || (term != null && term.contains("otype:bill"))) || (type != null && type.equals("bill")))) { sortField = "sortindex"; sortOrder = false; type = "bill"; } if (sortField!=null && !sortField.equals("")) { request.setAttribute("sortField", sortField); request.setAttribute("sortOrder",Boolean.toString(sortOrder)); } else { sortField = "when"; sortOrder = true; request.setAttribute("sortField", sortField); request.setAttribute("sortOrder", Boolean.toString(sortOrder)); } request.setAttribute(OpenLegConstants.PAGE_IDX,pageIdx+""); request.setAttribute(OpenLegConstants.PAGE_SIZE,pageSize+""); srs = null; if (term.length() == 0) { response.sendError(404); return; } String searchFormat = "json"; SenateResponse sr = null; if(term != null && !term.contains("year:") && !term.contains("when:") && !term.contains("oid:")) { if(type != null && type.equals("bill")) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } else { sr = searchEngine.search(term + " AND when:[" + DATE_START + " TO " + DATE_END + "]",searchFormat,start,pageSize,sortField,sortOrder); if(sr.getResults().isEmpty()) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } } } else { System.out.println("!!! " + term); sr = searchEngine.search(term,searchFormat,start,pageSize,sortField,sortOrder); } srs = new SearchResultSet(); srs.setTotalHitCount((Integer)sr.getMetadata().get("totalresults")); srs.setResults(ApiHelper.buildSearchResultList(sr)); if (srs != null) { if (srs.getResults().size() == 0) { response.sendError(404); } else { request.setAttribute("results", srs); String viewPath = "/views/search-" + format + DOT_JSP; getServletContext().getRequestDispatcher(viewPath).forward(request, response); } } else { logger.error("Search Error: " + request.getRequestURI()); response.sendError(500); } } catch (Exception e) { logger.error("Search Error: " + request.getRequestURI(),e); e.printStackTrace(); response.sendError(500); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("reset")!=null) searchEngine.closeSearcher(); String search = request.getParameter("search"); String term = request.getParameter("term"); String type = request.getParameter("type"); String full = request.getParameter("full"); String memo = request.getParameter("memo"); String status = request.getParameter("status"); String sponsor = request.getParameter("sponsor"); String cosponsors = request.getParameter("cosponsors"); String sameas = request.getParameter("sameas"); String committee = request.getParameter("committee"); String location = request.getParameter("location"); String session = request.getParameter("session"); if(search != null) { request.setAttribute("search", search); term = search; } String tempTerm = null; if((tempTerm = BillCleaner.getDesiredBillNumber(term)) != null) { term = "oid:" + tempTerm; type = "bill"; } String sortField = request.getParameter("sort"); boolean sortOrder = false; if (request.getParameter("sortOrder")!=null) sortOrder = Boolean.parseBoolean(request.getParameter("sortOrder")); Date startDate = null; Date endDate = null; try { if (request.getParameter("startdate")!=null && (!request.getParameter("startdate").equals("mm/dd/yyyy"))) startDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("startdate")); } catch (java.text.ParseException e1) { logger.warn(e1); } try { if (request.getParameter("enddate")!=null && (!request.getParameter("enddate").equals("mm/dd/yyyy"))) { endDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("enddate")); Calendar cal = Calendar.getInstance(); cal.setTime(endDate); cal.set(Calendar.HOUR, 11); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); endDate = cal.getTime(); } } catch (java.text.ParseException e1) { logger.warn(e1); } String format = "html"; if (request.getParameter("format")!=null) format = request.getParameter("format"); int pageIdx = 1; int pageSize = 20; if (request.getParameter("pageIdx") != null) pageIdx = Integer.parseInt(request.getParameter("pageIdx")); if (request.getParameter("pageSize") != null) pageSize = Integer.parseInt(request.getParameter("pageSize")); //now calculate start, end idx based on pageIdx and pageSize int start = (pageIdx - 1) * pageSize; SearchResultSet srs; StringBuilder searchText = new StringBuilder(); if (term != null) searchText.append(term); try { if (type != null && type.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("otype:"); searchText.append(type.equals("res") ? "bill AND oid:r*":type); } if(session != null && session.length() > 0) { if(searchText.length() > 0) searchText.append(" AND "); searchText.append("year:" + session); } if (full != null && full.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("(full:\""); searchText.append(full); searchText.append("\""); searchText.append(" OR "); searchText.append("osearch:\""); searchText.append(full); searchText.append("\")"); } if (memo != null && memo.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("memo:\""); searchText.append(memo); searchText.append("\""); } if (status != null && status.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("status:\""); searchText.append(status); searchText.append("\""); } if (sponsor != null && sponsor.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sponsor:\""); searchText.append(sponsor); searchText.append("\""); } if (cosponsors != null && cosponsors.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("cosponsors:\""); searchText.append(cosponsors); searchText.append("\""); } if (sameas != null && sameas.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sameas:"); searchText.append(sameas); } if (committee != null && committee.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("committee:\""); searchText.append(committee); searchText.append("\""); } if (location != null && location.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("location:\""); searchText.append(location); searchText.append("\""); } if (startDate != null && endDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); searchText.append(endDate.getTime()); searchText.append("]"); } else if (startDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); cal.set(Calendar.HOUR, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); startDate = cal.getTime(); searchText.append(startDate.getTime()); searchText.append("]"); } if (sortField!=null && !sortField.equals("")) { request.setAttribute("sortField", sortField); request.setAttribute("sortOrder",Boolean.toString(sortOrder)); } else { sortField = type != null && type.equals("bill") ? "sortindex":"when"; sortOrder = type != null && type.equals("bill") ? false:true; request.setAttribute("sortField", sortField); request.setAttribute("sortOrder", Boolean.toString(sortOrder)); } term = searchText.toString(); term = BillCleaner.billFormat(term); request.setAttribute("term", term); request.setAttribute("type", type); request.setAttribute(OpenLegConstants.PAGE_IDX,pageIdx+""); request.setAttribute(OpenLegConstants.PAGE_SIZE,pageSize+""); //default behavior is to return only active bills, so if a user searches //s1234 and s1234a is available then s1234a should be returned if(search == null && term != null && term.contains("otype:bill")) { term += " AND active:true"; type = "bill"; } srs = null; if (term.length() == 0) { response.sendError(404); return; } String searchFormat = "json"; SenateResponse sr = null; if(term != null && !term.contains("year:") && !term.contains("when:") && !term.contains("oid:")) { if(type != null && type.equals("bill")) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } else { sr = searchEngine.search(term + " AND when:[" + DATE_START + " TO " + DATE_END + "]",searchFormat,start,pageSize,sortField,sortOrder); if(sr.getResults().isEmpty()) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } } } else { sr = searchEngine.search(term,searchFormat,start,pageSize,sortField,sortOrder); } srs = new SearchResultSet(); srs.setTotalHitCount((Integer)sr.getMetadata().get("totalresults")); srs.setResults(ApiHelper.buildSearchResultList(sr)); if (srs != null) { if (srs.getResults().size() == 0) { response.sendError(404); } else { request.setAttribute("results", srs); String viewPath = "/views/search-" + format + DOT_JSP; getServletContext().getRequestDispatcher(viewPath).forward(request, response); } } else { logger.error("Search Error: " + request.getRequestURI()); response.sendError(500); } } catch (Exception e) { logger.error("Search Error: " + request.getRequestURI(),e); response.sendError(500); } } #location 29 #vulnerability type NULL_DEREFERENCE
#fixed code public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("reset")!=null) searchEngine.closeSearcher(); String search = request.getParameter("search"); String term = request.getParameter("term"); String type = request.getParameter("type"); String full = request.getParameter("full"); String memo = request.getParameter("memo"); String status = request.getParameter("status"); String sponsor = request.getParameter("sponsor"); String cosponsors = request.getParameter("cosponsors"); String sameas = request.getParameter("sameas"); String committee = request.getParameter("committee"); String location = request.getParameter("location"); String session = request.getParameter("session"); if(search != null) { request.setAttribute("search", search); term = search; } String tempTerm = null; if((tempTerm = BillCleaner.getDesiredBillNumber(term)) != null) { term = "oid:" + tempTerm; type = "bill"; } String sortField = request.getParameter("sort"); boolean sortOrder = false; if (request.getParameter("sortOrder")!=null) sortOrder = Boolean.parseBoolean(request.getParameter("sortOrder")); Date startDate = null; Date endDate = null; try { if (request.getParameter("startdate")!=null && (!request.getParameter("startdate").equals("mm/dd/yyyy"))) startDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("startdate")); } catch (java.text.ParseException e1) { logger.warn(e1); } try { if (request.getParameter("enddate")!=null && (!request.getParameter("enddate").equals("mm/dd/yyyy"))) { endDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("enddate")); Calendar cal = Calendar.getInstance(); cal.setTime(endDate); cal.set(Calendar.HOUR, 11); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); endDate = cal.getTime(); } } catch (java.text.ParseException e1) { logger.warn(e1); } String format = "html"; if (request.getParameter("format")!=null) format = request.getParameter("format"); int pageIdx = 1; int pageSize = 20; if (request.getParameter("pageIdx") != null) pageIdx = Integer.parseInt(request.getParameter("pageIdx")); if (request.getParameter("pageSize") != null) pageSize = Integer.parseInt(request.getParameter("pageSize")); //now calculate start, end idx based on pageIdx and pageSize int start = (pageIdx - 1) * pageSize; SearchResultSet srs; StringBuilder searchText = new StringBuilder(); if (term != null) searchText.append(term); try { if (type != null && type.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("otype:"); searchText.append(type.equals("res") ? "bill AND oid:r*":type); } if(session != null && session.length() > 0) { if(searchText.length() > 0) searchText.append(" AND "); searchText.append("year:" + session); } if (full != null && full.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("(full:\""); searchText.append(full); searchText.append("\""); searchText.append(" OR "); searchText.append("osearch:\""); searchText.append(full); searchText.append("\")"); } if (memo != null && memo.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("memo:\""); searchText.append(memo); searchText.append("\""); } if (status != null && status.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("status:\""); searchText.append(status); searchText.append("\""); } if (sponsor != null && sponsor.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sponsor:\""); searchText.append(sponsor); searchText.append("\""); } if (cosponsors != null && cosponsors.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("cosponsors:\""); searchText.append(cosponsors); searchText.append("\""); } if (sameas != null && sameas.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sameas:"); searchText.append(sameas); } if (committee != null && committee.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("committee:\""); searchText.append(committee); searchText.append("\""); } if (location != null && location.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("location:\""); searchText.append(location); searchText.append("\""); } if (startDate != null && endDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); searchText.append(endDate.getTime()); searchText.append("]"); } else if (startDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); cal.set(Calendar.HOUR, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); startDate = cal.getTime(); searchText.append(startDate.getTime()); searchText.append("]"); } if (sortField!=null && !sortField.equals("")) { request.setAttribute("sortField", sortField); request.setAttribute("sortOrder",Boolean.toString(sortOrder)); } else { sortField = "when"; sortOrder = true; request.setAttribute("sortField", sortField); request.setAttribute("sortOrder", Boolean.toString(sortOrder)); } term = searchText.toString(); term = BillCleaner.billFormat(term); request.setAttribute("term", term); request.setAttribute("type", type); //default behavior is to return only active bills, so if a user searches //s1234 and s1234a is available then s1234a should be returned if((search == null && (term != null && term.contains("otype:bill"))) || (type != null && type.equals("bill"))) { if(sortField == null) { sortField = "sortindex"; sortOrder = false; term += " AND active:true"; type = "bill"; } } request.setAttribute(OpenLegConstants.PAGE_IDX,pageIdx+""); request.setAttribute(OpenLegConstants.PAGE_SIZE,pageSize+""); srs = null; if (term.length() == 0) { response.sendError(404); return; } String searchFormat = "json"; SenateResponse sr = null; if(term != null && !term.contains("year:") && !term.contains("when:") && !term.contains("oid:")) { if(type != null && type.equals("bill")) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } else { sr = searchEngine.search(term + " AND when:[" + DATE_START + " TO " + DATE_END + "]",searchFormat,start,pageSize,sortField,sortOrder); if(sr.getResults().isEmpty()) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } } } else { sr = searchEngine.search(term,searchFormat,start,pageSize,sortField,sortOrder); } srs = new SearchResultSet(); srs.setTotalHitCount((Integer)sr.getMetadata().get("totalresults")); srs.setResults(ApiHelper.buildSearchResultList(sr)); if (srs != null) { if (srs.getResults().size() == 0) { response.sendError(404); } else { request.setAttribute("results", srs); String viewPath = "/views/search-" + format + DOT_JSP; getServletContext().getRequestDispatcher(viewPath).forward(request, response); } } else { logger.error("Search Error: " + request.getRequestURI()); response.sendError(500); } } catch (Exception e) { logger.error("Search Error: " + request.getRequestURI(),e); e.printStackTrace(); response.sendError(500); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws IOException { LRSConnect l = LRSConnect.getInstance(); System.out.println(l.getLbdcBill("s1234-2011").getSummary()); System.out.println(l.getLbdcBill("s2008-2011").getSummary()); System.out.println(l.getLbdcBill("s1-2011")); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) throws IOException, org.apache.lucene.queryParser.ParseException, InterruptedException { TreeSet<String> set = new TreeSet<String>(); set.addAll(Arrays.asList("summary","billno","year","sponsor","cosponsors","when","sameas","committee","status","location","session-type","chair")); for(String s:set) { System.out.print("\"" + s + "\", "); } // // ReportBuilder reportBuilder = new ReportBuilder(); // TreeSet<ReportBill> bills = reportBuilder.getBillReportSet("2011"); // // LRSConnect l = LRSConnect.getInstance(); // // for(ReportBill bill:bills) { // if(bill.getHeat() < 7) // break; // // System.out.print("testing bill " + bill.getBill()); // // if(l.getBillFromLbdc(bill.getBill()) == null) // System.out.println(" -- delete " + bill.getMissingFields()); // else // System.out.println(" -- keep " + bill.getMissingFields()); // // // Thread.currentThread().sleep(3600); // } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doParsing (String filePath) throws Exception { engine = new SearchEngine2(); XMLSENATEDATA senateData = parseStream(new FileReader(new File(filePath))); Iterator<Object> it = senateData.getSencalendarOrSencalendaractive().iterator(); Object nextItem = null; String action = null; Calendar calendar = null; Supplemental supplemental = null; ArrayList<LuceneObject> objectsToUpdate = new ArrayList<LuceneObject>(); PersistenceManager pm = PMF.getPersistenceManager(); while (it.hasNext()) { nextItem = it.next(); Transaction currentTx = pm.currentTransaction(); currentTx.begin(); if (nextItem instanceof XMLSencalendar) { XMLSencalendar xmlCalendar = (XMLSencalendar)nextItem; action = xmlCalendar.getAction(); calendar = getCalendar(pm, Calendar.TYPE_FLOOR,xmlCalendar.getNo(),xmlCalendar.getYear(),xmlCalendar.getSessyr()); supplemental = parseSupplemental(pm, calendar,xmlCalendar.getSupplemental()); supplemental.setCalendar(calendar); objectsToUpdate.add(calendar); } else if (nextItem instanceof XMLSencalendaractive) { XMLSencalendaractive xmlActiveList = (XMLSencalendaractive)nextItem; action = xmlActiveList.getAction(); calendar = getCalendar(pm, Calendar.TYPE_ACTIVE,xmlActiveList.getNo(),xmlActiveList.getYear(),xmlActiveList.getSessyr()); supplemental = parseSupplemental(pm, calendar,xmlActiveList.getSupplemental()); supplemental.setCalendar(calendar); objectsToUpdate.add(calendar); } if (action.equals("remove") && removeObject != null) { logger.info("REMOVING: " + removeObject.getClass() + "=" + removeObjectId); PMF.removePersistedObject(pm, removeObject.getClass(), removeObjectId); } currentTx.commit(); } Transaction currentTx = pm.currentTransaction(); try { currentTx.begin(); engine.indexSenateObjects(objectsToUpdate, new LuceneSerializer[]{new XmlSerializer(), new JsonSerializer()}); currentTx.commit(); } catch (Exception e) { currentTx.rollback(); } engine.optimize(); } #location 57 #vulnerability type NULL_DEREFERENCE
#fixed code public void doParsing (String filePath) throws Exception { engine = SearchEngine2.getInstance(); XMLSENATEDATA senateData = parseStream(new FileReader(new File(filePath))); Iterator<Object> it = senateData.getSencalendarOrSencalendaractive().iterator(); Object nextItem = null; String action = null; Calendar calendar = null; Supplemental supplemental = null; ArrayList<LuceneObject> objectsToUpdate = new ArrayList<LuceneObject>(); PersistenceManager pm = PMF.getPersistenceManager(); while (it.hasNext()) { nextItem = it.next(); Transaction currentTx = pm.currentTransaction(); currentTx.begin(); if (nextItem instanceof XMLSencalendar) { XMLSencalendar xmlCalendar = (XMLSencalendar)nextItem; action = xmlCalendar.getAction(); calendar = getCalendar(pm, Calendar.TYPE_FLOOR,xmlCalendar.getNo(),xmlCalendar.getYear(),xmlCalendar.getSessyr()); supplemental = parseSupplemental(pm, calendar,xmlCalendar.getSupplemental()); supplemental.setCalendar(calendar); objectsToUpdate.add(calendar); } else if (nextItem instanceof XMLSencalendaractive) { XMLSencalendaractive xmlActiveList = (XMLSencalendaractive)nextItem; action = xmlActiveList.getAction(); calendar = getCalendar(pm, Calendar.TYPE_ACTIVE,xmlActiveList.getNo(),xmlActiveList.getYear(),xmlActiveList.getSessyr()); supplemental = parseSupplemental(pm, calendar,xmlActiveList.getSupplemental()); supplemental.setCalendar(calendar); objectsToUpdate.add(calendar); } if (action.equals("remove") && removeObject != null) { logger.info("REMOVING: " + removeObject.getClass() + "=" + removeObjectId); PMF.removePersistedObject(pm, removeObject.getClass(), removeObjectId); } currentTx.commit(); } Transaction currentTx = pm.currentTransaction(); try { currentTx.begin(); engine.indexSenateObjects(objectsToUpdate, new LuceneSerializer[]{new XmlSerializer(), new JsonSerializer()}); currentTx.commit(); } catch (Exception e) { currentTx.rollback(); } engine.optimize(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Benchmark public int offerAndPollLoops() { final int burstSize = this.burstSize; for (int i = 0; i < burstSize; i++) { q.offer(DUMMY_MESSAGE); } Integer result = null; for (int i = 0; i < burstSize; i++) { result = q.poll(); } return result; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Benchmark public int offerAndPollLoops() { final int burstSize = this.burstSize; for (int i = 0; i < burstSize; i++) { q.offer(DUMMY_MESSAGE); } Integer result = DUMMY_MESSAGE; for (int i = 0; i < burstSize; i++) { result = q.poll(); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); this.primitiveArray = (A) directMemoryService.getObject(allocationStartAddress); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); // Clear array content directMemoryService.setMemory(arrayIndexStartAddress, arrayIndexScale * length, (byte) 0); primitiveArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(allocationStartAddress); switch (JvmUtil.getAddressSize()) { case JvmUtil.SIZE_32_BIT: jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder(); break; case JvmUtil.SIZE_64_BIT: int referenceSize = JvmUtil.getReferenceSize(); switch (referenceSize) { case JvmUtil.ADDRESSING_4_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; case JvmUtil.ADDRESSING_8_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; default: throw new AssertionError("Unsupported reference size: " + referenceSize); } break; default: throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize()); } } #location 59 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); this.currentIndex = 0; int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objectsStartAddress += (JvmUtil.getAddressSize() - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void objectRetrievedSuccessfullyFromExtendableObjectOffHeapPoolWithDefaultObjectOffHeapPool() { ExtendableObjectOffHeapPool<SampleOffHeapClass> extendableObjectPool = offHeapService.createOffHeapPool( new DefaultExtendableObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>(). elementType(SampleOffHeapClass.class). build()); List<SampleOffHeapClass> objList = new ArrayList<SampleOffHeapClass>(); for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = extendableObjectPool.get(); obj.setOrder(i); objList.add(obj); } for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objList.get(i); Assert.assertEquals(i, obj.getOrder()); } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void objectRetrievedSuccessfullyFromExtendableObjectOffHeapPoolWithDefaultObjectOffHeapPool() { ExtendableObjectOffHeapPool<SampleOffHeapClass> extendableObjectPool = offHeapService.createOffHeapPool( new DefaultExtendableObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>(). elementType(SampleOffHeapClass.class). build()); List<SampleOffHeapClass> objList = new ArrayList<SampleOffHeapClass>(); for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = extendableObjectPool.get(); Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); Assert.assertEquals(i, obj.getOrder()); objList.add(obj); } for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objList.get(i); Assert.assertEquals(i, obj.getOrder()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override public T getAt(int index) { checkAvailability(); if (index < 0 || index > length) { throw new IllegalArgumentException("Invalid index: " + index); } processObject( jvmAwareArrayElementAddressFinder.findAddress( arrayIndexStartAddress, arrayIndexScale, index)); T obj = ((T[])(objectArray))[index]; if (obj instanceof OffHeapAwareObject) { ((OffHeapAwareObject) obj).onGet(offHeapService, directMemoryService); } return obj; } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override public T getAt(int index) { checkAvailability(); if (index < 0 || index > length) { throw new IllegalArgumentException("Invalid index: " + index); } processObject( jvmAwareArrayElementAddressFinder.findAddress( arrayIndexStartAddress, arrayIndexScale, index)); T obj = ((T[])(getObjectArray()))[index]; if (obj instanceof OffHeapAwareObject) { ((OffHeapAwareObject) obj).onGet(offHeapService, directMemoryService); } return obj; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); this.currentIndex = 0; int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); this.currentIndex = 0; int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objectsStartAddress += (JvmUtil.getAddressSize() - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(allocationStartAddress); switch (JvmUtil.getAddressSize()) { case JvmUtil.SIZE_32_BIT: jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder(); break; case JvmUtil.SIZE_64_BIT: int referenceSize = JvmUtil.getReferenceSize(); switch (referenceSize) { case JvmUtil.ADDRESSING_4_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; case JvmUtil.ADDRESSING_8_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; default: throw new AssertionError("Unsupported reference size: " + referenceSize); } break; default: throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize()); } } #location 45 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected long allocateStringFromOffHeap(String str) { long addressOfStr = JvmUtil.addressOf(str); char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString); int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length); int strSize = stringSize + valueArraySize + JvmUtil.getAddressSize(); // Extra memory for possible aligning long addressMod1 = currentAddress % JvmUtil.getAddressSize(); if (addressMod1 != 0) { currentAddress += (JvmUtil.getAddressSize() - addressMod1); } if (currentAddress + strSize > allocationEndAddress) { return 0; } // Copy string object content to allocated area directMemoryService.copyMemory(addressOfStr, currentAddress, strSize); long valueAddress = currentAddress + stringSize; long addressMod2 = valueAddress % JvmUtil.getAddressSize(); if (addressMod2 != 0) { valueAddress += (JvmUtil.getAddressSize() - addressMod2); } // Copy value array in allocated string to allocated char array directMemoryService.copyMemory( JvmUtil.toNativeAddress( directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)), valueAddress, valueArraySize); // Now, value array in allocated string points to allocated char array directMemoryService.putAddress( currentAddress + valueArrayOffsetInString, JvmUtil.toJvmAddress(valueAddress)); long allocatedStrAddress = currentAddress; currentAddress += strSize; return allocatedStrAddress; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected long allocateStringFromOffHeap(String str) { long addressOfStr = directMemoryService.addressOf(str); char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString); int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length); int strSize = stringSize + valueArraySize; // + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning long addressMod1 = currentAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod1 != 0) { currentAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod1); } if (currentAddress + strSize > allocationEndAddress) { return 0; } // Copy string object content to allocated area directMemoryService.copyMemory(addressOfStr, currentAddress, strSize); long valueAddress = currentAddress + stringSize; long addressMod2 = valueAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod2 != 0) { valueAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod2); } // Copy value array in allocated string to allocated char array directMemoryService.copyMemory( JvmUtil.toNativeAddress( directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)), valueAddress, valueArraySize); // Now, value array in allocated string points to allocated char array directMemoryService.putAddress( currentAddress + valueArrayOffsetInString, JvmUtil.toJvmAddress(valueAddress)); long allocatedStrAddress = currentAddress; currentAddress += strSize; return allocatedStrAddress; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; sampleStr = new String(); sampleStrAddress = JvmUtil.addressOf(sampleStr); sampleCharArray = new char[0]; init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void init() { super.init(); currentAddress = stringsStartAddress; full = false; currentIndex = INDEX_NOT_YET_USED; currentBlockIndex = INDEX_NOT_YET_USED; directMemoryService.setMemory(inUseBlockAddress, inUseBlockCount, (byte)0); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void init() { super.init(); currentAddress = stringsStartAddress; full = false; currentSegmentIndex = INDEX_NOT_YET_USED; currentSegmentBlockIndex = INDEX_NOT_YET_USED; directMemoryService.setMemory(inUseBlockAddress, inUseBlockCount, (byte)0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 34 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void init() { super.init(); objectsStartAddress = allocationStartAddress; objectsEndAddress = allocationEndAddress; currentAddress = allocationStartAddress - objectSize; long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = allocationStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void init() { super.init(); objectsStartAddress = allocationStartAddress; // Allocated objects must start aligned as address size from start address of allocated address long addressMod = objectsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(allocationStartAddress); switch (JvmUtil.getAddressSize()) { case JvmUtil.SIZE_32_BIT: jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder(); break; case JvmUtil.SIZE_64_BIT: int referenceSize = JvmUtil.getReferenceSize(); switch (referenceSize) { case JvmUtil.ADDRESSING_4_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; case JvmUtil.ADDRESSING_8_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; default: throw new AssertionError("Unsupported reference size: " + referenceSize); } break; default: throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize()); } } #location 37 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void init() { super.init(); objectsStartAddress = allocationStartAddress; // Allocated objects must start aligned as address size from start address of allocated address long addressMod = objectsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void init() { super.init(); long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected long allocateStringFromOffHeap(String str) { long addressOfStr = JvmUtil.addressOf(str); char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString); int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length); int strSize = stringSize + valueArraySize + JvmUtil.getAddressSize(); // Extra memory for possible aligning long addressMod1 = currentAddress % JvmUtil.getAddressSize(); if (addressMod1 != 0) { currentAddress += (JvmUtil.getAddressSize() - addressMod1); } if (currentAddress + strSize > allocationEndAddress) { return 0; } // Copy string object content to allocated area directMemoryService.copyMemory(addressOfStr, currentAddress, strSize); long valueAddress = currentAddress + stringSize; long addressMod2 = valueAddress % JvmUtil.getAddressSize(); if (addressMod2 != 0) { valueAddress += (JvmUtil.getAddressSize() - addressMod2); } // Copy value array in allocated string to allocated char array directMemoryService.copyMemory( JvmUtil.toNativeAddress( directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)), valueAddress, valueArraySize); // Now, value array in allocated string points to allocated char array directMemoryService.putAddress( currentAddress + valueArrayOffsetInString, JvmUtil.toJvmAddress(valueAddress)); long allocatedStrAddress = currentAddress; currentAddress += strSize; return allocatedStrAddress; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected long allocateStringFromOffHeap(String str) { long addressOfStr = directMemoryService.addressOf(str); char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString); int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length); int strSize = stringSize + valueArraySize; // + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning long addressMod1 = currentAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod1 != 0) { currentAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod1); } if (currentAddress + strSize > allocationEndAddress) { return 0; } // Copy string object content to allocated area directMemoryService.copyMemory(addressOfStr, currentAddress, strSize); long valueAddress = currentAddress + stringSize; long addressMod2 = valueAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod2 != 0) { valueAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod2); } // Copy value array in allocated string to allocated char array directMemoryService.copyMemory( JvmUtil.toNativeAddress( directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)), valueAddress, valueArraySize); // Now, value array in allocated string points to allocated char array directMemoryService.putAddress( currentAddress + valueArrayOffsetInString, JvmUtil.toJvmAddress(valueAddress)); long allocatedStrAddress = currentAddress; currentAddress += strSize; return allocatedStrAddress; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType); // All index in object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); int estimatedSizeMod = estimatedStringSize % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (estimatedSizeMod != 0) { estimatedStringSize += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - estimatedSizeMod); } allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; totalSegmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { totalSegmentCount++; } inUseBlockCount = totalSegmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = totalSegmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; sampleStr = new String(); sampleStrAddress = JvmUtil.addressOf(sampleStr); sampleCharArray = new char[0]; init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); this.primitiveArray = (A) directMemoryService.getObject(allocationStartAddress); } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); // Clear array content directMemoryService.setMemory(arrayIndexStartAddress, arrayIndexScale * length, (byte) 0); primitiveArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType); // All index in object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(allocationStartAddress); switch (JvmUtil.getAddressSize()) { case JvmUtil.SIZE_32_BIT: jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder(); break; case JvmUtil.SIZE_64_BIT: int referenceSize = JvmUtil.getReferenceSize(); switch (referenceSize) { case JvmUtil.ADDRESSING_4_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; case JvmUtil.ADDRESSING_8_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; default: throw new AssertionError("Unsupported reference size: " + referenceSize); } break; default: throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize()); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; sampleStr = new String(); sampleStrAddress = JvmUtil.addressOf(sampleStr); sampleCharArray = new char[0]; init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean isMe(A array) { checkAvailability(); return objectArray == array; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean isMe(A array) { checkAvailability(); return getObjectArray() == array; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void objectRetrievedSuccessfullyFromEagerReferencedObjectOffHeapPool() { EagerReferencedObjectOffHeapPool<SampleOffHeapClass> objectPool = offHeapService.createOffHeapPool( new ObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>(). type(SampleOffHeapClass.class). objectCount(ELEMENT_COUNT). referenceType(ObjectPoolReferenceType.EAGER_REFERENCED). build()); for (int i = 0; i < ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objectPool.get(); Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); Assert.assertEquals(i, obj.getOrder()); } objectPool.reset(); for (int i = 0; i < ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objectPool.getAt(i); Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); Assert.assertEquals(i, obj.getOrder()); } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void objectRetrievedSuccessfullyFromEagerReferencedObjectOffHeapPool() { EagerReferencedObjectOffHeapPool<SampleOffHeapClass> objectPool = offHeapService.createOffHeapPool( new ObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>(). type(SampleOffHeapClass.class). objectCount(ELEMENT_COUNT). referenceType(ObjectPoolReferenceType.EAGER_REFERENCED). build()); for (int i = 0; true; i++) { SampleOffHeapClass obj = objectPool.get(); if (obj == null) { break; } Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); Assert.assertEquals(i, obj.getOrder()); } objectPool.reset(); for (int i = 0; i < ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objectPool.getAt(i); Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); Assert.assertEquals(i, obj.getOrder()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); this.primitiveArray = (A) directMemoryService.getObject(allocationStartAddress); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); // Clear array content directMemoryService.setMemory(arrayIndexStartAddress, arrayIndexScale * length, (byte) 0); primitiveArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { directMemoryService.copyMemory( sampleObjectAddress, objStartAddress + (l * objectSize), objectSize); } /* long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } */ } else { // All indexes in object pool array point to empty (null) object for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0L); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); } #location 39 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { directMemoryService.copyMemory( sampleObjectAddress, objStartAddress + (l * objectSize), objectSize); } /* long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } */ } else { // All indexes in object pool array point to empty (null) object for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0L); } } //this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); directMemoryService.setObjectField(this, "objectArray", directMemoryService.getObject(arrayStartAddress)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType); // All index in object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; sampleStr = new String(); sampleStrAddress = JvmUtil.addressOf(sampleStr); sampleCharArray = new char[0]; init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 28 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); int estimatedSizeMod = estimatedStringSize % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (estimatedSizeMod != 0) { estimatedStringSize += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - estimatedSizeMod); } allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; totalSegmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { totalSegmentCount++; } inUseBlockCount = totalSegmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = totalSegmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { directMemoryService.copyMemory( sampleObjectAddress, objStartAddress + (l * objectSize), objectSize); } /* long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } */ } else { // All indexes in object pool array point to empty (null) object for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0L); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); } #location 39 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { directMemoryService.copyMemory( sampleObjectAddress, objStartAddress + (l * objectSize), objectSize); } /* long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } */ } else { // All indexes in object pool array point to empty (null) object for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0L); } } // this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void init() { super.init(); objectsStartAddress = allocationStartAddress; // Allocated objects must start aligned as address size from start address of allocated address long addressMod = objectsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void init() { super.init(); long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(allocationStartAddress); switch (JvmUtil.getAddressSize()) { case JvmUtil.SIZE_32_BIT: jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder(); break; case JvmUtil.SIZE_64_BIT: int referenceSize = JvmUtil.getReferenceSize(); switch (referenceSize) { case JvmUtil.ADDRESSING_4_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; case JvmUtil.ADDRESSING_8_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; default: throw new AssertionError("Unsupported reference size: " + referenceSize); } break; default: throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize()); } } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; sampleStr = new String(); sampleStrAddress = JvmUtil.addressOf(sampleStr); sampleCharArray = new char[0]; init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; sampleStr = new String(); sampleStrAddress = JvmUtil.addressOf(sampleStr); sampleCharArray = new char[0]; init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void init() { super.init(); currentAddress = stringsStartAddress; full = false; currentIndex = INDEX_NOT_YET_USED; currentBlockIndex = INDEX_NOT_YET_USED; directMemoryService.setMemory(inUseBlockAddress, inUseBlockCount, (byte)0); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void init() { super.init(); currentAddress = stringsStartAddress; full = false; currentSegmentIndex = INDEX_NOT_YET_USED; currentSegmentBlockIndex = INDEX_NOT_YET_USED; directMemoryService.setMemory(inUseBlockAddress, inUseBlockCount, (byte)0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(allocationStartAddress); switch (JvmUtil.getAddressSize()) { case JvmUtil.SIZE_32_BIT: jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder(); break; case JvmUtil.SIZE_64_BIT: int referenceSize = JvmUtil.getReferenceSize(); switch (referenceSize) { case JvmUtil.ADDRESSING_4_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; case JvmUtil.ADDRESSING_8_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; default: throw new AssertionError("Unsupported reference size: " + referenceSize); } break; default: throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize()); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); this.primitiveArray = (A) directMemoryService.getObject(allocationStartAddress); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); // Clear array content directMemoryService.setMemory(arrayIndexStartAddress, arrayIndexScale * length, (byte) 0); primitiveArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType); // All index in object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(allocationStartAddress); switch (JvmUtil.getAddressSize()) { case JvmUtil.SIZE_32_BIT: jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder(); break; case JvmUtil.SIZE_64_BIT: int referenceSize = JvmUtil.getReferenceSize(); switch (referenceSize) { case JvmUtil.ADDRESSING_4_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; case JvmUtil.ADDRESSING_8_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; default: throw new AssertionError("Unsupported reference size: " + referenceSize); } break; default: throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize()); } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public T getAt(int index) { checkAvailability(); if (index < 0 || index >= objectCount) { throw new IllegalArgumentException("Invalid index: " + index); } if (getInUseFromObjectIndex(index) != OBJECT_IS_AVAILABLE) { throw new ObjectInUseException(index); } if (index == 0) { System.out.println(directMemoryService.addressOf(objectArray) + ", " + arrayStartAddress); } // Address of class could be changed by GC at "Compact" phase. //long address = objectsStartAddress + (index * objectSize); //updateClassPointerOfObject(address); return takeObject(objectArray[index]); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public T getAt(int index) { checkAvailability(); if (index < 0 || index >= objectCount) { throw new IllegalArgumentException("Invalid index: " + index); } if (getInUseFromObjectIndex(index) != OBJECT_IS_AVAILABLE) { throw new ObjectInUseException(index); } // Address of class could be changed by GC at "Compact" phase. //long address = objectsStartAddress + (index * objectSize); //updateClassPointerOfObject(address); return takeObject(objectArray[index]); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public T getAt(int index) { checkAvailability(); if (index < 0 || index >= objectCount) { throw new IllegalArgumentException("Invalid index: " + index); } if (getInUseFromObjectIndex(index) != OBJECT_IS_AVAILABLE) { throw new ObjectInUseException(index); } if (index == 0) { System.out.println(directMemoryService.addressOf(objectArray) + ", " + arrayStartAddress); } // Address of class could be changed by GC at "Compact" phase. //long address = objectsStartAddress + (index * objectSize); //updateClassPointerOfObject(address); return takeObject(objectArray[index]); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public T getAt(int index) { checkAvailability(); if (index < 0 || index >= objectCount) { throw new IllegalArgumentException("Invalid index: " + index); } if (getInUseFromObjectIndex(index) != OBJECT_IS_AVAILABLE) { throw new ObjectInUseException(index); } // Address of class could be changed by GC at "Compact" phase. //long address = objectsStartAddress + (index * objectSize); //updateClassPointerOfObject(address); return takeObject(objectArray[index]); }
Below is the vulnerable code, please generate the patch based on the following information.