output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { // key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); timeoutClose(); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } }
#vulnerable code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } }
#vulnerable code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } ByteBufferStream.free(packet.buffers[1]); clearTimeout(); handler.onSended(this, packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { // key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); timeoutClose(); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } }
#vulnerable code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Map<String, String> filterInfo(Map<String, String> info) { Map<String, String> newInfo = Maps.newHashMap(info); String limitLine = newInfo.remove(PUSH_PROPERTIES_LIMIT); Set<String> limitKeys = getLimitKeys(limitLine); if (limitKeys.isEmpty()) { return newInfo; } ImmutableMap.Builder<String, String> result = ImmutableMap.builder(); for (String key : limitKeys) { result.put(key, newInfo.get(key)); } return result.build(); }
#vulnerable code private Map<String, String> filterInfo(Map<String, String> info) { HashMap<String, String> newInfo = Maps.newHashMap(info); String limit = newInfo.get(PUSH_PROPERTIES_LIMIT); if (Strings.isNullOrEmpty(limit)) { newInfo.remove(PUSH_PROPERTIES_LIMIT); return ImmutableMap.copyOf(newInfo); } List<String> limitList = PUSH_LIMIT_SPLITTER.splitToList(limit); if (limitList.size() == 0) { newInfo.remove(PUSH_PROPERTIES_LIMIT); return ImmutableMap.copyOf(newInfo); } ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (String key : limitList) { builder.put(key, newInfo.get(key)); } return builder.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public T blpopObject(int timeout, String key, Class clazz) { this.setSchema(clazz); Jedis jedis = null; try { jedis = jedisPool.getResource(); List<byte[]> bytes = jedis.blpop(timeout, key.getBytes()); if (bytes == null || bytes.size() == 0) { return null; } return getBytes(bytes.get(1)); } finally { jedis.close(); } }
#vulnerable code public T blpopObject(int timeout, String key, Class clazz) { this.setSchema(clazz); Jedis jedis = null; try { List<byte[]> bytes = jedis.blpop(timeout, key.getBytes()); if (bytes == null || bytes.size() == 0) { return null; } return getBytes(bytes.get(1)); } finally { jedis.close(); } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPostMultipleFiles() throws JSONException, URISyntaxException { HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .field("param3", "wot") .field("file1", new File(getClass().getResource("/test").toURI())) .field("file2", new File(getClass().getResource("/test").toURI())) .asJson(); parse(response) .assertParam("param3", "wot") .assertFileContent("file1", "This is a test file") .assertFileContent("file2", "This is a test file"); }
#vulnerable code @Test public void testPostMultipleFiles() throws JSONException, URISyntaxException { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("param3", "wot").field("file1", new File(getClass().getResource("/test").toURI())).field("file2", new File(getClass().getResource("/test").toURI())).asJson(); JSONObject names = response.getBody().getObject().getJSONObject("files"); assertEquals(2, names.length()); assertEquals("This is a test file", names.getString("file1")); assertEquals("This is a test file", names.getString("file2")); assertEquals("wot", response.getBody().getObject().getJSONObject("form").getString("param3")); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCustomUserAgent() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .header("user-agent", "hello-world") .asJson(); RequestCapture json = parse(response); json.assertHeader("User-Agent", "hello-world"); }
#vulnerable code @Test public void testCustomUserAgent() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get?name=mark").header("user-agent", "hello-world").asJson(); assertEquals("hello-world", response.getBody().getObject().getJSONObject("headers").getString("User-Agent")); GetRequest getRequest = Unirest.get("http"); for (Object current : Arrays.asList(0, 1, 2)) { getRequest.queryString("name", current); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { // Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") // .header("accept", "application/json") // .field("param1", "value1") // .field("param2","bye") // .asJsonAsync(); // // assertNotNull(future); // HttpResponse<JsonNode> jsonResponse = future.get(); // // assertTrue(jsonResponse.getHeaders().size() > 0); // assertTrue(jsonResponse.getBody().toString().length() > 0); // assertFalse(jsonResponse.getRawBody() == null); // assertEquals(200, jsonResponse.getCode()); // // JsonNode json = jsonResponse.getBody(); // assertFalse(json.isArray()); // assertNotNull(json.getObject()); // assertNotNull(json.getArray()); // assertEquals(1, json.getArray().length()); // assertNotNull(json.getArray().get(0)); Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2", "value2") .asJsonAsync(new Callback<JsonNode>() { public void failed(Exception e) { System.out.println("The request has failed"); } public void completed(HttpResponse<JsonNode> response) { int code = response.getCode(); Map<String, String> headers = response.getHeaders(); JsonNode body = response.getBody(); InputStream rawBody = response.getRawBody(); } public void cancelled() { System.out.println("The request has been cancelled"); } }); }
#vulnerable code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2","bye") .asJsonAsync(); assertNotNull(future); HttpResponse<JsonNode> jsonResponse = future.get(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getCode()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static <T> MashapeResponse<T> doRequest (Class<T> clazz, HttpMethod httpMethod, String url, Map<String, Object> parameters, ContentType contentType, ResponseType responseType, List<Authentication> authenticationHandlers) { if (authenticationHandlers == null) authenticationHandlers = new ArrayList<Authentication>(); if (parameters == null) parameters = new HashMap<String, Object>(); List<Header> headers = new LinkedList<Header>(); // Handle authentications for (Authentication authentication : authenticationHandlers) { if (authentication instanceof HeaderAuthentication) { headers.addAll(authentication.getHeaders()); } else { Map<String, String> queryParameters = authentication.getQueryParameters(); if (authentication instanceof QueryAuthentication) { parameters.putAll(queryParameters); } else if (authentication instanceof OAuth10aAuthentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_SECRET) == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException("Before consuming OAuth endpoint, invoke authorize('access_token','access_secret') with not null values"); } headers.add(new BasicHeader("x-mashape-oauth-consumerkey", queryParameters.get(OAuthAuthentication.CONSUMER_KEY))); headers.add(new BasicHeader("x-mashape-oauth-consumersecret", queryParameters.get(OAuthAuthentication.CONSUMER_SECRET))); headers.add(new BasicHeader("x-mashape-oauth-accesstoken", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN))); headers.add(new BasicHeader("x-mashape-oauth-accesssecret", queryParameters.get(OAuthAuthentication.ACCESS_SECRET))); } else if (authentication instanceof OAuth2Authentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException("Before consuming OAuth endpoint, invoke authorize('access_token') with a not null value"); } parameters.put("access_token", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN)); } } } // Sanitize null parameters Set<String> keySet = new HashSet<String>(parameters.keySet()); for (String key : keySet) { if (parameters.get(key) == null) { parameters.remove(key); } } headers.add(new BasicHeader("User-Agent", USER_AGENT)); HttpUriRequest request = null; switch(httpMethod) { case GET: request = new HttpGet(url + "?" + HttpUtils.getQueryString(parameters)); break; case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDeleteWithBody(url); break; case PATCH: request = new HttpPatchWithBody(url); break; } for(Header header : headers) { request.addHeader(header); } if (httpMethod != HttpMethod.GET) { switch(contentType) { case BINARY: MultipartEntity entity = new MultipartEntity(); for(Entry<String, Object> parameter : parameters.entrySet()) { if (parameter.getValue() instanceof File) { entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue())); } else { try { entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } ((HttpEntityEnclosingRequestBase) request).setEntity(entity); break; case FORM: try { ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } break; case JSON: String jsonBody = null; if((parameters.get(JSON_PARAM_BODY) != null)) { String jsonParamBody = parameters.get(JSON_PARAM_BODY).toString(); jsonBody = (HttpUtils.isJson(jsonParamBody)) ? jsonParamBody : gson.toJson(jsonParamBody); } try { ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(jsonBody, "UTF-8")); ((HttpEntityEnclosingRequestBase) request).setHeader(new BasicHeader("Content-Type", "application/json")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpResponse response; try { response = client.execute(request); } catch (Exception e) { throw new RuntimeException(e); } MashapeResponse<T> mashapeResponse = HttpUtils.getResponse(responseType, response); return mashapeResponse; }
#vulnerable code public static <T> MashapeResponse<T> doRequest (Class<T> clazz, HttpMethod httpMethod, String url, Map<String, Object> parameters, ContentType contentType, ResponseType responseType, List<Authentication> authenticationHandlers) { if (authenticationHandlers == null) authenticationHandlers = new ArrayList<Authentication>(); if (parameters == null) parameters = new HashMap<String, Object>(); List<Header> headers = new LinkedList<Header>(); // Handle authentications for (Authentication authentication : authenticationHandlers) { if (authentication instanceof HeaderAuthentication) { headers.addAll(authentication.getHeaders()); } else { Map<String, String> queryParameters = authentication.getQueryParameters(); if (authentication instanceof QueryAuthentication) { parameters.putAll(queryParameters); } else if (authentication instanceof OAuth10aAuthentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_SECRET) == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException("Before consuming OAuth endpoint, invoke authorize('access_token','access_secret') with not null values"); } headers.add(new BasicHeader("x-mashape-oauth-consumerkey", queryParameters.get(OAuthAuthentication.CONSUMER_KEY))); headers.add(new BasicHeader("x-mashape-oauth-consumersecret", queryParameters.get(OAuthAuthentication.CONSUMER_SECRET))); headers.add(new BasicHeader("x-mashape-oauth-accesstoken", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN))); headers.add(new BasicHeader("x-mashape-oauth-accesssecret", queryParameters.get(OAuthAuthentication.ACCESS_SECRET))); } else if (authentication instanceof OAuth2Authentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException("Before consuming OAuth endpoint, invoke authorize('access_token') with a not null value"); } parameters.put("access_token", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN)); } } } // Sanitize null parameters Set<String> keySet = new HashSet<String>(parameters.keySet()); for (String key : keySet) { if (parameters.get(key) == null) { parameters.remove(key); } } headers.add(new BasicHeader("User-Agent", USER_AGENT)); HttpUriRequest request = null; switch(httpMethod) { case GET: request = new HttpGet(url + "?" + HttpUtils.getQueryString(parameters)); break; case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDeleteWithBody(url); break; case PATCH: request = new HttpPatchWithBody(url); break; } for(Header header : headers) { request.addHeader(header); } if (httpMethod != HttpMethod.GET) { switch(contentType) { case BINARY: MultipartEntity entity = new MultipartEntity(); for(Entry<String, Object> parameter : parameters.entrySet()) { if (parameter.getValue() instanceof File) { entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue())); } else { try { entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } ((HttpEntityEnclosingRequestBase) request).setEntity(entity); break; case FORM: try { ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } break; case JSON: String jsonBody = null; if((parameters.get(JSON_PARAM_BODY) == null)) { String jsonParamBody = parameters.get(JSON_PARAM_BODY).toString(); jsonBody = (HttpUtils.isJson(jsonParamBody)) ? jsonParamBody : gson.toJson(jsonParamBody); } try { ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(jsonBody, "UTF-8")); ((HttpEntityEnclosingRequestBase) request).setHeader(new BasicHeader("Content-Type", "application/json")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpResponse response; try { response = client.execute(request); } catch (Exception e) { throw new RuntimeException(e); } MashapeResponse<T> mashapeResponse = HttpUtils.getResponse(responseType, response); return mashapeResponse; } #location 98 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPostRawBody() { String sourceString = "'\"@こんにちは-test-123-" + Math.random(); byte[] sentBytes = sourceString.getBytes(); HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .body(sentBytes) .asJson(); RequestCapture json = parse(response); json.asserBody(sourceString); }
#vulnerable code @Test public void testPostRawBody() { String sourceString = "'\"@こんにちは-test-123-" + Math.random(); byte[] sentBytes = sourceString.getBytes(); HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").body(sentBytes).asJson(); assertEquals(sourceString, response.getBody().getObject().getString("data")); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMultipartAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { Unirest.post("http://httpbin.org/post") .field("name", "Mark") .field("file", new File(getClass().getResource("/test").toURI())).asJsonAsync(new Callback<JsonNode>() { public void failed(UnirestException e) { fail(); } public void completed(HttpResponse<JsonNode> response) { assertTrue(response.getHeaders().size() > 0); assertTrue(response.getBody().toString().length() > 0); assertFalse(response.getRawBody() == null); assertEquals(200, response.getCode()); JsonNode json = response.getBody(); System.out.println(json); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertEquals("This \nis \na \ntest \nfile", json.getObject().getJSONObject("files").getString("file")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); status = true; lock.countDown(); } public void cancelled() { fail(); } }); lock.await(10, TimeUnit.SECONDS); assertTrue(status); }
#vulnerable code @Test public void testMultipartAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") .field("file", new File(getClass().getResource("/test").toURI())).asJsonAsync(new Callback<JsonNode>() { public void failed(UnirestException e) { // TODO Auto-generated method stub } public void completed(HttpResponse<JsonNode> response) { assertTrue(response.getHeaders().size() > 0); assertTrue(response.getBody().toString().length() > 0); assertFalse(response.getRawBody() == null); assertEquals(200, response.getCode()); JsonNode json = response.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } public void cancelled() { // TODO Auto-generated method stub } }); HttpResponse<JsonNode> response = future.get(); assertTrue(response.getHeaders().size() > 0); assertTrue(response.getBody().toString().length() > 0); assertFalse(response.getRawBody() == null); assertEquals(200, response.getCode()); JsonNode json = response.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); // assertNotNull(json.getObject().getJSONObject("files")); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); MultipartBody request = Unirest.post(MockServer.HOST + "/post") .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) .field("name", "Mark") .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); HttpResponse<JsonNode> jsonResponse = request .asJson(); assertEquals(200, jsonResponse.getStatus()); FormCapture json = TestUtils.read(jsonResponse, FormCapture.class); json.assertHeader("Accept", ContentType.MULTIPART_FORM_DATA.toString()); json.assertQuery("name", "Mark"); assertEquals("application/octet-stream", json.getFile("image.jpg").type); // assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); // assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); }
#vulnerable code @Test public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); MultipartBody request = Unirest.post(MockServer.HOST + "/post") .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) .field("name", "Mark") .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); HttpResponse<JsonNode> jsonResponse = request .asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); JSONObject object = json.getObject(); assertNotNull(object); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(object.getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDeleteBody() throws JSONException, UnirestException { String body = "{\"jsonString\":{\"members\":\"members1\"}}"; HttpResponse<JsonNode> response = Unirest.delete(MockServer.DELETE) .body(body) .asJson(); assertEquals(200, response.getStatus()); parse(response).asserBody(body); }
#vulnerable code @Test public void testDeleteBody() throws JSONException, UnirestException { String body = "{\"jsonString\":{\"members\":\"members1\"}}"; HttpResponse<JsonNode> response = Unirest.delete("http://httpbin.org/delete").body(body).asJson(); assertEquals(200, response.getStatus()); assertEquals(body, response.getBody().getObject().getString("data")); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetMultiple() throws JSONException, UnirestException { for (int i = 1; i <= 20; i++) { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON + "?try=" + i).asJson(); parse(response).assertQuery("try", String.valueOf(i)); } }
#vulnerable code @Test public void testGetMultiple() throws JSONException, UnirestException { for (int i = 1; i <= 20; i++) { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get?try=" + i).asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("try"), ((Integer) i).toString()); } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPostCollection() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .field("name", Arrays.asList("Mark", "Tom")) .asJson(); parse(response) .assertParam("name", "Mark") .assertParam("name", "Tom"); }
#vulnerable code @Test public void testPostCollection() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("name", Arrays.asList("Mark", "Tom")).asJson(); JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GET) .queryString("name", Arrays.asList("Mark", "Tom")) .asJson(); parse(response) .assertParam("name", "Mark") .assertParam("name", "Tom"); }
#vulnerable code @Test public void testGetArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString("name", Arrays.asList("Mark", "Tom")).asJson(); JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testQueryStringEncoding() throws JSONException, UnirestException { String testKey = "email2=someKey&email"; String testValue = "[email protected]"; HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .queryString(testKey, testValue) .asJson(); parse(response).assertQuery(testKey, testValue); }
#vulnerable code @Test public void testQueryStringEncoding() throws JSONException, UnirestException { String testKey = "email2=someKey&email"; String testValue = "[email protected]"; HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString(testKey, testValue).asJson(); assertEquals(testValue, response.getBody().getObject().getJSONObject("args").getString(testKey)); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetUTF8() { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .header("accept", "application/json") .queryString("param3", "こんにちは") .asJson(); FormCapture json = TestUtils.read(response, FormCapture.class); json.assertQuery("param3", "こんにちは"); }
#vulnerable code @Test public void testGetUTF8() { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString("param3", "こんにちは").asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("param3"), "こんにちは"); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testObjectMapperWrite() { Unirest.setObjectMapper(new JacksonObjectMapper()); GetResponse postResponseMock = new GetResponse(); postResponseMock.setUrl(MockServer.POST); HttpResponse<JsonNode> postResponse = Unirest.post(postResponseMock.getUrl()) .header("accept", "application/json") .header("Content-Type", "application/json") .body(postResponseMock) .asJson(); assertEquals(200, postResponse.getStatus()); parse(postResponse) .asserBody("{\"url\":\"http://localhost:4567/post\"}"); }
#vulnerable code @Test public void testObjectMapperWrite() { Unirest.setObjectMapper(new JacksonObjectMapper()); GetResponse postResponseMock = new GetResponse(); postResponseMock.setUrl("http://httpbin.org/post"); HttpResponse<JsonNode> postResponse = Unirest.post(postResponseMock.getUrl()).header("accept", "application/json").header("Content-Type", "application/json").body(postResponseMock).asJson(); assertEquals(200, postResponse.getStatus()); assertEquals(postResponse.getBody().getObject().getString("data"), "{\"url\":\"http://httpbin.org/post\"}"); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetQuerystringArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GET) .queryString("name", "Mark") .queryString("name", "Tom") .asJson(); parse(response) .assertParam("name", "Mark") .assertParam("name", "Tom"); }
#vulnerable code @Test public void testGetQuerystringArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString("name", "Mark").queryString("name", "Tom").asJson(); JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDelete() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.delete(MockServer.DELETE).asJson(); assertEquals(200, response.getStatus()); response = Unirest.delete(MockServer.DELETE) .field("name", "mark") .field("foo","bar") .asJson(); RequestCapture parse = parse(response); parse.assertParam("name", "mark"); parse.assertParam("foo", "bar"); }
#vulnerable code @Test public void testDelete() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.delete("http://httpbin.org/delete").asJson(); assertEquals(200, response.getStatus()); response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson(); assertEquals("mark", response.getBody().getObject().getJSONObject("form").getString("name")); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPostBinaryUTF8() throws URISyntaxException { HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .header("Accept", ContentType.MULTIPART_FORM_DATA.getMimeType()) .field("param3", "こんにちは") .field("file", new File(getClass().getResource("/test").toURI())) .asJson(); FormCapture json = TestUtils.read(response, FormCapture.class); json.assertQuery("param3", "こんにちは"); json.getFile("test").assertBody("This is a test file"); }
#vulnerable code @Test public void testPostBinaryUTF8() throws URISyntaxException { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("param3", "こんにちは").field("file", new File(getClass().getResource("/test").toURI())).asJson(); assertEquals("This is a test file", response.getBody().getObject().getJSONObject("files").getString("file")); assertEquals("こんにちは", response.getBody().getObject().getJSONObject("form").getString("param3")); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCaseInsensitiveHeaders() { GetRequest request = Unirest.get(MockServer.GET) .header("Name", "Marco"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); parse(request.asJson()) .assertHeader("Name", "Marco"); request = Unirest.get(MockServer.GET).header("Name", "Marco").header("Name", "John"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("John", request.getHeaders().get("name").get(1)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("John", request.getHeaders().get("NAme").get(1)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); assertEquals("John", request.getHeaders().get("Name").get(1)); }
#vulnerable code @Test public void testCaseInsensitiveHeaders() { GetRequest request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); JSONObject headers = request.asJson().getBody().getObject().getJSONObject("headers"); assertEquals("Marco", headers.getString("Name")); request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco").header("Name", "John"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("John", request.getHeaders().get("name").get(1)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("John", request.getHeaders().get("NAme").get(1)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); assertEquals("John", request.getHeaders().get("Name").get(1)); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMultipartInputStreamContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException { FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); MultipartBody request = Unirest.post(HOST + "/post") .field("name", "Mark") .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); HttpResponse<JsonNode> jsonResponse = request .asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); JSONObject object = json.getObject(); assertNotNull(object); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(object.getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); }
#vulnerable code @Test public void testMultipartInputStreamContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException { HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())), ContentType.APPLICATION_OCTET_STREAM, "image.jpg").asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(json.getObject().getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:application/octet-stream")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { Future<HttpResponse<JsonNode>> future = Unirest.post(MockServer.POST) .header("accept", "application/json") .field("param1", "value1") .field("param2", "bye") .asJsonAsync(); assertNotNull(future); RequestCapture req = parse(future.get()); req.assertParam("param1", "value1"); req.assertParam("param2", "bye"); }
#vulnerable code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(); assertNotNull(future); HttpResponse<JsonNode> jsonResponse = future.get(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetFields2() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .queryString("email", "[email protected]") .asJson(); parse(response).assertQuery("email", "[email protected]"); }
#vulnerable code @Test public void testGetFields2() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString("email", "[email protected]").asJson(); assertEquals("[email protected]", response.getBody().getObject().getJSONObject("args").getString("email")); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPostUTF8() { HttpResponse response = Unirest.post(MockServer.POSTJSON) .header("accept", "application/json") .field("param3", "こんにちは") .asJson(); FormCapture json = TestUtils.read(response, FormCapture.class); json.assertQuery("param3", "こんにちは"); }
#vulnerable code @Test public void testPostUTF8() { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("param3", "こんにちは").asJson(); assertEquals(response.getBody().getObject().getJSONObject("form").getString("param3"), "こんにちは"); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBasicAuth() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .basicAuth("user", "test") .asJson(); parse(response).assertHeader("Authorization", "Basic dXNlcjp0ZXN0"); }
#vulnerable code @Test public void testBasicAuth() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/headers").basicAuth("user", "test").asJson(); assertEquals("Basic dXNlcjp0ZXN0", response.getBody().getObject().getJSONObject("headers").getString("Authorization")); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPostArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .field("name", "Mark") .field("name", "Tom") .asJson(); parse(response) .assertParam("name", "Mark") .assertParam("name", "Tom"); }
#vulnerable code @Test public void testPostArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("name", "Tom").asJson(); JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRequests() throws JSONException { HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2","bye") .asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getCode()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); }
#vulnerable code @Test public void testRequests() throws Exception { HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2","bye") .asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getCode()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isStarted() { try { lock.lock(); return client.getState() == CuratorFrameworkState.STARTED; } finally { lock.unlock(); } }
#vulnerable code public boolean isStarted() { return client.getState() == CuratorFrameworkState.STARTED; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void postEvent(ApplicationType applicationType, ActionType actionType, ProtocolType protocolType, ProtocolMessage message) { if (message.getException() == null) { return; } ProtocolEvent protocolEvent = new ProtocolEvent(applicationType, actionType, protocolType, message); if (eventNotification) { EventControllerFactory.getAsyncController().post(protocolEvent); } }
#vulnerable code public static void postEvent(ApplicationType applicationType, ActionType actionType, ProtocolType protocolType, ProtocolMessage message) { if (message.getException() == null) { return; } ProtocolEvent protocolEvent = new ProtocolEvent(applicationType, actionType, protocolType, message); if (eventNotification) { EventControllerFactory.getSingletonController(EventControllerType.ASYNC).post(protocolEvent); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void onEvent(PathChildrenCacheEvent event, InstanceEventType instanceEventType) throws Exception { String childPath = event.getData().getPath(); String applicationJson = childPath.substring(childPath.lastIndexOf("/") + 1); ApplicationEntity applicationEntity = ZookeeperApplicationEntityFactory.fromJson(applicationJson); List<String> applicationJsonList = invoker.getChildNameList(client, path); List<ApplicationEntity> applicationEntityList = ZookeeperApplicationEntityFactory.fromJson(applicationJsonList); InstanceEvent instanceEvent = null; switch (applicationType) { case SERVICE: instanceEvent = new ServiceInstanceEvent(instanceEventType, interfaze, applicationEntity, applicationEntityList); if (executorContainer != null) { ConsistencyExecutor consistencyExecutor = executorContainer.getConsistencyExecutor(); if (consistencyExecutor != null) { consistencyExecutor.consist((ServiceInstanceEvent) instanceEvent); } } break; case REFERENCE: instanceEvent = new ReferenceInstanceEvent(instanceEventType, interfaze, applicationEntity, applicationEntityList); break; } EventControllerFactory.getAsyncController(instanceEvent.toString()).post(instanceEvent); LOG.info("Watched {} {} - interface={}, {}", applicationType.toString(), instanceEventType.toString(), interfaze, applicationEntity.toString()); }
#vulnerable code private void onEvent(PathChildrenCacheEvent event, InstanceEventType instanceEventType) throws Exception { String childPath = event.getData().getPath(); String applicationJson = childPath.substring(childPath.lastIndexOf("/") + 1); ApplicationEntity applicationEntity = ZookeeperApplicationEntityFactory.fromJson(applicationJson); List<String> applicationJsonList = invoker.getChildNameList(client, path); List<ApplicationEntity> applicationEntityList = ZookeeperApplicationEntityFactory.fromJson(applicationJsonList); InstanceEvent instanceEvent = null; switch (applicationType) { case SERVICE: instanceEvent = new ServiceInstanceEvent(instanceEventType, interfaze, applicationEntity, applicationEntityList); if (executorContainer != null) { ConsistencyExecutor consistencyExecutor = executorContainer.getConsistencyExecutor(); if (consistencyExecutor != null) { consistencyExecutor.consist((ServiceInstanceEvent) instanceEvent); } } break; case REFERENCE: instanceEvent = new ReferenceInstanceEvent(instanceEventType, interfaze, applicationEntity, applicationEntityList); break; } EventControllerFactory.getController(instanceEvent.toString(), EventControllerType.ASYNC).post(instanceEvent); LOG.info("Watched {} {} - interface={}, {}", applicationType.toString(), instanceEventType.toString(), interfaze, applicationEntity.toString()); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSourceSinkStartResumeRollingEverySecond() throws Exception { //This is the config that is required to make the VanillaChronicle roll every second final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); assertNotNull(sourceBasePath); assertNotNull(sinkBasePath); final Chronicle source = ChronicleQueueBuilder.source( ChronicleQueueBuilder.vanilla(sourceBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build()) .bindAddress("localhost", BASE_PORT + 104) .build(); ExcerptAppender appender = source.createAppender(); System.out.print("writing 100 items will take take 10 seconds."); for (int i = 0; i < 100; i++) { appender.startExcerpt(); int value = 1000000000 + i; appender.append(value).append(' '); //this space is really important. appender.finish(); Thread.sleep(100); if(i % 10==0) { System.out.print("."); } } appender.close(); System.out.print("\n"); //create a tailer to get the first 50 items then exit the tailer final Chronicle sink1 = ChronicleQueueBuilder.sink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build()) .connectAddress("localhost", BASE_PORT + 104) .build(); final ExcerptTailer tailer1 = sink1.createTailer().toStart(); System.out.println("Sink1 reading first 50 items then stopping"); for( int count=0; count < 50 ;) { if(tailer1.nextIndex()) { assertEquals(1000000000 + count, tailer1.parseLong()); tailer1.finish(); count++; } } tailer1.close(); sink1.close(); //TODO: fix sink1.checkCounts(1, 1); //now resume the tailer to get the first 50 items final Chronicle sink2 = ChronicleQueueBuilder.sink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build()) .connectAddress("localhost", BASE_PORT + 104) .build(); //Take the tailer to the last index (item 50) and start reading from there. final ExcerptTailer tailer2 = sink2.createTailer().toEnd(); assertEquals(1000000000 + 49, tailer2.parseLong()); tailer2.finish(); System.out.println("Sink2 restarting to continue to read the next 50 items"); for(int count=50 ; count < 100 ; ) { if(tailer2.nextIndex()) { assertEquals(1000000000 + count, tailer2.parseLong()); tailer2.finish(); count++; } } tailer2.close(); sink2.close(); //TODO: fix sink2.checkCounts(1, 1); sink2.clear(); source.close(); //TODO: fix source.checkCounts(1, 1); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); }
#vulnerable code @Test public void testSourceSinkStartResumeRollingEverySecond() throws Exception { //This is the config that is required to make the VanillaChronicle roll every second final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); assertNotNull(sourceBasePath); assertNotNull(sinkBasePath); final ChronicleSource source = new ChronicleSource( ChronicleQueueBuilder.vanilla(sourceBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build(), 8888); ExcerptAppender appender = source.createAppender(); System.out.print("writing 100 items will take take 10 seconds."); for (int i = 0; i < 100; i++) { appender.startExcerpt(); int value = 1000000000 + i; appender.append(value).append(' '); //this space is really important. appender.finish(); Thread.sleep(100); if(i % 10==0) { System.out.print("."); } } appender.close(); System.out.print("\n"); //create a tailer to get the first 50 items then exit the tailer final ChronicleSink sink1 = new ChronicleSink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build(), "localhost", 8888); final ExcerptTailer tailer1 = sink1.createTailer().toStart(); System.out.println("Sink1 reading first 50 items then stopping"); for( int count=0; count < 50 ;) { if(tailer1.nextIndex()) { assertEquals(1000000000 + count, tailer1.parseLong()); tailer1.finish(); count++; } } tailer1.close(); sink1.close(); sink1.checkCounts(1, 1); //now resume the tailer to get the first 50 items final ChronicleSink sink2 = new ChronicleSink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build(), "localhost", 8888); //Take the tailer to the last index (item 50) and start reading from there. final ExcerptTailer tailer2 = sink2.createTailer().toEnd(); assertEquals(1000000000 + 49, tailer2.parseLong()); tailer2.finish(); System.out.println("Sink2 restarting to continue to read the next 50 items"); for(int count=50 ; count < 100 ; ) { if(tailer2.nextIndex()) { assertEquals(1000000000 + count, tailer2.parseLong()); tailer2.finish(); count++; } } tailer2.close(); sink2.close(); sink2.checkCounts(1, 1); sink2.clear(); source.close(); source.checkCounts(1, 1); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPricePublishing1() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource) .source() .bindAddress(BASE_PORT + 2) .build(); final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink) .sink() .connectAddress("localhost", BASE_PORT + 2) .build(); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); reader.read(); long start = System.nanoTime(); int prices = 12000000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); }
#vulnerable code @Test public void testPricePublishing1() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 2); final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 2); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); reader.read(); long start = System.nanoTime(); int prices = 12000000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testOverTCP() throws IOException, InterruptedException { String baseDir = System.getProperty("java.io.tmpdir"); String srcBasePath = baseDir + "/IPCT.testOverTCP.source"; ChronicleTools.deleteOnExit(srcBasePath); // NOTE: the sink and source must have different chronicle files. // TODO, make more robust. final int messages = 5 * 1000 * 1000; ChronicleConfig config = ChronicleConfig.DEFAULT.clone(); // config.dataBlockSize(4096); // config.indexBlockSize(4096); final IndexedChronicle underlying = new IndexedChronicle(srcBasePath/*, config*/); final Chronicle source = new InProcessChronicleSource(underlying, PORT + 1); Thread t = new Thread(new Runnable() { @Override public void run() { try { // PosixJNAAffinity.INSTANCE.setAffinity(1 << 1); ExcerptAppender excerpt = source.createAppender(); for (int i = 1; i <= messages; i++) { // use a size which will cause mis-alignment. excerpt.startExcerpt(); excerpt.writeLong(i); excerpt.append(' '); excerpt.append(i); excerpt.append('\n'); excerpt.finish(); } System.out.println(System.currentTimeMillis() + ": Finished writing messages"); } catch (Exception e) { throw new AssertionError(e); } } }); // PosixJNAAffinity.INSTANCE.setAffinity(1 << 2); String snkBasePath = baseDir + "/IPCT.testOverTCP.sink"; ChronicleTools.deleteOnExit(snkBasePath); final IndexedChronicle underlying2 = new IndexedChronicle(snkBasePath/*, config*/); Chronicle sink = new InProcessChronicleSink(underlying2, "localhost", PORT + 1); long start = System.nanoTime(); t.start(); ExcerptTailer excerpt = sink.createTailer(); int count = 0; for (int i = 1; i <= messages; i++) { while (!excerpt.nextIndex()) count++; long n = excerpt.readLong(); String text = excerpt.parseUTF(StopCharTesters.CONTROL_STOP); if (i != n) assertEquals('\'' + text + '\'', i, n); excerpt.finish(); } sink.close(); System.out.println("There were " + count + " isSync messages"); t.join(); source.close(); long time = System.nanoTime() - start; System.out.printf("Messages per second %,d%n", (int) (messages * 1e9 / time)); }
#vulnerable code @Test public void testOverTCP() throws IOException, InterruptedException { String baseDir = System.getProperty("java.io.tmpdir"); String srcBasePath = baseDir + "/IPCT.testOverTCP.source"; ChronicleTools.deleteOnExit(srcBasePath); // NOTE: the sink and source must have different chronicle files. // TODO, make more robust. final int messages = 2 * 1000 * 1000; ChronicleConfig config = ChronicleConfig.DEFAULT.clone(); // config.dataBlockSize(4096); // config.indexBlockSize(4096); final Chronicle source = new InProcessChronicleSource(new IndexedChronicle(srcBasePath, config), PORT + 1); Thread t = new Thread(new Runnable() { @Override public void run() { try { // PosixJNAAffinity.INSTANCE.setAffinity(1 << 1); ExcerptAppender excerpt = source.createAppender(); for (int i = 1; i <= messages; i++) { // use a size which will cause mis-alignment. excerpt.startExcerpt(); excerpt.writeLong(i); excerpt.append(' '); excerpt.append(i); excerpt.append('\n'); excerpt.finish(); } System.out.println(System.currentTimeMillis() + ": Finished writing messages"); } catch (Exception e) { throw new AssertionError(e); } } }); // PosixJNAAffinity.INSTANCE.setAffinity(1 << 2); String snkBasePath = baseDir + "/IPCT.testOverTCP.sink"; ChronicleTools.deleteOnExit(snkBasePath); Chronicle sink = new InProcessChronicleSink(new IndexedChronicle(snkBasePath, config), "localhost", PORT + 1); long start = System.nanoTime(); t.start(); ExcerptTailer excerpt = sink.createTailer(); int count = 0; for (int i = 1; i <= messages; i++) { while (!excerpt.nextIndex()) count++; long n = excerpt.readLong(); String text = excerpt.parseUTF(StopCharTesters.CONTROL_STOP); if (i != n) assertEquals('\'' + text + '\'', i, n); excerpt.finish(); } sink.close(); System.out.println("There were " + count + " isSync messages"); t.join(); source.close(); long time = System.nanoTime() - start; System.out.printf("Messages per second %,d%n", (int) (messages * 1e9 / time)); } #location 38 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String... ignored) throws IOException { String basePath = TMP + "/ExampleCacheMain"; ChronicleTools.deleteOnExit(basePath); CachePerfMain map = new CachePerfMain(basePath, 64); buildkeylist(keys); long duration; for (int i = 0; i < 2; i++) { duration = putTest(keys, "base", map); System.out.printf(i + "th iter: Took %.3f secs to put seq %,d entries%n", duration / 1e9, keys); } for (int i = 0; i < 2; i++) { duration = getTest(keys, map); System.out.printf(i + "th iter: Took %.3f secs to get seq %,d entries%n", duration / 1e9, keys); } shufflelist(); for (int i = 0; i < 2; i++) { System.gc(); duration = getTest(keys, map); System.out.printf(i + "th iter: Took %.3f secs to get random %,d entries%n", duration / 1e9, keys); } for (int i = 0; i < 2; i++) { duration = putTest(keys, "modif", map); System.out .printf(i + "th iter: Took %.3f secs to update random %,d entries%n", duration / 1e9, keys); } }
#vulnerable code public static void main(String... ignored) throws IOException { String basePath = TMP + "/ExampleCacheMain"; ChronicleTools.deleteOnExit(basePath); CachePerfMain map = new CachePerfMain(basePath, 32); long start = System.nanoTime(); buildkeylist(keys); StringBuilder name = new StringBuilder(); StringBuilder surname = new StringBuilder(); Person person = new Person(name, surname, 0); for (int i = 0; i < keys; i++) { name.setLength(0); name.append("name"); name.append(i); surname.setLength(0); surname.append("surname"); surname.append(i); person.set_age(i % 100); map.put(i, person); } long end = System.nanoTime(); System.out.printf("Took %.3f secs to add %,d entries%n", (end - start) / 1e9, keys); long duration; for (int i = 0; i < 2; i++) { duration = randomGet(keys, map); System.out.printf(i + "th iter: Took %.3f secs to get seq %,d entries%n", duration / 1e9, keys); } System.out.println("before shuffle"); shufflelist(); System.out.println("after shuffle"); for (int i = 0; i < 2; i++) { System.gc(); duration = randomGet(keys, map); System.out.printf(i + "th iter: Took %.3f secs to get random %,d entries%n", duration / 1e9, keys); } } #location 27 #vulnerability type CHECKERS_PRINTF_ARGS
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPricePublishing1() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource) .source() .bindAddress(BASE_PORT + 2) .build(); final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink) .sink() .connectAddress("localhost", BASE_PORT + 2) .build(); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); reader.read(); long start = System.nanoTime(); int prices = 12000000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); }
#vulnerable code @Test public void testPricePublishing1() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 2); final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 2); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); reader.read(); long start = System.nanoTime(); int prices = 12000000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shouldBeAbleToDumpReadOnlyQueueFile() throws Exception { if (OS.isWindows()) return; final File dataDir = DirectoryUtils.tempDir(DumpQueueMainTest.class.getSimpleName()); try (final SingleChronicleQueue queue = SingleChronicleQueueBuilder. binary(dataDir). build()) { final ExcerptAppender excerptAppender = queue.acquireAppender(); excerptAppender.writeText("first"); excerptAppender.writeText("last"); final Path queueFile = Files.list(dataDir.toPath()). filter(p -> p.toString().endsWith(SingleChronicleQueue.SUFFIX)). findFirst().orElseThrow(() -> new AssertionError("Could not find queue file in directory " + dataDir)); assertThat(queueFile.toFile().setWritable(false), is(true)); final CountingOutputStream countingOutputStream = new CountingOutputStream(); DumpQueueMain.dump(queueFile.toFile(), new PrintStream(countingOutputStream), Long.MAX_VALUE); assertThat(countingOutputStream.bytes, is(not(0L))); } }
#vulnerable code @Test public void shouldBeAbleToDumpReadOnlyQueueFile() throws Exception { if (OS.isWindows()) return; final File dataDir = DirectoryUtils.tempDir(DumpQueueMainTest.class.getSimpleName()); final SingleChronicleQueue queue = SingleChronicleQueueBuilder. binary(dataDir). build(); final ExcerptAppender excerptAppender = queue.acquireAppender(); excerptAppender.writeText("first"); excerptAppender.writeText("last"); final Path queueFile = Files.list(dataDir.toPath()). filter(p -> p.toString().endsWith(SingleChronicleQueue.SUFFIX)). findFirst().orElseThrow(() -> new AssertionError("Could not find queue file in directory " + dataDir)); assertThat(queueFile.toFile().setWritable(false), is(true)); final CountingOutputStream countingOutputStream = new CountingOutputStream(); DumpQueueMain.dump(queueFile.toFile(), new PrintStream(countingOutputStream), Long.MAX_VALUE); assertThat(countingOutputStream.bytes, is(not(0L))); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shouldDetermineQueueDirectoryFromQueueFile() throws Exception { final Path path = Paths.get(OS.USER_DIR, TEST_QUEUE_FILE); try (final SingleChronicleQueue queue = SingleChronicleQueueBuilder.binary(path) .testBlockSize() .build()) { assertThat(queue.createTailer().readingDocument().isPresent(), is(true)); } }
#vulnerable code @Test public void shouldDetermineQueueDirectoryFromQueueFile() throws Exception { final File queuePath = DirectoryUtils.tempDir(getClass().getSimpleName()); try (final SingleChronicleQueue queue = SingleChronicleQueueBuilder.binary(queuePath) .testBlockSize() .build()) { try (DocumentContext ctx = queue.acquireAppender().writingDocument()) { ctx.wire().write("key").text("value"); } } final Path path = queuePath.listFiles(QUEUE_FILE_FILTER)[0].toPath(); try (final SingleChronicleQueue queue = SingleChronicleQueueBuilder.binary(path) .testBlockSize() .build()) { assertThat(queue.createTailer().readingDocument().isPresent(), is(true)); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static long getCurrentQueueFileLength(final Path dataDir) throws IOException { try (RandomAccessFile file = new RandomAccessFile( Files.list(dataDir).filter(p -> p.toString().endsWith("cq4")).findFirst(). orElseThrow(AssertionError::new).toFile(), "r")) { return file.length(); } }
#vulnerable code private static long getCurrentQueueFileLength(final Path dataDir) throws IOException { return new RandomAccessFile( Files.list(dataDir).filter(p -> p.toString().endsWith("cq4")).findFirst(). orElseThrow(AssertionError::new).toFile(), "r").length(); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public VanillaFile dataForLast(int cycle, int threadId) throws IOException { String cycleStr = dateCache.formatFor(cycle); String cyclePath = basePath + "/" + cycleStr; String dataPrefix = "data-" + threadId + "-"; if (lastCycle != cycle) { int maxCount = 0; File[] files = new File(cyclePath).listFiles(); if (files != null) for (File file : files) { if (file.getName().startsWith(dataPrefix)) { int count = Integer.parseInt(file.getName().substring(dataPrefix.length())); if (maxCount < count) maxCount = count; } } lastCycle = cycle; lastCount = maxCount; } return dataFor(cycle, threadId, lastCount, true); }
#vulnerable code public VanillaFile dataForLast(int cycle, int threadId) throws IOException { String cycleStr = dateCache.formatFor(cycle); String dataPrefix = basePath + "/" + cycleStr + "/data-" + threadId + "-"; if (lastCycle != cycle) { int maxCount = 0; File[] files = new File(dataPrefix).listFiles(); if (files != null) for (File file : files) { if (file.getName().startsWith(dataPrefix)) { int count = Integer.parseInt(file.getName().substring(dataPrefix.length())); if (maxCount < count) maxCount = count; } } lastCycle = cycle; lastCount = maxCount; } return dataFor(cycle, threadId, lastCount, true); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testOverTCP() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); // NOTE: the sink and source must have different chronicle files. // TODO, make more robust. final int messages = 5 * 1000 * 1000; final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource) .source() .bindAddress(BASE_PORT + 1) .build(); final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink) .sink() .connectAddress("localhost", BASE_PORT + 1) .build(); Thread t = new Thread(new Runnable() { @Override public void run() { try { ExcerptAppender excerpt = source.createAppender(); for (int i = 1; i <= messages; i++) { // use a size which will cause mis-alignment. excerpt.startExcerpt(); excerpt.writeLong(i); excerpt.append(' '); excerpt.append(i); excerpt.append('\n'); excerpt.finish(); } System.out.println(System.currentTimeMillis() + ": Finished writing messages"); } catch (Exception e) { throw new AssertionError(e); } } }); long start = System.nanoTime(); t.start(); ExcerptTailer excerpt = sink.createTailer(); int count = 0; for (int i = 1; i <= messages; i++) { while (!excerpt.nextIndex()) { count++; } long n = excerpt.readLong(); String text = excerpt.parseUTF(StopCharTesters.CONTROL_STOP); if (i != n) { assertEquals('\'' + text + '\'', i, n); } excerpt.finish(); } sink.close(); System.out.println("There were " + count + " InSynk messages"); t.join(); source.close(); long time = System.nanoTime() - start; System.out.printf("Messages per second %,d%n", (int) (messages * 1e9 / time)); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); }
#vulnerable code @Test public void testOverTCP() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); // NOTE: the sink and source must have different chronicle files. // TODO, make more robust. final int messages = 5 * 1000 * 1000; final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 1); final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 1); Thread t = new Thread(new Runnable() { @Override public void run() { try { ExcerptAppender excerpt = source.createAppender(); for (int i = 1; i <= messages; i++) { // use a size which will cause mis-alignment. excerpt.startExcerpt(); excerpt.writeLong(i); excerpt.append(' '); excerpt.append(i); excerpt.append('\n'); excerpt.finish(); } System.out.println(System.currentTimeMillis() + ": Finished writing messages"); } catch (Exception e) { throw new AssertionError(e); } } }); long start = System.nanoTime(); t.start(); ExcerptTailer excerpt = sink.createTailer(); int count = 0; for (int i = 1; i <= messages; i++) { while (!excerpt.nextIndex()) { count++; } long n = excerpt.readLong(); String text = excerpt.parseUTF(StopCharTesters.CONTROL_STOP); if (i != n) { assertEquals('\'' + text + '\'', i, n); } excerpt.finish(); } sink.close(); System.out.println("There were " + count + " InSynk messages"); t.join(); source.close(); long time = System.nanoTime() - start; System.out.printf("Messages per second %,d%n", (int) (messages * 1e9 / time)); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); } #location 26 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPersistedLocalVanillaSink_001() throws Exception { final int port = BASE_PORT + 301; final String basePath = getVanillaTestPath(); final Chronicle chronicle = ChronicleQueueBuilder.vanilla(basePath).build(); final Chronicle source = ChronicleQueueBuilder.source(chronicle) .bindAddress("localhost", port) .build(); final Chronicle sink = ChronicleQueueBuilder.sink(chronicle) .sharedChronicle(true) .connectAddress("localhost",port) .build(); final CountDownLatch latch = new CountDownLatch(5); final Random random = new Random(); final int items = 100; try { Thread appenderThread = new Thread() { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (long i = 1; i <= items; i++) { if (latch.getCount() > 0) { latch.countDown(); } appender.startExcerpt(8); appender.writeLong(i); appender.finish(); sleep(10 + random.nextInt(80)); appender.close(); } } catch (Exception e) { e.printStackTrace(); } } }; appenderThread.start(); latch.await(); final ExcerptTailer tailer1 = sink.createTailer().toStart(); for (long i = 1; i <= items; i++) { assertTrue(tailer1.nextIndex()); assertEquals(i, tailer1.readLong()); tailer1.finish(); } tailer1.close(); appenderThread.join(); sink.close(); sink.clear(); } finally { source.close(); source.clear(); } }
#vulnerable code @Test public void testPersistedLocalVanillaSink_001() throws Exception { final int port = BASE_PORT + 301; final String basePath = getVanillaTestPath(); final Chronicle chronicle = ChronicleQueueBuilder.vanilla(basePath).build(); final ChronicleSource source = new ChronicleSource(chronicle, port); final Chronicle sink = localChronicleSink(chronicle, "localhost", port); final CountDownLatch latch = new CountDownLatch(5); final Random random = new Random(); final int items = 100; try { Thread appenderThread = new Thread() { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (long i = 1; i <= items; i++) { if (latch.getCount() > 0) { latch.countDown(); } appender.startExcerpt(8); appender.writeLong(i); appender.finish(); sleep(10 + random.nextInt(80)); appender.close(); } } catch (Exception e) { e.printStackTrace(); } } }; appenderThread.start(); latch.await(); final ExcerptTailer tailer1 = sink.createTailer().toStart(); for (long i = 1; i <= items; i++) { assertTrue(tailer1.nextIndex()); assertEquals(i, tailer1.readLong()); tailer1.finish(); } tailer1.close(); appenderThread.join(); sink.close(); sink.clear(); } finally { source.close(); source.clear(); } } #location 55 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void init() { tableStore.doWithExclusiveLock(ts -> { maxCycleValue = ts.acquireValueFor(HIGHEST_CREATED_CYCLE); minCycleValue = ts.acquireValueFor(LOWEST_CREATED_CYCLE); lock = ts.acquireValueFor(LOCK); modCount = ts.acquireValueFor(MOD_COUNT); if (lock.getVolatileValue() == Long.MIN_VALUE) { lock.compareAndSwapValue(Long.MIN_VALUE, 0); } if (modCount.getVolatileValue() == Long.MIN_VALUE) { modCount.compareAndSwapValue(Long.MIN_VALUE, 0); } return this; }); }
#vulnerable code @Override public void init() { final long timeoutAt = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(20L); boolean warnedOnFailure = false; while (System.currentTimeMillis() < timeoutAt) { try (final FileChannel channel = FileChannel.open(tableStore.file().toPath(), StandardOpenOption.WRITE); final FileLock fileLock = channel.tryLock()) { maxCycleValue = tableStore.acquireValueFor(HIGHEST_CREATED_CYCLE); minCycleValue = tableStore.acquireValueFor(LOWEST_CREATED_CYCLE); lock = tableStore.acquireValueFor(LOCK); modCount = tableStore.acquireValueFor(MOD_COUNT); if (lock.getVolatileValue() == Long.MIN_VALUE) { lock.compareAndSwapValue(Long.MIN_VALUE, 0); } if (modCount.getVolatileValue() == Long.MIN_VALUE) { modCount.compareAndSwapValue(Long.MIN_VALUE, 0); } return; } catch (IOException | RuntimeException e) { // failed to acquire the lock, wait until other operation completes if (!warnedOnFailure) { LOGGER.warn("Failed to acquire a lock on the directory-listing file: {}:{}. Retrying.", e.getClass().getSimpleName(), e.getMessage()); warnedOnFailure = true; } Jvm.pause(50L); } } throw new IllegalStateException("Unable to claim exclusive lock on file " + tableStore.file()); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPricePublishing2() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource) .source() .bindAddress(BASE_PORT + 3) .build(); final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink) .sink() .connectAddress("localhost", BASE_PORT + 3) .build(); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); assertEquals(-1, reader.excerpt.index()); reader.read(); assertEquals(0, reader.excerpt.index()); long start = System.nanoTime(); int prices = 2 * 1000 * 1000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read using Excerpt%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); }
#vulnerable code @Test public void testPricePublishing2() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 3); final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 3); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); assertEquals(-1, reader.excerpt.index()); reader.read(); assertEquals(0, reader.excerpt.index()); long start = System.nanoTime(); int prices = 2 * 1000 * 1000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read using Excerpt%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void writeBytesInternal(final long index, @NotNull final BytesStore bytes, boolean metadata) { final int cycle = queue.rollCycle().toCycle(index); if (wire == null) setCycle2(cycle, true); else if (queue.rollCycle().toCycle(wire.headerNumber()) != cycle) rollCycleTo(cycle); long headerNumber = wire.headerNumber(); boolean isNextIndex = index == headerNumber + 1; if (!isNextIndex) { // in case our cached headerNumber is incorrect. if (resetPosition()) { headerNumber = wire.headerNumber(); /// if the header number has changed then we will have roll if (queue.rollCycle().toCycle(headerNumber) != cycle) { rollCycleTo(cycle); headerNumber = wire.headerNumber(); } } isNextIndex = index == headerNumber + 1; if (!isNextIndex) { if (index > headerNumber + 1) throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " beyond the end of the queue, current: " + Long.toHexString(headerNumber)); Jvm.warn().on(getClass(), "Trying to overwrite index " + Long.toHexString(index) + " which is before the end of the queue"); return; } } writeBytesInternal(bytes, metadata); }
#vulnerable code protected void writeBytesInternal(final long index, @NotNull final BytesStore bytes, boolean metadata) { final int cycle = queue.rollCycle().toCycle(index); long headerNumber = wire.headerNumber(); if (wire == null) { setCycle2(cycle, true); headerNumber = wire.headerNumber(); } else if (queue.rollCycle().toCycle(headerNumber) != cycle) { rollCycleTo(cycle); headerNumber = wire.headerNumber(); } boolean isNextIndex = index == headerNumber + 1; if (!isNextIndex) { // in case our cached headerNumber is incorrect. if (resetPosition()) { headerNumber = wire.headerNumber(); /// if the header number has changed then we will have roll if (queue.rollCycle().toCycle(headerNumber) != cycle) { rollCycleTo(cycle); headerNumber = wire.headerNumber(); } } isNextIndex = index == headerNumber + 1; if (!isNextIndex) { if (index > headerNumber + 1) throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " beyond the end of the queue, current: " + Long.toHexString(headerNumber)); Jvm.warn().on(getClass(), "Trying to overwrite index " + Long.toHexString(index) + " which is before the end of the queue"); return; } } writeBytesInternal(bytes, metadata); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSimpledSingleThreadedWriteRead() throws Exception { try (DirectStore allocate = DirectStore.allocate(150)) { final BytesRingBuffer bytesRingBuffer = new BytesRingBuffer(allocate.bytes()); bytesRingBuffer.offer(output.clear()); Bytes actual = bytesRingBuffer.take(maxSize -> input.clear()); assertEquals(EXPECTED, actual.readUTF()); } }
#vulnerable code @Test public void testSimpledSingleThreadedWriteRead() throws Exception { try (DirectStore allocate = DirectStore.allocate(150)) { final BytesQueue bytesRingBuffer = new BytesQueue(allocate.bytes()); bytesRingBuffer.offer(output.clear()); Bytes poll = bytesRingBuffer.poll(input.clear()); assertEquals(EXPECTED, poll.readUTF()); } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSourceSinkStartResumeRollingEverySecond() throws Exception { //This is the config that is required to make the VanillaChronicle roll every second final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); assertNotNull(sourceBasePath); assertNotNull(sinkBasePath); final Chronicle source = ChronicleQueueBuilder.source( ChronicleQueueBuilder.vanilla(sourceBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build()) .bindAddress("localhost", BASE_PORT + 104) .build(); ExcerptAppender appender = source.createAppender(); System.out.print("writing 100 items will take take 10 seconds."); for (int i = 0; i < 100; i++) { appender.startExcerpt(); int value = 1000000000 + i; appender.append(value).append(' '); //this space is really important. appender.finish(); Thread.sleep(100); if(i % 10==0) { System.out.print("."); } } appender.close(); System.out.print("\n"); //create a tailer to get the first 50 items then exit the tailer final Chronicle sink1 = ChronicleQueueBuilder.sink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build()) .connectAddress("localhost", BASE_PORT + 104) .build(); final ExcerptTailer tailer1 = sink1.createTailer().toStart(); System.out.println("Sink1 reading first 50 items then stopping"); for( int count=0; count < 50 ;) { if(tailer1.nextIndex()) { assertEquals(1000000000 + count, tailer1.parseLong()); tailer1.finish(); count++; } } tailer1.close(); sink1.close(); //TODO: fix sink1.checkCounts(1, 1); //now resume the tailer to get the first 50 items final Chronicle sink2 = ChronicleQueueBuilder.sink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build()) .connectAddress("localhost", BASE_PORT + 104) .build(); //Take the tailer to the last index (item 50) and start reading from there. final ExcerptTailer tailer2 = sink2.createTailer().toEnd(); assertEquals(1000000000 + 49, tailer2.parseLong()); tailer2.finish(); System.out.println("Sink2 restarting to continue to read the next 50 items"); for(int count=50 ; count < 100 ; ) { if(tailer2.nextIndex()) { assertEquals(1000000000 + count, tailer2.parseLong()); tailer2.finish(); count++; } } tailer2.close(); sink2.close(); //TODO: fix sink2.checkCounts(1, 1); sink2.clear(); source.close(); //TODO: fix source.checkCounts(1, 1); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); }
#vulnerable code @Test public void testSourceSinkStartResumeRollingEverySecond() throws Exception { //This is the config that is required to make the VanillaChronicle roll every second final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); assertNotNull(sourceBasePath); assertNotNull(sinkBasePath); final ChronicleSource source = new ChronicleSource( ChronicleQueueBuilder.vanilla(sourceBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build(), 8888); ExcerptAppender appender = source.createAppender(); System.out.print("writing 100 items will take take 10 seconds."); for (int i = 0; i < 100; i++) { appender.startExcerpt(); int value = 1000000000 + i; appender.append(value).append(' '); //this space is really important. appender.finish(); Thread.sleep(100); if(i % 10==0) { System.out.print("."); } } appender.close(); System.out.print("\n"); //create a tailer to get the first 50 items then exit the tailer final ChronicleSink sink1 = new ChronicleSink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build(), "localhost", 8888); final ExcerptTailer tailer1 = sink1.createTailer().toStart(); System.out.println("Sink1 reading first 50 items then stopping"); for( int count=0; count < 50 ;) { if(tailer1.nextIndex()) { assertEquals(1000000000 + count, tailer1.parseLong()); tailer1.finish(); count++; } } tailer1.close(); sink1.close(); sink1.checkCounts(1, 1); //now resume the tailer to get the first 50 items final ChronicleSink sink2 = new ChronicleSink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build(), "localhost", 8888); //Take the tailer to the last index (item 50) and start reading from there. final ExcerptTailer tailer2 = sink2.createTailer().toEnd(); assertEquals(1000000000 + 49, tailer2.parseLong()); tailer2.finish(); System.out.println("Sink2 restarting to continue to read the next 50 items"); for(int count=50 ; count < 100 ; ) { if(tailer2.nextIndex()) { assertEquals(1000000000 + count, tailer2.parseLong()); tailer2.finish(); count++; } } tailer2.close(); sink2.close(); sink2.checkCounts(1, 1); sink2.clear(); source.close(); source.checkCounts(1, 1); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPricePublishing3() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource) .source() .bindAddress(BASE_PORT + 4) .build(); final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink) .sink() .connectAddress("localhost", BASE_PORT + 4) .build(); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); assertEquals(-1, reader.excerpt.index()); reader.read(); assertEquals(0, reader.excerpt.index()); long start = System.nanoTime(); int prices = 2 * 1000 * 1000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) reader.read(); long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); }
#vulnerable code @Test public void testPricePublishing3() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 4); final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 4); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); assertEquals(-1, reader.excerpt.index()); reader.read(); assertEquals(0, reader.excerpt.index()); long start = System.nanoTime(); int prices = 2 * 1000 * 1000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) reader.read(); long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReplication1() throws Exception { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final ChronicleSource source = new ChronicleSource( new VanillaChronicle(sourceBasePath), 0); final ChronicleSink sink = new ChronicleSink( new VanillaChronicle(sinkBasePath), "localhost", source.getLocalPort()); try { final Thread at = new Thread("th-appender") { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (int i = 0; i < RUNS; i++) { appender.startExcerpt(); long value = 1000000000 + i; appender.append(value).append(' '); appender.finish(); } appender.close(); } catch(Exception e) { } } }; final Thread tt = new Thread("th-tailer") { public void run() { try { final ExcerptTailer tailer = sink.createTailer(); for (int i = 0; i < RUNS; i++) { long value = 1000000000 + i; assertTrue(tailer.nextIndex()); long val = tailer.parseLong(); assertEquals("i: " + i, value, val); assertEquals("i: " + i, 0, tailer.remaining()); tailer.finish(); } tailer.close(); } catch(Exception e) { } } }; at.start(); tt.start(); at.join(); tt.join(); } finally { sink.close(); sink.clear(); source.close(); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } }
#vulnerable code @Test public void testReplication1() throws IOException { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final ChronicleSource source = new ChronicleSource(new VanillaChronicle(sourceBasePath), 0); final ChronicleSink sink = new ChronicleSink(new VanillaChronicle(sinkBasePath), "localhost", source.getLocalPort()); try { final ExcerptAppender appender = source.createAppender(); final ExcerptTailer tailer = sink.createTailer(); for (int i = 0; i < RUNS; i++) { appender.startExcerpt(); long value = 1000000000 + i; appender.append(value).append(' '); appender.finish(); while(!tailer.nextIndex()); long val = tailer.parseLong(); //System.out.println("" + val); assertEquals("i: " + i, value, val); assertEquals("i: " + i, 0, tailer.remaining()); tailer.finish(); } appender.close(); tailer.close(); } finally { sink.close(); sink.checkCounts(1, 1); sink.clear(); source.close(); source.checkCounts(1, 1); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } } #location 38 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlowAroundSingleThreadedWriteDiffrentSizeBuffers() throws Exception { for (int j = 23 + 34; j < 100; j++) { try (DirectStore allocate = DirectStore.allocate(j)) { final BytesRingBuffer bytesRingBuffer = new BytesRingBuffer(allocate.bytes()); for (int i = 0; i < 50; i++) { bytesRingBuffer.offer(output.clear()); assertEquals(EXPECTED, bytesRingBuffer.take(maxSize -> input.clear()).readUTF()); } } } }
#vulnerable code @Test public void testFlowAroundSingleThreadedWriteDiffrentSizeBuffers() throws Exception { for (int j = 23 + 34; j < 100; j++) { try (DirectStore allocate = DirectStore.allocate(j)) { final BytesQueue bytesRingBuffer = new BytesQueue(allocate.bytes()); for (int i = 0; i < 50; i++) { bytesRingBuffer.offer(output.clear()); assertEquals(EXPECTED, bytesRingBuffer.poll(input.clear()).readUTF()); } } } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReplication1() throws Exception { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final Chronicle source = ChronicleQueueBuilder.vanilla(sourceBasePath) .source() .bindAddress("localhost", BASE_PORT + 101) .build(); final Chronicle sink = ChronicleQueueBuilder.vanilla(sinkBasePath) .sink() .connectAddress("localhost", BASE_PORT + 101) .build(); try { final Thread at = new Thread("th-appender") { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (int i = 0; i < RUNS; i++) { appender.startExcerpt(); long value = 1000000000 + i; appender.append(value).append(' '); appender.finish(); } appender.close(); } catch(Exception e) { } } }; final Thread tt = new Thread("th-tailer") { public void run() { try { final ExcerptTailer tailer = sink.createTailer(); for (int i = 0; i < RUNS; i++) { long value = 1000000000 + i; assertTrue(tailer.nextIndex()); long val = tailer.parseLong(); assertEquals("i: " + i, value, val); assertEquals("i: " + i, 0, tailer.remaining()); tailer.finish(); } tailer.close(); } catch(Exception e) { } } }; at.start(); tt.start(); at.join(); tt.join(); } finally { sink.close(); sink.clear(); source.close(); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } }
#vulnerable code @Test public void testReplication1() throws Exception { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final ChronicleSource source = new ChronicleSource( ChronicleQueueBuilder.vanilla(sourceBasePath).build(), 0); final ChronicleSink sink = new ChronicleSink( ChronicleQueueBuilder.vanilla(sinkBasePath).build(), "localhost", source.getLocalPort()); try { final Thread at = new Thread("th-appender") { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (int i = 0; i < RUNS; i++) { appender.startExcerpt(); long value = 1000000000 + i; appender.append(value).append(' '); appender.finish(); } appender.close(); } catch(Exception e) { } } }; final Thread tt = new Thread("th-tailer") { public void run() { try { final ExcerptTailer tailer = sink.createTailer(); for (int i = 0; i < RUNS; i++) { long value = 1000000000 + i; assertTrue(tailer.nextIndex()); long val = tailer.parseLong(); assertEquals("i: " + i, value, val); assertEquals("i: " + i, 0, tailer.remaining()); tailer.finish(); } tailer.close(); } catch(Exception e) { } } }; at.start(); tt.start(); at.join(); tt.join(); } finally { sink.close(); sink.clear(); source.close(); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } } #location 62 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPricePublishing2() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource) .source() .bindAddress(BASE_PORT + 3) .build(); final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink) .sink() .connectAddress("localhost", BASE_PORT + 3) .build(); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); assertEquals(-1, reader.excerpt.index()); reader.read(); assertEquals(0, reader.excerpt.index()); long start = System.nanoTime(); int prices = 2 * 1000 * 1000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read using Excerpt%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); }
#vulnerable code @Test public void testPricePublishing2() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 3); final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 3); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); assertEquals(-1, reader.excerpt.index()); reader.read(); assertEquals(0, reader.excerpt.index()); long start = System.nanoTime(); int prices = 2 * 1000 * 1000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read using Excerpt%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @NotNull private WireStore acquireStore(final long cycle, final long epoch) { @NotNull final RollCycle rollCycle = builder.rollCycle(); @NotNull final String cycleFormat = this.dateCache.formatFor(cycle); @NotNull final File cycleFile = new File(this.builder.path(), cycleFormat + SUFFIX); try { final File parentFile = cycleFile.getParentFile(); if (parentFile != null && !parentFile.exists()) { parentFile.mkdirs(); } final WireType wireType = builder.wireType(); final MappedBytes mappedBytes = mappedBytes(builder, cycleFile); //noinspection PointlessBitwiseExpression if (mappedBytes.compareAndSwapInt(0, Wires.NOT_INITIALIZED, Wires.META_DATA | Wires.NOT_READY | Wires.UNKNOWN_LENGTH)) { final SingleChronicleQueueStore wireStore = new SingleChronicleQueueStore(rollCycle, wireType, mappedBytes, epoch); final Bytes<?> bytes = mappedBytes.bytesForWrite().writePosition(4); wireType.apply(bytes).getValueOut().typedMarshallable(wireStore); final long length = bytes.writePosition(); wireStore.install( length, true, cycle, builder ); mappedBytes.writeOrderedInt(0L, Wires.META_DATA | Wires.toIntU30(bytes.writePosition() - 4, "Delegate too large")); return wireStore; } else { long end = System.currentTimeMillis() + TIMEOUT; while ((mappedBytes.readVolatileInt(0) & Wires.NOT_READY) == Wires.NOT_READY) { if (System.currentTimeMillis() > end) { throw new IllegalStateException("Timed out waiting for the header record to be ready in " + cycleFile); } Jvm.pause(1); } mappedBytes.readPosition(0); mappedBytes.writePosition(mappedBytes.capacity()); final int len = Wires.lengthOf(mappedBytes.readVolatileInt()); final long length = mappedBytes.readPosition() + len; mappedBytes.readLimit(length); //noinspection unchecked final WireStore wireStore = wireType.apply(mappedBytes).getValueIn().typedMarshallable(); wireStore.install(length, false, cycle, builder); return wireStore; } } catch (FileNotFoundException e) { throw Jvm.rethrow(e); } }
#vulnerable code @NotNull private WireStore acquireStore(final long cycle, final long epoch) { @NotNull final RollCycle rollCycle = builder.rollCycle(); @NotNull final String cycleFormat = this.dateCache.formatFor(cycle); @NotNull final File cycleFile = new File(this.builder.path(), cycleFormat + SUFFIX); try { final File parentFile = cycleFile.getParentFile(); if (parentFile != null && !parentFile.exists()) { parentFile.mkdirs(); } final WireType wireType = builder.wireType(); final MappedBytes mappedBytes = mappedBytes(builder, cycleFile); //noinspection PointlessBitwiseExpression if (mappedBytes.compareAndSwapInt(0, Wires.NOT_INITIALIZED, Wires.META_DATA | Wires.NOT_READY | Wires.UNKNOWN_LENGTH)) { final SingleChronicleQueueStore wireStore = new SingleChronicleQueueStore(rollCycle, wireType, mappedBytes, epoch); final Bytes<?> bytes = mappedBytes.bytesForWrite().writePosition(4); wireType.apply(bytes).getValueOut().typedMarshallable(wireStore); final long length = bytes.writePosition(); final WiredBytes<WireStore> wiredBytes = new WiredBytes<>(wireType, mappedBytes, wireStore, length, true); wiredBytes.delegate().install( wiredBytes.headerLength(), wiredBytes.headerCreated(), cycle, builder ); mappedBytes.writeOrderedInt(0L, Wires.META_DATA | Wires.toIntU30(bytes.writePosition() - 4, "Delegate too large")); return wiredBytes.delegate(); } else { long end = System.currentTimeMillis() + TIMEOUT; while ((mappedBytes.readVolatileInt(0) & Wires.NOT_READY) == Wires.NOT_READY) { if (System.currentTimeMillis() > end) { throw new IllegalStateException("Timed out waiting for the header record to be ready in " + cycleFile); } Jvm.pause(1); } mappedBytes.readPosition(0); mappedBytes.writePosition(mappedBytes.capacity()); final int len = Wires.lengthOf(mappedBytes.readVolatileInt()); final long length = mappedBytes.readPosition() + len; mappedBytes.readLimit(length); //noinspection unchecked final WireStore wireStore = wireType.apply(mappedBytes).getValueIn().typedMarshallable(); final WiredBytes<WireStore> wiredBytes = new WiredBytes<>(wireType, mappedBytes, wireStore, length, false); wiredBytes.delegate().install( wiredBytes.headerLength(), wiredBytes.headerCreated(), cycle, builder); return wiredBytes.delegate(); } } catch (FileNotFoundException e) { throw Jvm.rethrow(e); } } #location 37 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPersistedLocalIndexedSink_001() throws Exception { final int port = BASE_PORT + 201; final String basePath = getIndexedTestPath(); final Chronicle chronicle = ChronicleQueueBuilder.indexed(basePath).build(); final Chronicle source = ChronicleQueueBuilder.source(chronicle) .bindAddress("localhost", port) .build(); final Chronicle sink = ChronicleQueueBuilder.sink(chronicle) .sharedChronicle(true) .connectAddress("localhost", port) .build(); final CountDownLatch latch = new CountDownLatch(5); final Random random = new Random(); final int items = 100; try { Thread appenderThread = new Thread() { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (long i = 1; i <= items; i++) { if (latch.getCount() > 0) { latch.countDown(); } appender.startExcerpt(8); appender.writeLong(i); appender.finish(); sleep(10 + random.nextInt(80)); } appender.close(); } catch (Exception e) { } } }; appenderThread.start(); latch.await(); final ExcerptTailer tailer1 = sink.createTailer().toStart(); for (long i = 1; i <= items; i++) { assertTrue(tailer1.nextIndex()); assertEquals(i - 1, tailer1.index()); assertEquals(i, tailer1.readLong()); tailer1.finish(); } tailer1.close(); appenderThread.join(); sink.close(); sink.clear(); } finally { source.close(); source.clear(); } }
#vulnerable code @Test public void testPersistedLocalIndexedSink_001() throws Exception { final int port = BASE_PORT + 201; final String basePath = getIndexedTestPath(); final Chronicle chronicle = ChronicleQueueBuilder.indexed(basePath).build(); final ChronicleSource source = new ChronicleSource(chronicle, port); final Chronicle sink = localChronicleSink(chronicle, "localhost", port); final CountDownLatch latch = new CountDownLatch(5); final Random random = new Random(); final int items = 100; try { Thread appenderThread = new Thread() { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (long i = 1; i <= items; i++) { if (latch.getCount() > 0) { latch.countDown(); } appender.startExcerpt(8); appender.writeLong(i); appender.finish(); sleep(10 + random.nextInt(80)); } appender.close(); } catch (Exception e) { } } }; appenderThread.start(); latch.await(); final ExcerptTailer tailer1 = sink.createTailer().toStart(); for (long i = 1; i <= items; i++) { assertTrue(tailer1.nextIndex()); assertEquals(i - 1, tailer1.index()); assertEquals(i, tailer1.readLong()); tailer1.finish(); } tailer1.close(); appenderThread.join(); sink.close(); sink.clear(); } finally { source.close(); source.clear(); } } #location 55 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testOverTCP() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); // NOTE: the sink and source must have different chronicle files. // TODO, make more robust. final int messages = 5 * 1000 * 1000; final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource) .source() .bindAddress(BASE_PORT + 1) .build(); final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink) .sink() .connectAddress("localhost", BASE_PORT + 1) .build(); Thread t = new Thread(new Runnable() { @Override public void run() { try { ExcerptAppender excerpt = source.createAppender(); for (int i = 1; i <= messages; i++) { // use a size which will cause mis-alignment. excerpt.startExcerpt(); excerpt.writeLong(i); excerpt.append(' '); excerpt.append(i); excerpt.append('\n'); excerpt.finish(); } System.out.println(System.currentTimeMillis() + ": Finished writing messages"); } catch (Exception e) { throw new AssertionError(e); } } }); long start = System.nanoTime(); t.start(); ExcerptTailer excerpt = sink.createTailer(); int count = 0; for (int i = 1; i <= messages; i++) { while (!excerpt.nextIndex()) { count++; } long n = excerpt.readLong(); String text = excerpt.parseUTF(StopCharTesters.CONTROL_STOP); if (i != n) { assertEquals('\'' + text + '\'', i, n); } excerpt.finish(); } sink.close(); System.out.println("There were " + count + " InSynk messages"); t.join(); source.close(); long time = System.nanoTime() - start; System.out.printf("Messages per second %,d%n", (int) (messages * 1e9 / time)); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); }
#vulnerable code @Test public void testOverTCP() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); // NOTE: the sink and source must have different chronicle files. // TODO, make more robust. final int messages = 5 * 1000 * 1000; final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 1); final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 1); Thread t = new Thread(new Runnable() { @Override public void run() { try { ExcerptAppender excerpt = source.createAppender(); for (int i = 1; i <= messages; i++) { // use a size which will cause mis-alignment. excerpt.startExcerpt(); excerpt.writeLong(i); excerpt.append(' '); excerpt.append(i); excerpt.append('\n'); excerpt.finish(); } System.out.println(System.currentTimeMillis() + ": Finished writing messages"); } catch (Exception e) { throw new AssertionError(e); } } }); long start = System.nanoTime(); t.start(); ExcerptTailer excerpt = sink.createTailer(); int count = 0; for (int i = 1; i <= messages; i++) { while (!excerpt.nextIndex()) { count++; } long n = excerpt.readLong(); String text = excerpt.parseUTF(StopCharTesters.CONTROL_STOP); if (i != n) { assertEquals('\'' + text + '\'', i, n); } excerpt.finish(); } sink.close(); System.out.println("There were " + count + " InSynk messages"); t.join(); source.close(); long time = System.nanoTime() - start; System.out.printf("Messages per second %,d%n", (int) (messages * 1e9 / time)); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); } #location 26 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @NotNull private WireStore acquireStore(final long cycle, final long epoch) { @NotNull final RollCycle rollCycle = builder.rollCycle(); @NotNull final String cycleFormat = this.dateCache.formatFor(cycle); @NotNull final File cycleFile = new File(this.builder.path(), cycleFormat + SUFFIX); try { final File parentFile = cycleFile.getParentFile(); if (parentFile != null && !parentFile.exists()) { parentFile.mkdirs(); } final WireType wireType = builder.wireType(); final MappedBytes mappedBytes = mappedBytes(builder, cycleFile); //noinspection PointlessBitwiseExpression if (mappedBytes.compareAndSwapInt(0, Wires.NOT_INITIALIZED, Wires.META_DATA | Wires.NOT_READY | Wires.UNKNOWN_LENGTH)) { final SingleChronicleQueueStore wireStore = new SingleChronicleQueueStore(rollCycle, wireType, mappedBytes, epoch); final Bytes<?> bytes = mappedBytes.bytesForWrite().writePosition(4); wireType.apply(bytes).getValueOut().typedMarshallable(wireStore); final long length = bytes.writePosition(); wireStore.install( length, true, cycle, builder ); mappedBytes.writeOrderedInt(0L, Wires.META_DATA | Wires.toIntU30(bytes.writePosition() - 4, "Delegate too large")); return wireStore; } else { long end = System.currentTimeMillis() + TIMEOUT; while ((mappedBytes.readVolatileInt(0) & Wires.NOT_READY) == Wires.NOT_READY) { if (System.currentTimeMillis() > end) { throw new IllegalStateException("Timed out waiting for the header record to be ready in " + cycleFile); } Jvm.pause(1); } mappedBytes.readPosition(0); mappedBytes.writePosition(mappedBytes.capacity()); final int len = Wires.lengthOf(mappedBytes.readVolatileInt()); final long length = mappedBytes.readPosition() + len; mappedBytes.readLimit(length); //noinspection unchecked final WireStore wireStore = wireType.apply(mappedBytes).getValueIn().typedMarshallable(); wireStore.install(length, false, cycle, builder); return wireStore; } } catch (FileNotFoundException e) { throw Jvm.rethrow(e); } }
#vulnerable code @NotNull private WireStore acquireStore(final long cycle, final long epoch) { @NotNull final RollCycle rollCycle = builder.rollCycle(); @NotNull final String cycleFormat = this.dateCache.formatFor(cycle); @NotNull final File cycleFile = new File(this.builder.path(), cycleFormat + SUFFIX); try { final File parentFile = cycleFile.getParentFile(); if (parentFile != null && !parentFile.exists()) { parentFile.mkdirs(); } final WireType wireType = builder.wireType(); final MappedBytes mappedBytes = mappedBytes(builder, cycleFile); //noinspection PointlessBitwiseExpression if (mappedBytes.compareAndSwapInt(0, Wires.NOT_INITIALIZED, Wires.META_DATA | Wires.NOT_READY | Wires.UNKNOWN_LENGTH)) { final SingleChronicleQueueStore wireStore = new SingleChronicleQueueStore(rollCycle, wireType, mappedBytes, epoch); final Bytes<?> bytes = mappedBytes.bytesForWrite().writePosition(4); wireType.apply(bytes).getValueOut().typedMarshallable(wireStore); final long length = bytes.writePosition(); final WiredBytes<WireStore> wiredBytes = new WiredBytes<>(wireType, mappedBytes, wireStore, length, true); wiredBytes.delegate().install( wiredBytes.headerLength(), wiredBytes.headerCreated(), cycle, builder ); mappedBytes.writeOrderedInt(0L, Wires.META_DATA | Wires.toIntU30(bytes.writePosition() - 4, "Delegate too large")); return wiredBytes.delegate(); } else { long end = System.currentTimeMillis() + TIMEOUT; while ((mappedBytes.readVolatileInt(0) & Wires.NOT_READY) == Wires.NOT_READY) { if (System.currentTimeMillis() > end) { throw new IllegalStateException("Timed out waiting for the header record to be ready in " + cycleFile); } Jvm.pause(1); } mappedBytes.readPosition(0); mappedBytes.writePosition(mappedBytes.capacity()); final int len = Wires.lengthOf(mappedBytes.readVolatileInt()); final long length = mappedBytes.readPosition() + len; mappedBytes.readLimit(length); //noinspection unchecked final WireStore wireStore = wireType.apply(mappedBytes).getValueIn().typedMarshallable(); final WiredBytes<WireStore> wiredBytes = new WiredBytes<>(wireType, mappedBytes, wireStore, length, false); wiredBytes.delegate().install( wiredBytes.headerLength(), wiredBytes.headerCreated(), cycle, builder); return wiredBytes.delegate(); } } catch (FileNotFoundException e) { throw Jvm.rethrow(e); } } #location 37 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWriteAndRead() throws Exception { try (DirectStore allocate = DirectStore.allocate(150)) { final BytesRingBuffer bytesRingBuffer = new BytesRingBuffer(allocate.bytes()); bytesRingBuffer.offer(output.clear()); Bytes actual = bytesRingBuffer.take(maxSize -> input.clear()); assertEquals(EXPECTED, actual.readUTF()); } }
#vulnerable code @Test public void testWriteAndRead() throws Exception { try (DirectStore allocate = DirectStore.allocate(150)) { final BytesQueue bytesRingBuffer = new BytesQueue(allocate.bytes()); bytesRingBuffer.offer(output.clear()); Bytes poll = bytesRingBuffer.poll(input.clear()); assertEquals(EXPECTED, poll.readUTF()); } } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long exceptsPerCycle(int cycle) { StoreTailer tailer = acquireTailer(); try { long index = rollCycle.toIndex(cycle, 0); if (tailer.moveToIndex(index)) { assert tailer.store != null && tailer.store.refCount() > 0; return tailer.store.lastSequenceNumber(tailer) + 1; } else { return -1; } } catch (StreamCorruptedException e) { throw new IllegalStateException(e); } finally { tailer.release(); } }
#vulnerable code public long exceptsPerCycle(int cycle) { StoreTailer tailer = acquireTailer(); try { long index = rollCycle.toIndex(cycle, 0); if (tailer.moveToIndex(index)) { assert tailer.store.refCount() > 0; return tailer.store.lastSequenceNumber(tailer) + 1; } else { return -1; } } catch (StreamCorruptedException e) { throw new IllegalStateException(e); } finally { tailer.release(); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReplication1() throws Exception { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final ChronicleSource source = new ChronicleSource( new VanillaChronicle(sourceBasePath), 0); final ChronicleSink sink = new ChronicleSink( new VanillaChronicle(sinkBasePath), "localhost", source.getLocalPort()); try { final Thread at = new Thread("th-appender") { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (int i = 0; i < RUNS; i++) { appender.startExcerpt(); long value = 1000000000 + i; appender.append(value).append(' '); appender.finish(); } appender.close(); } catch(Exception e) { } } }; final Thread tt = new Thread("th-tailer") { public void run() { try { final ExcerptTailer tailer = sink.createTailer(); for (int i = 0; i < RUNS; i++) { long value = 1000000000 + i; assertTrue(tailer.nextIndex()); long val = tailer.parseLong(); assertEquals("i: " + i, value, val); assertEquals("i: " + i, 0, tailer.remaining()); tailer.finish(); } tailer.close(); } catch(Exception e) { } } }; at.start(); tt.start(); at.join(); tt.join(); } finally { sink.close(); sink.clear(); source.close(); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } }
#vulnerable code @Test public void testReplication1() throws IOException { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final ChronicleSource source = new ChronicleSource(new VanillaChronicle(sourceBasePath), 0); final ChronicleSink sink = new ChronicleSink(new VanillaChronicle(sinkBasePath), "localhost", source.getLocalPort()); try { final ExcerptAppender appender = source.createAppender(); final ExcerptTailer tailer = sink.createTailer(); for (int i = 0; i < RUNS; i++) { appender.startExcerpt(); long value = 1000000000 + i; appender.append(value).append(' '); appender.finish(); while(!tailer.nextIndex()); long val = tailer.parseLong(); //System.out.println("" + val); assertEquals("i: " + i, value, val); assertEquals("i: " + i, 0, tailer.remaining()); tailer.finish(); } appender.close(); tailer.close(); } finally { sink.close(); sink.checkCounts(1, 1); sink.clear(); source.close(); source.checkCounts(1, 1); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } } #location 34 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReplication1() throws Exception { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final Chronicle source = ChronicleQueueBuilder.vanilla(sourceBasePath) .source() .bindAddress("localhost", BASE_PORT + 101) .build(); final Chronicle sink = ChronicleQueueBuilder.vanilla(sinkBasePath) .sink() .connectAddress("localhost", BASE_PORT + 101) .build(); try { final Thread at = new Thread("th-appender") { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (int i = 0; i < RUNS; i++) { appender.startExcerpt(); long value = 1000000000 + i; appender.append(value).append(' '); appender.finish(); } appender.close(); } catch(Exception e) { } } }; final Thread tt = new Thread("th-tailer") { public void run() { try { final ExcerptTailer tailer = sink.createTailer(); for (int i = 0; i < RUNS; i++) { long value = 1000000000 + i; assertTrue(tailer.nextIndex()); long val = tailer.parseLong(); assertEquals("i: " + i, value, val); assertEquals("i: " + i, 0, tailer.remaining()); tailer.finish(); } tailer.close(); } catch(Exception e) { } } }; at.start(); tt.start(); at.join(); tt.join(); } finally { sink.close(); sink.clear(); source.close(); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } }
#vulnerable code @Test public void testReplication1() throws Exception { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final ChronicleSource source = new ChronicleSource( ChronicleQueueBuilder.vanilla(sourceBasePath).build(), 0); final ChronicleSink sink = new ChronicleSink( ChronicleQueueBuilder.vanilla(sinkBasePath).build(), "localhost", source.getLocalPort()); try { final Thread at = new Thread("th-appender") { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (int i = 0; i < RUNS; i++) { appender.startExcerpt(); long value = 1000000000 + i; appender.append(value).append(' '); appender.finish(); } appender.close(); } catch(Exception e) { } } }; final Thread tt = new Thread("th-tailer") { public void run() { try { final ExcerptTailer tailer = sink.createTailer(); for (int i = 0; i < RUNS; i++) { long value = 1000000000 + i; assertTrue(tailer.nextIndex()); long val = tailer.parseLong(); assertEquals("i: " + i, value, val); assertEquals("i: " + i, 0, tailer.remaining()); tailer.finish(); } tailer.close(); } catch(Exception e) { } } }; at.start(); tt.start(); at.join(); tt.join(); } finally { sink.close(); sink.clear(); source.close(); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } } #location 59 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPricePublishing3() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource) .source() .bindAddress(BASE_PORT + 4) .build(); final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink) .sink() .connectAddress("localhost", BASE_PORT + 4) .build(); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); assertEquals(-1, reader.excerpt.index()); reader.read(); assertEquals(0, reader.excerpt.index()); long start = System.nanoTime(); int prices = 2 * 1000 * 1000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) reader.read(); long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); }
#vulnerable code @Test public void testPricePublishing3() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 4); final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 4); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); assertEquals(-1, reader.excerpt.index()); reader.read(); assertEquals(0, reader.excerpt.index()); long start = System.nanoTime(); int prices = 2 * 1000 * 1000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) reader.read(); long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code int lastIndexFile(int cycle) { return lastIndexFile(cycle, 0); }
#vulnerable code int lastIndexFile(int cycle, int defaultCycle) { int maxIndex = -1; final File cyclePath = new File(baseFile, dateCache.formatFor(cycle)); final File[] files = cyclePath.listFiles(); if (files != null) { for (final File file : files) { String name = file.getName(); if (name.startsWith(FILE_NAME_PREFIX)) { int index = Integer.parseInt(name.substring(FILE_NAME_PREFIX.length())); if (maxIndex < index) { maxIndex = index; } } } } return maxIndex != -1 ? maxIndex : defaultCycle; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public synchronized LongValue acquireValueFor(CharSequence key) { StringBuilder sb = Wires.acquireStringBuilder(); mappedBytes.reserve(); try { mappedBytes.readPosition(0); mappedBytes.readLimit(mappedBytes.realCapacity()); while (mappedWire.readDataHeader()) { int header = mappedBytes.readInt(); if (Wires.isNotComplete(header)) break; long readPosition = mappedBytes.readPosition(); int length = Wires.lengthOf(header); ValueIn valueIn = mappedWire.readEventName(sb); if (StringUtils.equalsCaseIgnore(key, sb)) { return valueIn.int64ForBinding(null); } mappedBytes.readPosition(readPosition + length); } // not found int safeLength = Maths.toUInt31(mappedBytes.realCapacity() - mappedBytes.readPosition()); mappedBytes.writeLimit(mappedBytes.realCapacity()); mappedBytes.writePosition(mappedBytes.readPosition()); long pos = recovery.writeHeader(mappedWire, Wires.UNKNOWN_LENGTH, safeLength, timeoutMS, null); LongValue longValue = wireType.newLongReference().get(); mappedWire.writeEventName(key).int64forBinding(Long.MIN_VALUE, longValue); mappedWire.updateHeader(pos, false); return longValue; } catch (StreamCorruptedException | EOFException e) { throw new IORuntimeException(e); } finally { mappedBytes.release(); } }
#vulnerable code @Override public synchronized LongValue acquireValueFor(CharSequence key) { StringBuilder sb = Wires.acquireStringBuilder(); mappedBytes.reserve(); try { mappedBytes.readPosition(0); mappedBytes.readLimit(mappedBytes.realCapacity()); while (mappedWire.readDataHeader()) { int header = mappedBytes.readInt(); if (Wires.isNotComplete(header)) break; long readPosition = mappedBytes.readPosition(); int length = Wires.lengthOf(header); ValueIn valueIn = mappedWire.readEventName(sb); if (StringUtils.equalsCaseIgnore(key, sb)) { return valueIn.int64ForBinding(null); } mappedBytes.readPosition(readPosition + length); } // not found int safeLength = Maths.toUInt31(mappedBytes.realCapacity() - mappedBytes.readPosition()); mappedBytes.writeLimit(mappedBytes.realCapacity()); mappedBytes.writePosition(mappedBytes.readPosition()); long pos = recovery.writeHeader(mappedWire, Wires.UNKNOWN_LENGTH, safeLength, 10_000, null); LongValue longValue = wireType.newLongReference().get(); mappedWire.writeEventName(key).int64forBinding(Long.MIN_VALUE, longValue); mappedWire.updateHeader(pos, false); return longValue; } catch (StreamCorruptedException | EOFException e) { throw new IORuntimeException(e); } finally { mappedBytes.release(); } } #location 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void unlock(@NotNull String dir) { File path = new File(dir); if (!path.isDirectory()) { System.err.println("Path argument must be a queue directory"); System.exit(1); } File storeFilePath = new File(path, QUEUE_METADATA_FILE); if (!storeFilePath.exists()) { System.err.println("Metadata file not found, nothing to unlock"); System.exit(0); } final TableStore<?> store = SingleTableBuilder.binary(storeFilePath, Metadata.NoMeta.INSTANCE).readOnly(false).build(); // appender lock (new TableStoreWriteLock(store, BusyTimedPauser::new, 0L, "chronicle.append.lock")).forceUnlockLockAndDontWarn(); // write lock (new TableStoreWriteLock(store, BusyTimedPauser::new, 0L)).forceUnlockLockAndDontWarn(); System.out.println("Done"); }
#vulnerable code private static void unlock(@NotNull String dir) { File path = new File(dir); if (!path.isDirectory()) { System.err.println("Path argument must be a queue directory"); System.exit(1); } File storeFilePath = new File(path, QUEUE_METADATA_FILE); if (!storeFilePath.exists()) { System.err.println("Metadata file not found, nothing to unlock"); System.exit(0); } TableStore store = SingleTableBuilder.binary(storeFilePath, Metadata.NoMeta.INSTANCE).readOnly(false).build(); TSQueueLock queueLock = new TSQueueLock(store, BusyTimedPauser::new, 0L); // writeLock AKA appendLock TableStoreWriteLock writeLock = new TableStoreWriteLock(store, BusyTimedPauser::new, 0L); forceUnlock(queueLock); forceUnlock(writeLock); System.out.println("Done"); } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPersistedLocalVanillaSink_001() throws Exception { final int port = BASE_PORT + 301; final String basePath = getVanillaTestPath(); final Chronicle chronicle = ChronicleQueueBuilder.vanilla(basePath).build(); final Chronicle source = ChronicleQueueBuilder.source(chronicle) .bindAddress("localhost", port) .build(); final Chronicle sink = ChronicleQueueBuilder.sink(chronicle) .sharedChronicle(true) .connectAddress("localhost",port) .build(); final CountDownLatch latch = new CountDownLatch(5); final Random random = new Random(); final int items = 100; try { Thread appenderThread = new Thread() { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (long i = 1; i <= items; i++) { if (latch.getCount() > 0) { latch.countDown(); } appender.startExcerpt(8); appender.writeLong(i); appender.finish(); sleep(10 + random.nextInt(80)); appender.close(); } } catch (Exception e) { e.printStackTrace(); } } }; appenderThread.start(); latch.await(); final ExcerptTailer tailer1 = sink.createTailer().toStart(); for (long i = 1; i <= items; i++) { assertTrue(tailer1.nextIndex()); assertEquals(i, tailer1.readLong()); tailer1.finish(); } tailer1.close(); appenderThread.join(); sink.close(); sink.clear(); } finally { source.close(); source.clear(); } }
#vulnerable code @Test public void testPersistedLocalVanillaSink_001() throws Exception { final int port = BASE_PORT + 301; final String basePath = getVanillaTestPath(); final Chronicle chronicle = ChronicleQueueBuilder.vanilla(basePath).build(); final ChronicleSource source = new ChronicleSource(chronicle, port); final Chronicle sink = localChronicleSink(chronicle, "localhost", port); final CountDownLatch latch = new CountDownLatch(5); final Random random = new Random(); final int items = 100; try { Thread appenderThread = new Thread() { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (long i = 1; i <= items; i++) { if (latch.getCount() > 0) { latch.countDown(); } appender.startExcerpt(8); appender.writeLong(i); appender.finish(); sleep(10 + random.nextInt(80)); appender.close(); } } catch (Exception e) { e.printStackTrace(); } } }; appenderThread.start(); latch.await(); final ExcerptTailer tailer1 = sink.createTailer().toStart(); for (long i = 1; i <= items; i++) { assertTrue(tailer1.nextIndex()); assertEquals(i, tailer1.readLong()); tailer1.finish(); } tailer1.close(); appenderThread.join(); sink.close(); sink.clear(); } finally { source.close(); source.clear(); } } #location 56 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Before public void setup() { final Bytes out = ByteBufferBytes.wrap(ByteBuffer.allocate(22)); out.writeUTF(EXPECTED); output = out.flip().slice(); }
#vulnerable code @Before public void setup() { final Bytes out = new ByteBufferBytes(ByteBuffer.allocate(22)); out.writeUTF(EXPECTED); output = out.flip().slice(); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testOneAtATime() throws IOException { ChronicleConfig config = ChronicleConfig.TEST.clone(); config.indexBlockSize(128); // very small config.dataBlockSize(128); // very small final String basePath = TMP + "/testOneAtATime"; ChronicleTools.deleteOnExit(basePath); File indexFile = new File(basePath + ".index"); for (int i = 0; i < 1000; i++) { if (i % 10 == 0) System.out.println("i: " + i); long indexFileSize = indexFile.length(); IndexedChronicle chronicle = new IndexedChronicle(basePath, config); assertEquals("Index should not grow on open (i=" + i + ")", indexFileSize, indexFile.length()); if (i == 0) { ExcerptTailer tailer = chronicle.createTailer(); assertFalse(tailer.nextIndex()); Excerpt excerpt = chronicle.createExcerpt(); assertFalse(excerpt.index(0)); } ExcerptAppender appender = chronicle.createAppender(); appender.startExcerpt(); appender.writeDouble(i); appender.finish(); // ChronicleIndexReader.main(basePath+".index"); ExcerptTailer tailer = chronicle.createTailer(); long[] indexes = new long[i + 1]; long lastIndex = -1; for (int j = 0; j <= i; j++) { assertTrue(tailer.nextIndex()); assertTrue(tailer.index() + " > " + lastIndex, tailer.index() > lastIndex); lastIndex = tailer.index(); double d = tailer.readDouble(); assertEquals(j, d, 0.0); assertEquals(0, tailer.remaining()); indexes[j] = tailer.index(); tailer.finish(); } assertFalse(tailer.nextIndex()); Excerpt excerpt = chronicle.createExcerpt(); // forward for (int j = 0; j < i; j++) { assertTrue(excerpt.index(indexes[j])); double d = excerpt.readDouble(); assertEquals(j, d, 0.0); assertEquals(0, excerpt.remaining()); excerpt.finish(); } assertFalse(excerpt.index(indexes[indexes.length - 1] + 1)); // backward for (int j = i - 1; j >= 0; j--) { assertTrue(excerpt.index(indexes[j])); double d = excerpt.readDouble(); assertEquals(j, d, 0.0); assertEquals(0, excerpt.remaining()); excerpt.finish(); } assertFalse(excerpt.index(-1)); chronicle.close(); } }
#vulnerable code @Test public void testOneAtATime() throws IOException { ChronicleConfig config = ChronicleConfig.TEST.clone(); config.indexBlockSize(128); // very small config.dataBlockSize(128); // very small final String basePath = TMP + "/testOneAtATime"; ChronicleTools.deleteOnExit(basePath); File indexFile = new File(basePath + ".index"); for (int i = 0; i < 100; i++) { if (i % 10 == 0) System.out.println("i: " + i); long indexFileSize = indexFile.length(); IndexedChronicle chronicle = new IndexedChronicle(basePath); assertEquals("Index should not grow on open (i=" + i + ")", indexFileSize, indexFile.length()); if (i == 0) { ExcerptTailer tailer = chronicle.createTailer(); assertFalse(tailer.nextIndex()); Excerpt excerpt = chronicle.createExcerpt(); assertFalse(excerpt.index(0)); } ExcerptAppender appender = chronicle.createAppender(); appender.startExcerpt(); appender.writeDouble(i); appender.finish(); // ChronicleIndexReader.main(basePath+".index"); ExcerptTailer tailer = chronicle.createTailer(); long[] indexes = new long[i + 1]; long lastIndex = -1; for (int j = 0; j <= i; j++) { assertTrue(tailer.nextIndex()); assertTrue(tailer.index() + " > " + lastIndex, tailer.index() > lastIndex); lastIndex = tailer.index(); double d = tailer.readDouble(); assertEquals(j, d, 0.0); assertEquals(0, tailer.remaining()); indexes[j] = tailer.index(); tailer.finish(); } assertFalse(tailer.nextIndex()); Excerpt excerpt = chronicle.createExcerpt(); // forward for (int j = 0; j < i; j++) { assertTrue(excerpt.index(indexes[j])); double d = excerpt.readDouble(); assertEquals(j, d, 0.0); assertEquals(0, excerpt.remaining()); excerpt.finish(); } assertFalse(excerpt.index(indexes[indexes.length - 1] + 1)); // backward for (int j = i - 1; j >= 0; j--) { assertTrue(excerpt.index(indexes[j])); double d = excerpt.readDouble(); assertEquals(j, d, 0.0); assertEquals(0, excerpt.remaining()); excerpt.finish(); } assertFalse(excerpt.index(-1)); chronicle.close(); } } #location 24 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWrite3read3SingleThreadedWrite() throws Exception { try (DirectStore allocate = DirectStore.allocate(40 * 3)) { final BytesRingBuffer bytesRingBuffer = new BytesRingBuffer(allocate.bytes()); for (int i = 0; i < 100; i++) { bytesRingBuffer.offer(output.clear()); bytesRingBuffer.offer(output.clear()); bytesRingBuffer.offer(output.clear()); assertEquals(EXPECTED, bytesRingBuffer.take(maxSize -> input.clear()).readUTF()); assertEquals(EXPECTED, bytesRingBuffer.take(maxSize -> input.clear()).readUTF()); assertEquals(EXPECTED, bytesRingBuffer.take(maxSize -> input.clear()).readUTF()); } } }
#vulnerable code @Test public void testWrite3read3SingleThreadedWrite() throws Exception { try (DirectStore allocate = DirectStore.allocate(40 * 3)) { final BytesQueue bytesRingBuffer = new BytesQueue(allocate.bytes()); for (int i = 0; i < 100; i++) { bytesRingBuffer.offer(output.clear()); bytesRingBuffer.offer(output.clear()); bytesRingBuffer.offer(output.clear()); assertEquals(EXPECTED, bytesRingBuffer.poll(input.clear()).readUTF()); assertEquals(EXPECTED, bytesRingBuffer.poll(input.clear()).readUTF()); assertEquals(EXPECTED, bytesRingBuffer.poll(input.clear()).readUTF()); } } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public synchronized void release(@NotNull CommonStore store) { store.release(); long refCount = store.refCount(); assert refCount >= 0; if (refCount == 0) { for (Map.Entry<RollDetails, WeakReference<WireStore>> entry : stores.entrySet()) { WeakReference<WireStore> ref = entry.getValue(); if (ref != null && ref.get() == store) { stores.remove(entry.getKey()); storeFileListener.onReleased(entry.getKey().cycle(), store.file()); return; } } if (Jvm.debug().isEnabled(getClass())) Jvm.debug().on(getClass(), "Store was not registered: " + store.file()); } }
#vulnerable code public synchronized void release(@NotNull CommonStore store) { store.release(); long refCount = store.refCount(); assert refCount >= 0; if (refCount == 0) { for (Map.Entry<RollDetails, WeakReference<WireStore>> entry : stores.entrySet()) { WeakReference<WireStore> ref = entry.getValue(); if (ref != null && ref.get() == store) { stores.remove(entry.getKey()); storeFileListener.onReleased(entry.getKey().cycle(), store.file()); return; } } LOGGER.warn("Store was not registered {}", store.file().getName()); } } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { raftNode.getLock().lock(); try { Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder(); responseBuilder.setGranted(false); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { raftNode.stepDown(request.getTerm()); } boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm() || (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm() && request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getVotedFor() == 0 && logIsOk) { raftNode.stepDown(request.getTerm()); raftNode.setVotedFor(request.getServerId()); raftNode.getRaftLog().updateMetaData(raftNode.getCurrentTerm(), raftNode.getVotedFor(), null); responseBuilder.setGranted(true); responseBuilder.setTerm(raftNode.getCurrentTerm()); } LOG.info("Receive RequestVote request from server {} " + "in term {} (my term is {}), granted={}", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm(), responseBuilder.getGranted()); return responseBuilder.build(); } finally { raftNode.getLock().unlock(); } }
#vulnerable code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { LOG.info("Receive RequestVote request from server {} " + "in term {} (my term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.getLock().lock(); try { Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder(); responseBuilder.setGranted(false); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { raftNode.stepDown(request.getTerm()); } boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm() || (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm() && request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getVotedFor() == 0 && logIsOk) { raftNode.stepDown(request.getTerm()); raftNode.setVotedFor(request.getServerId()); raftNode.getRaftLog().updateMetaData(raftNode.getCurrentTerm(), raftNode.getVotedFor(), null); responseBuilder.setGranted(true); responseBuilder.setTerm(raftNode.getCurrentTerm()); } return responseBuilder.build(); } finally { raftNode.getLock().unlock(); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void appendEntries(Peer peer) { long firstLogIndex = raftLog.getFirstLogIndex(); if (peer.getNextIndex() < firstLogIndex) { installSnapshot(peer); return; } long prevLogIndex = peer.getNextIndex() - 1; long prevLogTerm = 0; if (prevLogIndex >= firstLogIndex) { prevLogTerm = raftLog.getEntry(prevLogIndex).getTerm(); } else if (prevLogIndex == 0) { prevLogTerm = 0; } else if (prevLogIndex == snapshot.getMetaData().getLastIncludedIndex()) { prevLogTerm = snapshot.getMetaData().getLastIncludedTerm(); } else { installSnapshot(peer); return; } Raft.AppendEntriesRequest.Builder requestBuilder = Raft.AppendEntriesRequest.newBuilder(); requestBuilder.setServerId(localServer.getServerId()); requestBuilder.setTerm(currentTerm); requestBuilder.setPrevLogTerm(prevLogTerm); requestBuilder.setPrevLogIndex(prevLogIndex); long numEntries = packEntries(peer.getNextIndex(), requestBuilder); requestBuilder.setCommitIndex(Math.min(commitIndex, prevLogIndex + numEntries)); Raft.AppendEntriesRequest request = requestBuilder.build(); Raft.AppendEntriesResponse response = peer.getRaftConsensusService().appendEntries(request); if (response == null) { LOG.warn("appendEntries with peer[{}:{}] failed", peer.getServerAddress().getHost(), peer.getServerAddress().getPort()); return; } if (response.getTerm() > currentTerm) { LOG.info("Received AppendEntries response from server {} " + "in term {} (this server's term was {})", peer.getServerAddress().getServerId(), response.getTerm(), currentTerm); stepDown(response.getTerm()); } else { if (response.getSuccess()) { peer.setMatchIndex(prevLogIndex + numEntries); advanceCommitIndex(); peer.setNextIndex(peer.getMatchIndex() + 1); } else { if (peer.getNextIndex() > 1) { peer.setNextIndex(peer.getNextIndex() - 1); } if (response.getLastLogIndex() != 0 && peer.getNextIndex() > response.getLastLogIndex() + 1) { peer.setNextIndex(response.getLastLogIndex() + 1); } } } }
#vulnerable code public void appendEntries(Peer peer) { long startLogIndex = raftLog.getStartLogIndex(); if (peer.getNextIndex() < startLogIndex) { this.installSnapshot(peer); return; } long lastLogIndex = this.raftLog.getLastLogIndex(); long prevLogIndex = peer.getNextIndex() - 1; long prevLogTerm = 0; if (prevLogIndex >= startLogIndex) { prevLogTerm = raftLog.getEntry(prevLogIndex).getTerm(); } else if (prevLogIndex == 0) { prevLogTerm = 0; } else if (prevLogIndex == lastSnapshotIndex) { prevLogTerm = lastSnapshotTerm; } else { installSnapshot(peer); return; } Raft.AppendEntriesRequest.Builder requestBuilder = Raft.AppendEntriesRequest.newBuilder(); requestBuilder.setServerId(localServer.getServerId()); requestBuilder.setTerm(currentTerm); requestBuilder.setPrevLogTerm(prevLogTerm); requestBuilder.setPrevLogIndex(prevLogIndex); long numEntries = packEntries(peer.getNextIndex(), requestBuilder); requestBuilder.setCommitIndex(Math.min(commitIndex, prevLogIndex + numEntries)); Raft.AppendEntriesRequest request = requestBuilder.build(); Raft.AppendEntriesResponse response = peer.getRaftConsensusService().appendEntries(request); if (response == null) { LOG.warn("appendEntries with peer[{}:{}] failed", peer.getServerAddress().getHost(), peer.getServerAddress().getPort()); return; } if (response.getTerm() > currentTerm) { LOG.info("Received AppendEntries response from server {} " + "in term {} (this server's term was {})", peer.getServerAddress().getServerId(), response.getTerm(), currentTerm); stepDown(response.getTerm()); } else { if (response.getSuccess()) { peer.setMatchIndex(prevLogIndex + numEntries); advanceCommitIndex(); peer.setNextIndex(peer.getMatchIndex() + 1); } else { if (peer.getNextIndex() > 1) { peer.setNextIndex(peer.getNextIndex() - 1); } if (response.getLastLogIndex() != 0 && peer.getNextIndex() > response.getLastLogIndex() + 1) { peer.setNextIndex(response.getLastLogIndex() + 1); } } } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { raftNode.getLock().lock(); Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder(); responseBuilder.setGranted(false); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm() || (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm() && request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getVotedFor() == 0 || logIsOk) { raftNode.stepDown(request.getTerm()); raftNode.setVotedFor(request.getServerId()); raftNode.updateMetaData(); responseBuilder.setGranted(true); responseBuilder.setTerm(raftNode.getCurrentTerm()); } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (request.getTerm() == raftNode.getCurrentTerm()) { if ((raftNode.getVotedFor() == 0 || raftNode.getVotedFor() == request.getServerId()) && (raftNode.getCurrentTerm() == request.getTerm() && raftNode.getCommitIndex() == request.getLastLogIndex())) { raftNode.setVotedFor(request.getServerId()); raftNode.stepDown(raftNode.getCurrentTerm()); raftNode.resetElectionTimer(); raftNode.updateMetaData(); Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(true) .setTerm(raftNode.getCurrentTerm()).build(); return response; } } Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(false) .setTerm(raftNode.getCurrentTerm()).build(); return response; } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { raftNode.getLock().lock(); Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder(); responseBuilder.setGranted(false); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm() || (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm() && request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getVotedFor() == 0 || logIsOk) { raftNode.stepDown(request.getTerm()); raftNode.setVotedFor(request.getServerId()); raftNode.updateMetaData(); responseBuilder.setGranted(true); responseBuilder.setTerm(raftNode.getCurrentTerm()); } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (request.getTerm() == raftNode.getCurrentTerm()) { if ((raftNode.getVotedFor() == 0 || raftNode.getVotedFor() == request.getServerId()) && (raftNode.getCurrentTerm() == request.getTerm() && raftNode.getCommitIndex() == request.getLastLogIndex())) { raftNode.setVotedFor(request.getServerId()); raftNode.stepDown(raftNode.getCurrentTerm()); raftNode.resetElectionTimer(); raftNode.updateMetaData(); Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(true) .setTerm(raftNode.getCurrentTerm()).build(); return response; } } Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(false) .setTerm(raftNode.getCurrentTerm()).build(); return response; } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { raftNode.getLock().lock(); Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder(); responseBuilder.setGranted(false); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm() || (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm() && request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getVotedFor() == 0 || logIsOk) { raftNode.stepDown(request.getTerm()); raftNode.setVotedFor(request.getServerId()); raftNode.updateMetaData(); responseBuilder.setGranted(true); responseBuilder.setTerm(raftNode.getCurrentTerm()); } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (request.getTerm() == raftNode.getCurrentTerm()) { if ((raftNode.getVotedFor() == 0 || raftNode.getVotedFor() == request.getServerId()) && (raftNode.getCurrentTerm() == request.getTerm() && raftNode.getCommitIndex() == request.getLastLogIndex())) { raftNode.setVotedFor(request.getServerId()); raftNode.stepDown(raftNode.getCurrentTerm()); raftNode.resetElectionTimer(); raftNode.updateMetaData(); Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(true) .setTerm(raftNode.getCurrentTerm()).build(); return response; } } Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(false) .setTerm(raftNode.getCurrentTerm()).build(); return response; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { raftNode.getLock().lock(); Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received AppendEntries request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex() && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); raftNode.getLock().unlock(); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getStartLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { continue; } // truncate segment log from index long lastIndexKept = index - 1; raftNode.getRaftLog().truncateSuffix(lastIndexKept); } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // apply state machine for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) { raftNode.getStateMachine().apply( raftNode.getRaftLog().getEntry(index).getData().toByteArray()); } } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received AppendEntries request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); responseBuilder.setTerm(request.getTerm()); } raftNode.stepDown(request.getTerm()); raftNode.resetElectionTimer(); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex() && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getStartLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { continue; } // TODO: truncate segment log from index } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // TODO: apply state machine } return responseBuilder.build(); } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { raftNode.getLock().lock(); Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder(); responseBuilder.setGranted(false); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm() || (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm() && request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getVotedFor() == 0 || logIsOk) { raftNode.stepDown(request.getTerm()); raftNode.setVotedFor(request.getServerId()); raftNode.updateMetaData(); responseBuilder.setGranted(true); responseBuilder.setTerm(raftNode.getCurrentTerm()); } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (request.getTerm() == raftNode.getCurrentTerm()) { if ((raftNode.getVotedFor() == 0 || raftNode.getVotedFor() == request.getServerId()) && (raftNode.getCurrentTerm() == request.getTerm() && raftNode.getCommitIndex() == request.getLastLogIndex())) { raftNode.setVotedFor(request.getServerId()); raftNode.stepDown(raftNode.getCurrentTerm()); raftNode.resetElectionTimer(); raftNode.updateMetaData(); Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(true) .setTerm(raftNode.getCurrentTerm()).build(); return response; } } Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(false) .setTerm(raftNode.getCurrentTerm()).build(); return response; } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { raftNode.getLock().lock(); Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received AppendEntries request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex() && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); raftNode.getLock().unlock(); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getStartLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { continue; } // truncate segment log from index long lastIndexKept = index - 1; raftNode.getRaftLog().truncateSuffix(lastIndexKept); } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // apply state machine for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) { raftNode.getStateMachine().apply( raftNode.getRaftLog().getEntry(index).getData().toByteArray()); } } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received AppendEntries request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); responseBuilder.setTerm(request.getTerm()); } raftNode.stepDown(request.getTerm()); raftNode.resetElectionTimer(); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex() && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getStartLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { continue; } // TODO: truncate segment log from index } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // TODO: apply state machine } return responseBuilder.build(); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void replicate(byte[] data) { lock.lock(); Raft.LogEntry logEntry = Raft.LogEntry.newBuilder() .setTerm(currentTerm) .setType(Raft.EntryType.ENTRY_TYPE_DATA) .setData(ByteString.copyFrom(data)).build(); List<Raft.LogEntry> entries = new ArrayList<>(); entries.add(logEntry); long newLastLogIndex = raftLog.append(entries); for (final Peer peer : peers) { executorService.submit(new Runnable() { @Override public void run() { appendEntries(peer); } }); } // sync wait condition commitIndex >= newLastLogIndex // TODO: add timeout try { while (commitIndex < newLastLogIndex) { try { commitIndexCondition.await(); } catch (InterruptedException ex) { LOG.warn(ex.getMessage()); } } } finally { lock.unlock(); } }
#vulnerable code public void replicate(byte[] data) { Raft.LogEntry logEntry = Raft.LogEntry.newBuilder() .setTerm(currentTerm) .setType(Raft.EntryType.ENTRY_TYPE_DATA) .setData(ByteString.copyFrom(data)).build(); List<Raft.LogEntry> entries = new ArrayList<>(); entries.add(logEntry); long newLastLogIndex = raftLog.append(entries); for (final Peer peer : peers) { executorService.submit(new Runnable() { @Override public void run() { appendEntries(peer); } }); } // sync wait condition commitIndex >= newLastLogIndex // TODO: add timeout lock.lock(); try { while (commitIndex < newLastLogIndex) { try { commitIndexCondition.await(); } catch (InterruptedException ex) { LOG.warn(ex.getMessage()); } } } finally { lock.unlock(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void appendEntries(Peer peer) { long firstLogIndex = raftLog.getFirstLogIndex(); if (peer.getNextIndex() < firstLogIndex) { installSnapshot(peer); return; } long prevLogIndex = peer.getNextIndex() - 1; long prevLogTerm = 0; if (prevLogIndex >= firstLogIndex) { prevLogTerm = raftLog.getEntry(prevLogIndex).getTerm(); } else if (prevLogIndex == 0) { prevLogTerm = 0; } else if (prevLogIndex == snapshot.getMetaData().getLastIncludedIndex()) { prevLogTerm = snapshot.getMetaData().getLastIncludedTerm(); } else { installSnapshot(peer); return; } Raft.AppendEntriesRequest.Builder requestBuilder = Raft.AppendEntriesRequest.newBuilder(); requestBuilder.setServerId(localServer.getServerId()); requestBuilder.setTerm(currentTerm); requestBuilder.setPrevLogTerm(prevLogTerm); requestBuilder.setPrevLogIndex(prevLogIndex); long numEntries = packEntries(peer.getNextIndex(), requestBuilder); requestBuilder.setCommitIndex(Math.min(commitIndex, prevLogIndex + numEntries)); Raft.AppendEntriesRequest request = requestBuilder.build(); Raft.AppendEntriesResponse response = peer.getRaftConsensusService().appendEntries(request); if (response == null) { LOG.warn("appendEntries with peer[{}:{}] failed", peer.getServerAddress().getHost(), peer.getServerAddress().getPort()); return; } if (response.getTerm() > currentTerm) { LOG.info("Received AppendEntries response from server {} " + "in term {} (this server's term was {})", peer.getServerAddress().getServerId(), response.getTerm(), currentTerm); stepDown(response.getTerm()); } else { if (response.getSuccess()) { peer.setMatchIndex(prevLogIndex + numEntries); advanceCommitIndex(); peer.setNextIndex(peer.getMatchIndex() + 1); } else { if (peer.getNextIndex() > 1) { peer.setNextIndex(peer.getNextIndex() - 1); } if (response.getLastLogIndex() != 0 && peer.getNextIndex() > response.getLastLogIndex() + 1) { peer.setNextIndex(response.getLastLogIndex() + 1); } } } }
#vulnerable code public void appendEntries(Peer peer) { long startLogIndex = raftLog.getStartLogIndex(); if (peer.getNextIndex() < startLogIndex) { this.installSnapshot(peer); return; } long lastLogIndex = this.raftLog.getLastLogIndex(); long prevLogIndex = peer.getNextIndex() - 1; long prevLogTerm = 0; if (prevLogIndex >= startLogIndex) { prevLogTerm = raftLog.getEntry(prevLogIndex).getTerm(); } else if (prevLogIndex == 0) { prevLogTerm = 0; } else if (prevLogIndex == lastSnapshotIndex) { prevLogTerm = lastSnapshotTerm; } else { installSnapshot(peer); return; } Raft.AppendEntriesRequest.Builder requestBuilder = Raft.AppendEntriesRequest.newBuilder(); requestBuilder.setServerId(localServer.getServerId()); requestBuilder.setTerm(currentTerm); requestBuilder.setPrevLogTerm(prevLogTerm); requestBuilder.setPrevLogIndex(prevLogIndex); long numEntries = packEntries(peer.getNextIndex(), requestBuilder); requestBuilder.setCommitIndex(Math.min(commitIndex, prevLogIndex + numEntries)); Raft.AppendEntriesRequest request = requestBuilder.build(); Raft.AppendEntriesResponse response = peer.getRaftConsensusService().appendEntries(request); if (response == null) { LOG.warn("appendEntries with peer[{}:{}] failed", peer.getServerAddress().getHost(), peer.getServerAddress().getPort()); return; } if (response.getTerm() > currentTerm) { LOG.info("Received AppendEntries response from server {} " + "in term {} (this server's term was {})", peer.getServerAddress().getServerId(), response.getTerm(), currentTerm); stepDown(response.getTerm()); } else { if (response.getSuccess()) { peer.setMatchIndex(prevLogIndex + numEntries); advanceCommitIndex(); peer.setNextIndex(peer.getMatchIndex() + 1); } else { if (peer.getNextIndex() > 1) { peer.setNextIndex(peer.getNextIndex() - 1); } if (response.getLastLogIndex() != 0 && peer.getNextIndex() > response.getLastLogIndex() + 1) { peer.setNextIndex(response.getLastLogIndex() + 1); } } } } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void advanceCommitIndex(RaftMessage.AppendEntriesRequest request) { long newCommitIndex = Math.min(request.getCommitIndex(), request.getPrevLogIndex() + request.getEntriesCount()); raftNode.setCommitIndex(newCommitIndex); if (raftNode.getLastAppliedIndex() < raftNode.getCommitIndex()) { // apply state machine for (long index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) { RaftMessage.LogEntry entry = raftNode.getRaftLog().getEntry(index); if (entry != null) { if (entry.getType() == RaftMessage.EntryType.ENTRY_TYPE_DATA) { raftNode.getStateMachine().apply(entry.getData().toByteArray()); } else if (entry.getType() == RaftMessage.EntryType.ENTRY_TYPE_CONFIGURATION) { raftNode.applyConfiguration(entry); } } raftNode.setLastAppliedIndex(index); } } }
#vulnerable code private void advanceCommitIndex(RaftMessage.AppendEntriesRequest request) { long newCommitIndex = Math.min(request.getCommitIndex(), request.getPrevLogIndex() + request.getEntriesCount()); raftNode.setCommitIndex(newCommitIndex); if (raftNode.getLastAppliedIndex() < raftNode.getCommitIndex()) { // apply state machine for (long index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) { RaftMessage.LogEntry entry = raftNode.getRaftLog().getEntry(index); if (entry.getType() == RaftMessage.EntryType.ENTRY_TYPE_DATA) { raftNode.getStateMachine().apply(entry.getData().toByteArray()); } else if (entry.getType() == RaftMessage.EntryType.ENTRY_TYPE_CONFIGURATION) { raftNode.applyConfiguration(entry); } raftNode.setLastAppliedIndex(index); } } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { raftNode.getLock().lock(); try { Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } raftNode.stepDown(request.getTerm()); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getFirstLogIndex() && raftNode.getRaftLog().getEntryTerm(request.getPrevLogIndex()) != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getFirstLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntryTerm(index) == entry.getTerm()) { continue; } // truncate segment log from index long lastIndexKept = index - 1; raftNode.getRaftLog().truncateSuffix(lastIndexKept); } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // apply state machine for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) { raftNode.getStateMachine().apply( raftNode.getRaftLog().getEntry(index).getData().toByteArray()); } } LOG.info("Receive AppendEntries request from server {} " + "in term {} (my term is {}), success={}", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm(), responseBuilder.getSuccess()); return responseBuilder.build(); } finally { raftNode.getLock().unlock(); } }
#vulnerable code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { LOG.info("Receive AppendEntries request from server {} " + "in term {} (my term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.getLock().lock(); try { Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } raftNode.stepDown(request.getTerm()); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getFirstLogIndex() && raftNode.getRaftLog().getEntryTerm(request.getPrevLogIndex()) != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getFirstLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntryTerm(index) == entry.getTerm()) { continue; } // truncate segment log from index long lastIndexKept = index - 1; raftNode.getRaftLog().truncateSuffix(lastIndexKept); } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // apply state machine for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) { raftNode.getStateMachine().apply( raftNode.getRaftLog().getEntry(index).getData().toByteArray()); } } return responseBuilder.build(); } finally { raftNode.getLock().unlock(); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void installSnapshot(Peer peer) { Raft.InstallSnapshotRequest.Builder requestBuilder = Raft.InstallSnapshotRequest.newBuilder(); requestBuilder.setServerId(localServer.getServerId()); requestBuilder.setTerm(currentTerm); // send snapshot Raft.InstallSnapshotRequest request = this.buildInstallSnapshotRequest( null, 0, 0); peer.getRpcClient().asyncCall("RaftConsensusService.installSnapshot", request, new InstallSnapshotResponseCallback(peer, request)); isSnapshoting = true; }
#vulnerable code public void installSnapshot(Peer peer) { Raft.InstallSnapshotRequest.Builder requestBuilder = Raft.InstallSnapshotRequest.newBuilder(); requestBuilder.setServerId(localServer.getServerId()); requestBuilder.setTerm(currentTerm); // send snapshot try { snapshotLock.readLock().lock(); Raft.InstallSnapshotRequest request = this.buildInstallSnapshotRequest( null, 0, 0); peer.getRpcClient().asyncCall("RaftConsensusService.installSnapshot", request, new InstallSnapshotResponseCallback(peer, request)); isSnapshoting = true; } finally { snapshotLock.readLock().unlock(); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { raftNode.getLock().lock(); Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received AppendEntries request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex() && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); raftNode.getLock().unlock(); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getStartLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { continue; } // truncate segment log from index long lastIndexKept = index - 1; raftNode.getRaftLog().truncateSuffix(lastIndexKept); } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // apply state machine for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) { raftNode.getStateMachine().apply( raftNode.getRaftLog().getEntry(index).getData().toByteArray()); } } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received AppendEntries request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); responseBuilder.setTerm(request.getTerm()); } raftNode.stepDown(request.getTerm()); raftNode.resetElectionTimer(); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex() && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getStartLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { continue; } // TODO: truncate segment log from index } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // TODO: apply state machine } return responseBuilder.build(); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.InstallSnapshotResponse installSnapshot(Raft.InstallSnapshotRequest request) { raftNode.getLock().lock(); Raft.InstallSnapshotResponse.Builder responseBuilder = Raft.InstallSnapshotResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { LOG.info("Caller({}) is stale. Our term is {}, theirs is {}", request.getServerId(), raftNode.getCurrentTerm(), request.getTerm()); raftNode.getLock().unlock(); return responseBuilder.build(); } raftNode.stepDown(request.getTerm()); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } // write snapshot data to local String tmpSnapshotDir = raftNode.getSnapshot().getSnapshotDir() + ".tmp"; File file = new File(tmpSnapshotDir); if (file.exists() && request.getIsFirst()) { file.delete(); file.mkdir(); } if (request.getIsFirst()) { raftNode.getSnapshot().updateMetaData(tmpSnapshotDir, request.getSnapshotMetaData().getLastIncludedIndex(), request.getSnapshotMetaData().getLastIncludedTerm()); } // write to file RandomAccessFile randomAccessFile = null; try { String currentDataFileName = tmpSnapshotDir + File.pathSeparator + "data" + File.pathSeparator + request.getFileName(); File currentDataFile = new File(currentDataFileName); if (!currentDataFile.exists()) { currentDataFile.createNewFile(); } randomAccessFile = RaftFileUtils.openFile( tmpSnapshotDir + File.pathSeparator + "data", request.getFileName(), "rw"); randomAccessFile.skipBytes((int) request.getOffset()); randomAccessFile.write(request.getData().toByteArray()); if (randomAccessFile != null) { try { randomAccessFile.close(); randomAccessFile = null; } catch (Exception ex2) { LOG.warn("close failed"); } } // move tmp dir to snapshot dir if this is the last package File snapshotDirFile = new File(raftNode.getSnapshot().getSnapshotDir()); if (snapshotDirFile.exists()) { snapshotDirFile.delete(); } FileUtils.moveDirectory(new File(tmpSnapshotDir), snapshotDirFile); responseBuilder.setSuccess(true); } catch (IOException ex) { LOG.warn("io exception, msg={}", ex.getMessage()); } finally { RaftFileUtils.closeFile(randomAccessFile); } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.InstallSnapshotResponse installSnapshot(Raft.InstallSnapshotRequest request) { Raft.InstallSnapshotResponse.Builder responseBuilder = Raft.InstallSnapshotResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); raftNode.getLock().lock(); if (request.getTerm() < raftNode.getCurrentTerm()) { LOG.info("Caller({}) is stale. Our term is {}, theirs is {}", request.getServerId(), raftNode.getCurrentTerm(), request.getTerm()); raftNode.getLock().unlock(); return responseBuilder.build(); } raftNode.stepDown(request.getTerm()); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } raftNode.getLock().unlock(); // write snapshot data to local String tmpSnapshotDir = raftNode.getSnapshot().getSnapshotDir() + ".tmp"; File file = new File(tmpSnapshotDir); if (file.exists() && request.getIsFirst()) { file.delete(); file.mkdir(); } if (request.getIsFirst()) { raftNode.getSnapshot().updateMetaData(tmpSnapshotDir, request.getSnapshotMetaData().getLastIncludedIndex(), request.getSnapshotMetaData().getLastIncludedTerm()); } // write to file RandomAccessFile randomAccessFile = null; try { String currentDataFileName = tmpSnapshotDir + File.pathSeparator + "data" + File.pathSeparator + request.getFileName(); File currentDataFile = new File(currentDataFileName); if (!currentDataFile.exists()) { currentDataFile.createNewFile(); } randomAccessFile = RaftFileUtils.openFile( tmpSnapshotDir + File.pathSeparator + "data", request.getFileName(), "rw"); randomAccessFile.skipBytes((int) request.getOffset()); randomAccessFile.write(request.getData().toByteArray()); if (randomAccessFile != null) { try { randomAccessFile.close(); randomAccessFile = null; } catch (Exception ex2) { LOG.warn("close failed"); } } // move tmp dir to snapshot dir if this is the last package File snapshotDirFile = new File(raftNode.getSnapshot().getSnapshotDir()); if (snapshotDirFile.exists()) { snapshotDirFile.delete(); } FileUtils.moveDirectory(new File(tmpSnapshotDir), snapshotDirFile); responseBuilder.setSuccess(true); } catch (IOException ex) { LOG.warn("io exception, msg={}", ex.getMessage()); } finally { RaftFileUtils.closeFile(randomAccessFile); } return responseBuilder.build(); } #location 27 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void advanceCommitIndex() { // 获取quorum matchIndex int peerNum = peers.size(); long[] matchIndexes = new long[peerNum + 1]; for (int i = 0; i < peerNum - 1; i++) { matchIndexes[i] = peers.get(i).getMatchIndex(); } matchIndexes[peerNum] = raftLog.getLastLogIndex(); Arrays.sort(matchIndexes); long newCommitIndex = matchIndexes[(peerNum + 1 + 1) / 2]; if (raftLog.getEntry(newCommitIndex).getTerm() != currentTerm) { return; } lock.lock(); if (commitIndex >= newCommitIndex) { return; } long oldCommitIndex = commitIndex; commitIndex = newCommitIndex; // 同步到状态机 for (long index = oldCommitIndex + 1; index <= newCommitIndex; index++) { Raft.LogEntry entry = raftLog.getEntry(index); stateMachine.apply(entry.getData().toByteArray()); } lastAppliedIndex = commitIndex; commitIndexCondition.signalAll(); lock.unlock(); }
#vulnerable code public void advanceCommitIndex() { // 获取quorum matchIndex int peerNum = peers.size(); long[] matchIndexes = new long[peerNum + 1]; for (int i = 0; i < peerNum - 1; i++) { matchIndexes[i] = peers.get(i).getMatchIndex(); } matchIndexes[peerNum] = lastSyncedIndex; Arrays.sort(matchIndexes); long newCommitIndex = matchIndexes[(peerNum + 1 + 1) / 2]; if (raftLog.getEntry(newCommitIndex).getTerm() != currentTerm) { return; } lock.lock(); if (commitIndex >= newCommitIndex) { return; } long oldCommitIndex = commitIndex; commitIndex = newCommitIndex; // 同步到状态机 for (long index = oldCommitIndex + 1; index <= newCommitIndex; index++) { Raft.LogEntry entry = raftLog.getEntry(index); stateMachine.apply(entry.getData().toByteArray()); } lastAppliedIndex = commitIndex; commitIndexCondition.signalAll(); lock.unlock(); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void takeSnapshot() { if (raftLog.getTotalSize() < RaftOption.snapshotMinLogSize) { return; } if (lastAppliedIndex <= snapshot.getMetaData().getLastIncludedIndex()) { return; } long lastAppliedTerm = 0; if (lastAppliedIndex >= raftLog.getFirstLogIndex() && lastAppliedIndex <= raftLog.getLastLogIndex()) { lastAppliedTerm = raftLog.getEntry(lastAppliedIndex).getTerm(); } if (!isSnapshoting) { isSnapshoting = true; // take snapshot String tmpSnapshotDir = snapshot.getSnapshotDir() + ".tmp"; snapshot.updateMetaData(tmpSnapshotDir, lastAppliedIndex, lastAppliedTerm); String tmpSnapshotDataDir = tmpSnapshotDir + File.pathSeparator + "data"; stateMachine.writeSnapshot(tmpSnapshotDataDir); try { FileUtils.moveDirectory(new File(tmpSnapshotDir), new File(snapshot.getSnapshotDir())); } catch (IOException ex) { LOG.warn("move direct failed, msg={}", ex.getMessage()); } } }
#vulnerable code public void takeSnapshot() { if (raftLog.getTotalSize() < RaftOption.snapshotMinLogSize) { return; } if (lastAppliedIndex <= lastSnapshotIndex) { return; } long lastAppliedTerm = 0; if (lastAppliedIndex >= raftLog.getStartLogIndex() && lastAppliedIndex <= raftLog.getLastLogIndex()) { lastAppliedTerm = raftLog.getEntry(lastAppliedIndex).getTerm(); } snapshotLock.writeLock().lock(); // take snapshot String tmpSnapshotDir = snapshot.getSnapshotDir() + ".tmp"; snapshot.updateMetaData(tmpSnapshotDir, lastAppliedIndex, lastAppliedTerm); String tmpSnapshotDataDir = tmpSnapshotDir + File.pathSeparator + "data"; stateMachine.writeSnapshot(tmpSnapshotDataDir); try { FileUtils.moveDirectory(new File(tmpSnapshotDir), new File(snapshot.getSnapshotDir())); lastSnapshotIndex = lastAppliedIndex; lastSnapshotTerm = lastAppliedTerm; } catch (IOException ex) { LOG.warn("move direct failed, msg={}", ex.getMessage()); } snapshotLock.writeLock().unlock(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { raftNode.getLock().lock(); Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received AppendEntries request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex() && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); raftNode.getLock().unlock(); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getStartLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { continue; } // truncate segment log from index long lastIndexKept = index - 1; raftNode.getRaftLog().truncateSuffix(lastIndexKept); } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // apply state machine for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) { raftNode.getStateMachine().apply( raftNode.getRaftLog().getEntry(index).getData().toByteArray()); } } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received AppendEntries request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); responseBuilder.setTerm(request.getTerm()); } raftNode.stepDown(request.getTerm()); raftNode.resetElectionTimer(); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex() && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getStartLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { continue; } // TODO: truncate segment log from index } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // TODO: apply state machine } return responseBuilder.build(); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { raftNode.getLock().lock(); Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder(); responseBuilder.setGranted(false); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm() || (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm() && request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getVotedFor() == 0 || logIsOk) { raftNode.stepDown(request.getTerm()); raftNode.setVotedFor(request.getServerId()); raftNode.updateMetaData(); responseBuilder.setGranted(true); responseBuilder.setTerm(raftNode.getCurrentTerm()); } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (request.getTerm() == raftNode.getCurrentTerm()) { if ((raftNode.getVotedFor() == 0 || raftNode.getVotedFor() == request.getServerId()) && (raftNode.getCurrentTerm() == request.getTerm() && raftNode.getCommitIndex() == request.getLastLogIndex())) { raftNode.setVotedFor(request.getServerId()); raftNode.stepDown(raftNode.getCurrentTerm()); raftNode.resetElectionTimer(); raftNode.updateMetaData(); Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(true) .setTerm(raftNode.getCurrentTerm()).build(); return response; } } Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(false) .setTerm(raftNode.getCurrentTerm()).build(); return response; } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.InstallSnapshotResponse installSnapshot(Raft.InstallSnapshotRequest request) { raftNode.getLock().lock(); Raft.InstallSnapshotResponse.Builder responseBuilder = Raft.InstallSnapshotResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { LOG.info("Caller({}) is stale. Our term is {}, theirs is {}", request.getServerId(), raftNode.getCurrentTerm(), request.getTerm()); raftNode.getLock().unlock(); return responseBuilder.build(); } raftNode.stepDown(request.getTerm()); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } // write snapshot data to local String tmpSnapshotDir = raftNode.getSnapshot().getSnapshotDir() + ".tmp"; File file = new File(tmpSnapshotDir); if (file.exists() && request.getIsFirst()) { file.delete(); file.mkdir(); } if (request.getIsFirst()) { raftNode.getSnapshot().updateMetaData(tmpSnapshotDir, request.getSnapshotMetaData().getLastIncludedIndex(), request.getSnapshotMetaData().getLastIncludedTerm()); } // write to file RandomAccessFile randomAccessFile = null; try { String currentDataFileName = tmpSnapshotDir + File.pathSeparator + "data" + File.pathSeparator + request.getFileName(); File currentDataFile = new File(currentDataFileName); if (!currentDataFile.exists()) { currentDataFile.createNewFile(); } randomAccessFile = RaftFileUtils.openFile( tmpSnapshotDir + File.pathSeparator + "data", request.getFileName(), "rw"); randomAccessFile.skipBytes((int) request.getOffset()); randomAccessFile.write(request.getData().toByteArray()); if (randomAccessFile != null) { try { randomAccessFile.close(); randomAccessFile = null; } catch (Exception ex2) { LOG.warn("close failed"); } } // move tmp dir to snapshot dir if this is the last package File snapshotDirFile = new File(raftNode.getSnapshot().getSnapshotDir()); if (snapshotDirFile.exists()) { snapshotDirFile.delete(); } FileUtils.moveDirectory(new File(tmpSnapshotDir), snapshotDirFile); responseBuilder.setSuccess(true); } catch (IOException ex) { LOG.warn("io exception, msg={}", ex.getMessage()); } finally { RaftFileUtils.closeFile(randomAccessFile); } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.InstallSnapshotResponse installSnapshot(Raft.InstallSnapshotRequest request) { Raft.InstallSnapshotResponse.Builder responseBuilder = Raft.InstallSnapshotResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); raftNode.getLock().lock(); if (request.getTerm() < raftNode.getCurrentTerm()) { LOG.info("Caller({}) is stale. Our term is {}, theirs is {}", request.getServerId(), raftNode.getCurrentTerm(), request.getTerm()); raftNode.getLock().unlock(); return responseBuilder.build(); } raftNode.stepDown(request.getTerm()); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } raftNode.getLock().unlock(); // write snapshot data to local String tmpSnapshotDir = raftNode.getSnapshot().getSnapshotDir() + ".tmp"; File file = new File(tmpSnapshotDir); if (file.exists() && request.getIsFirst()) { file.delete(); file.mkdir(); } if (request.getIsFirst()) { raftNode.getSnapshot().updateMetaData(tmpSnapshotDir, request.getSnapshotMetaData().getLastIncludedIndex(), request.getSnapshotMetaData().getLastIncludedTerm()); } // write to file RandomAccessFile randomAccessFile = null; try { String currentDataFileName = tmpSnapshotDir + File.pathSeparator + "data" + File.pathSeparator + request.getFileName(); File currentDataFile = new File(currentDataFileName); if (!currentDataFile.exists()) { currentDataFile.createNewFile(); } randomAccessFile = RaftFileUtils.openFile( tmpSnapshotDir + File.pathSeparator + "data", request.getFileName(), "rw"); randomAccessFile.skipBytes((int) request.getOffset()); randomAccessFile.write(request.getData().toByteArray()); if (randomAccessFile != null) { try { randomAccessFile.close(); randomAccessFile = null; } catch (Exception ex2) { LOG.warn("close failed"); } } // move tmp dir to snapshot dir if this is the last package File snapshotDirFile = new File(raftNode.getSnapshot().getSnapshotDir()); if (snapshotDirFile.exists()) { snapshotDirFile.delete(); } FileUtils.moveDirectory(new File(tmpSnapshotDir), snapshotDirFile); responseBuilder.setSuccess(true); } catch (IOException ex) { LOG.warn("io exception, msg={}", ex.getMessage()); } finally { RaftFileUtils.closeFile(randomAccessFile); } return responseBuilder.build(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void installSnapshot(Peer peer) { Raft.InstallSnapshotRequest.Builder requestBuilder = Raft.InstallSnapshotRequest.newBuilder(); requestBuilder.setServerId(localServer.getServerId()); requestBuilder.setTerm(currentTerm); // send snapshot Raft.InstallSnapshotRequest request = this.buildInstallSnapshotRequest( null, 0, 0); peer.getRpcClient().asyncCall("RaftConsensusService.installSnapshot", request, new InstallSnapshotResponseCallback(peer, request)); isSnapshoting = true; }
#vulnerable code public void installSnapshot(Peer peer) { Raft.InstallSnapshotRequest.Builder requestBuilder = Raft.InstallSnapshotRequest.newBuilder(); requestBuilder.setServerId(localServer.getServerId()); requestBuilder.setTerm(currentTerm); // send snapshot try { snapshotLock.readLock().lock(); Raft.InstallSnapshotRequest request = this.buildInstallSnapshotRequest( null, 0, 0); peer.getRpcClient().asyncCall("RaftConsensusService.installSnapshot", request, new InstallSnapshotResponseCallback(peer, request)); isSnapshoting = true; } finally { snapshotLock.readLock().unlock(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { raftNode.getLock().lock(); Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received AppendEntries request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex() && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); raftNode.getLock().unlock(); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getStartLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { continue; } // truncate segment log from index long lastIndexKept = index - 1; raftNode.getRaftLog().truncateSuffix(lastIndexKept); } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // apply state machine for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) { raftNode.getStateMachine().apply( raftNode.getRaftLog().getEntry(index).getData().toByteArray()); } } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); responseBuilder.setSuccess(false); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received AppendEntries request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); responseBuilder.setTerm(request.getTerm()); } raftNode.stepDown(request.getTerm()); raftNode.resetElectionTimer(); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { LOG.debug("Rejecting AppendEntries RPC: would leave gap"); return responseBuilder.build(); } if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex() && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() != request.getPrevLogTerm()) { LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); return responseBuilder.build(); } responseBuilder.setSuccess(true); List<Raft.LogEntry> entries = new ArrayList<>(); long index = request.getPrevLogIndex(); for (Raft.LogEntry entry : request.getEntriesList()) { index++; if (index < raftNode.getRaftLog().getStartLogIndex()) { continue; } if (raftNode.getRaftLog().getLastLogIndex() >= index) { if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { continue; } // TODO: truncate segment log from index } entries.add(entry); } raftNode.getRaftLog().append(entries); responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getCommitIndex() < request.getCommitIndex()) { raftNode.setCommitIndex(request.getCommitIndex()); // TODO: apply state machine } return responseBuilder.build(); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void replicate(byte[] data) { lock.lock(); Raft.LogEntry logEntry = Raft.LogEntry.newBuilder() .setTerm(currentTerm) .setType(Raft.EntryType.ENTRY_TYPE_DATA) .setData(ByteString.copyFrom(data)).build(); List<Raft.LogEntry> entries = new ArrayList<>(); entries.add(logEntry); long newLastLogIndex = raftLog.append(entries); for (final Peer peer : peers) { executorService.submit(new Runnable() { @Override public void run() { appendEntries(peer); } }); } // sync wait condition commitIndex >= newLastLogIndex // TODO: add timeout try { while (commitIndex < newLastLogIndex) { try { commitIndexCondition.await(); } catch (InterruptedException ex) { LOG.warn(ex.getMessage()); } } } finally { lock.unlock(); } }
#vulnerable code public void replicate(byte[] data) { Raft.LogEntry logEntry = Raft.LogEntry.newBuilder() .setTerm(currentTerm) .setType(Raft.EntryType.ENTRY_TYPE_DATA) .setData(ByteString.copyFrom(data)).build(); List<Raft.LogEntry> entries = new ArrayList<>(); entries.add(logEntry); long newLastLogIndex = raftLog.append(entries); for (final Peer peer : peers) { executorService.submit(new Runnable() { @Override public void run() { appendEntries(peer); } }); } // sync wait condition commitIndex >= newLastLogIndex // TODO: add timeout lock.lock(); try { while (commitIndex < newLastLogIndex) { try { commitIndexCondition.await(); } catch (InterruptedException ex) { LOG.warn(ex.getMessage()); } } } finally { lock.unlock(); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.InstallSnapshotResponse installSnapshot(Raft.InstallSnapshotRequest request) { raftNode.getLock().lock(); try { Raft.InstallSnapshotResponse.Builder responseBuilder = Raft.InstallSnapshotResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } raftNode.stepDown(request.getTerm()); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } // write snapshot data to local String tmpSnapshotDir = raftNode.getSnapshot().getSnapshotDir() + ".tmp"; File file = new File(tmpSnapshotDir); if (file.exists() && request.getIsFirst()) { file.delete(); file.mkdir(); } if (request.getIsFirst()) { raftNode.getSnapshot().updateMetaData(tmpSnapshotDir, request.getSnapshotMetaData().getLastIncludedIndex(), request.getSnapshotMetaData().getLastIncludedTerm()); } // write to file RandomAccessFile randomAccessFile = null; try { String currentDataFileName = tmpSnapshotDir + File.separator + "data" + File.separator + request.getFileName(); File currentDataFile = new File(currentDataFileName); if (!currentDataFile.exists()) { currentDataFile.createNewFile(); } randomAccessFile = RaftFileUtils.openFile( tmpSnapshotDir + File.separator + "data", request.getFileName(), "rw"); randomAccessFile.skipBytes((int) request.getOffset()); randomAccessFile.write(request.getData().toByteArray()); if (randomAccessFile != null) { try { randomAccessFile.close(); randomAccessFile = null; } catch (Exception ex2) { LOG.warn("close failed"); } } // move tmp dir to snapshot dir if this is the last package File snapshotDirFile = new File(raftNode.getSnapshot().getSnapshotDir()); if (snapshotDirFile.exists()) { snapshotDirFile.delete(); } FileUtils.moveDirectory(new File(tmpSnapshotDir), snapshotDirFile); responseBuilder.setSuccess(true); } catch (IOException ex) { LOG.warn("io exception, msg={}", ex.getMessage()); } finally { RaftFileUtils.closeFile(randomAccessFile); } LOG.info("Receive installSnapshot request from server {} " + "in term {} (my term is {}), success={}", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm(), responseBuilder.getSuccess()); return responseBuilder.build(); } finally { raftNode.getLock().unlock(); } }
#vulnerable code @Override public Raft.InstallSnapshotResponse installSnapshot(Raft.InstallSnapshotRequest request) { LOG.info("Receive installSnapshot request from server {} " + "in term {} (my term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.getLock().lock(); try { Raft.InstallSnapshotResponse.Builder responseBuilder = Raft.InstallSnapshotResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { return responseBuilder.build(); } raftNode.stepDown(request.getTerm()); if (raftNode.getLeaderId() == 0) { raftNode.setLeaderId(request.getServerId()); } // write snapshot data to local String tmpSnapshotDir = raftNode.getSnapshot().getSnapshotDir() + ".tmp"; File file = new File(tmpSnapshotDir); if (file.exists() && request.getIsFirst()) { file.delete(); file.mkdir(); } if (request.getIsFirst()) { raftNode.getSnapshot().updateMetaData(tmpSnapshotDir, request.getSnapshotMetaData().getLastIncludedIndex(), request.getSnapshotMetaData().getLastIncludedTerm()); } // write to file RandomAccessFile randomAccessFile = null; try { String currentDataFileName = tmpSnapshotDir + File.separator + "data" + File.separator + request.getFileName(); File currentDataFile = new File(currentDataFileName); if (!currentDataFile.exists()) { currentDataFile.createNewFile(); } randomAccessFile = RaftFileUtils.openFile( tmpSnapshotDir + File.separator + "data", request.getFileName(), "rw"); randomAccessFile.skipBytes((int) request.getOffset()); randomAccessFile.write(request.getData().toByteArray()); if (randomAccessFile != null) { try { randomAccessFile.close(); randomAccessFile = null; } catch (Exception ex2) { LOG.warn("close failed"); } } // move tmp dir to snapshot dir if this is the last package File snapshotDirFile = new File(raftNode.getSnapshot().getSnapshotDir()); if (snapshotDirFile.exists()) { snapshotDirFile.delete(); } FileUtils.moveDirectory(new File(tmpSnapshotDir), snapshotDirFile); responseBuilder.setSuccess(true); } catch (IOException ex) { LOG.warn("io exception, msg={}", ex.getMessage()); } finally { RaftFileUtils.closeFile(randomAccessFile); } return responseBuilder.build(); } finally { raftNode.getLock().unlock(); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { raftNode.getLock().lock(); Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder(); responseBuilder.setGranted(false); responseBuilder.setTerm(raftNode.getCurrentTerm()); if (request.getTerm() < raftNode.getCurrentTerm()) { raftNode.getLock().unlock(); return responseBuilder.build(); } if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm() || (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm() && request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex()); if (raftNode.getVotedFor() == 0 || logIsOk) { raftNode.stepDown(request.getTerm()); raftNode.setVotedFor(request.getServerId()); raftNode.updateMetaData(); responseBuilder.setGranted(true); responseBuilder.setTerm(raftNode.getCurrentTerm()); } raftNode.getLock().unlock(); return responseBuilder.build(); }
#vulnerable code @Override public Raft.VoteResponse requestVote(Raft.VoteRequest request) { if (request.getTerm() > raftNode.getCurrentTerm()) { LOG.info("Received RequestVote request from server {} " + "in term {} (this server's term was {})", request.getServerId(), request.getTerm(), raftNode.getCurrentTerm()); raftNode.stepDown(request.getTerm()); } if (request.getTerm() == raftNode.getCurrentTerm()) { if ((raftNode.getVotedFor() == 0 || raftNode.getVotedFor() == request.getServerId()) && (raftNode.getCurrentTerm() == request.getTerm() && raftNode.getCommitIndex() == request.getLastLogIndex())) { raftNode.setVotedFor(request.getServerId()); raftNode.stepDown(raftNode.getCurrentTerm()); raftNode.resetElectionTimer(); raftNode.updateMetaData(); Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(true) .setTerm(raftNode.getCurrentTerm()).build(); return response; } } Raft.VoteResponse response = Raft.VoteResponse.newBuilder() .setGranted(false) .setTerm(raftNode.getCurrentTerm()).build(); return response; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) { String pipelinePath = new ZhihuConfiguration().getFolloweePath(); int crawlSize = 1000000; Spider.create(new ZhihuFolloweePageProcessor()) .setScheduler(//new QueueScheduler() new FileCacheQueueScheduler(pipelinePath) .setDuplicateRemover(new BloomFilterDuplicateRemover(crawlSize))) .addPipeline(new FilePipeline(pipelinePath)) .addUrl(generateMemberUrl("hydro-ding")) .thread(20) .run(); }
#vulnerable code public static void main(String[] args) { String pipelinePath = new ZhihuConfiguration().getFolloweePath(); int crawlSize = 1000000; Spider.create(new ZhihuFolloweePageProcessor()) .setScheduler(//new QueueScheduler() new FixedFileCacheQueueScheduler(pipelinePath) .setDuplicateRemover(new BloomFilterDuplicateRemover(crawlSize))) .addPipeline(new FilePipeline(pipelinePath)) .addUrl(generateMemberUrl("hydro-ding")) .thread(20) .run(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Set<String> getURLTokens(String path) { List<String> tokens = FileHelper.processFile(path, br -> { List<String> ts = new ArrayList<>(); String s; while ((s = br.readLine()) != null) { ts.add(s); } return ts; }).orElse(new ArrayList<>()); return new HashSet<>(tokens); }
#vulnerable code public Set<String> getURLTokens(String path) { Set<String> urlTokens = new HashSet<>(); BufferedReader in; try { in = new BufferedReader( new FileReader(new File(path)) ); String s; while ((s = in.readLine()) != null) { urlTokens.add(s); } in.close(); return urlTokens; } catch (IOException e) { logger.error("IOException when readFollowees user data from file : {}", e); return null; } } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) { ElasticsearchUploader esUploader = new ElasticsearchUploader(); ElasticsearchUploader.logger.info("aaa"); }
#vulnerable code public static void main(String[] args) { TransportClient client = null; try { // on startup client = new PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300)) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300)); // on shutdown client.close(); } catch (UnknownHostException e) { e.printStackTrace(); } } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String readFollowees(File inItem) { List<String> followees = FileHelper.processFile(inItem, br -> { br.readLine();//pass first line String s = br.readLine(); if (!StringUtils.isEmpty(s)) { s = s.substring(s.indexOf("{")); } return Collections.singletonList(s); }).orElse(new ArrayList<>()); return followees.size() == 0 ? null : followees.get(0); }
#vulnerable code public static String readFollowees(File inItem) { BufferedReader in = null; try { in = new BufferedReader( new FileReader(inItem) ); String s; in.readLine();//pass first line s = in.readLine(); if (!StringUtils.isEmpty(s)) { s = s.substring(s.indexOf("{")); } in.close(); return s; } catch (IOException e) { logger.error("IOException when readFollowees user data from file : {}", e); return null; } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.