input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Test public void publicResourceHandlerTest() throws URISyntaxException { PublicResourceHandler handler = new PublicResourceHandler(); URL resourceUrl = handler.getResourceUrl("VISIBLE"); assertNotNull(resourceUrl); Path visibleFile = Paths.get(resourceUrl.toURI()); assertNotNull(visibleFile); Path basePath = visibleFile.getParent(); URL url = handler.getResourceUrl("../HIDDEN"); assertNotNull(url); assertTrue("Path traversal security issue", Paths.get(url.toURI()).startsWith(basePath)); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void publicResourceHandlerTest() throws URISyntaxException { PublicResourceHandler handler = new PublicResourceHandler(); URL resourceUrl = handler.getResourceUrl("VISIBLE"); assertNotNull(resourceUrl); Path visibleFile = Paths.get(resourceUrl.toURI()); assertNotNull(visibleFile); URL url = handler.getResourceUrl("../HIDDEN"); assertNull(url); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String injectVersion(String resourcePath) { URL resourceUrl = getResourceUrl(resourcePath); try { long lastModified = resourceUrl.openConnection().getLastModified(); // check for extension int extensionAt = resourcePath.lastIndexOf('.'); StringBuilder versionedResourcePath = new StringBuilder(); if (extensionAt == -1) { versionedResourcePath.append(resourcePath); versionedResourcePath.append("-ver-").append(lastModified); } else { versionedResourcePath.append(resourcePath.substring(0, extensionAt)); versionedResourcePath.append("-ver-").append(lastModified); versionedResourcePath.append(resourcePath.substring(extensionAt, resourcePath.length())); } log.trace("Inject version in resource path: '{}' => '{}'", resourcePath, versionedResourcePath); return versionedResourcePath.toString(); } catch (IOException e) { throw new PippoRuntimeException("Failed to read lastModified property for {}", e, resourceUrl); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public String injectVersion(String resourcePath) { String version = getResourceVersion(resourcePath); if (StringUtils.isNullOrEmpty(version)) { // unversioned, pass-through resource path return resourcePath; } // check for extension int extensionAt = resourcePath.lastIndexOf('.'); StringBuilder versionedResourcePath = new StringBuilder(); if (extensionAt == -1) { versionedResourcePath.append(resourcePath); versionedResourcePath.append("-ver-").append(version); } else { versionedResourcePath.append(resourcePath.substring(0, extensionAt)); versionedResourcePath.append("-ver-").append(version); versionedResourcePath.append(resourcePath.substring(extensionAt, resourcePath.length())); } log.trace("Inject version in resource path: '{}' => '{}'", resourcePath, versionedResourcePath); return versionedResourcePath.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code String buildRealData(final ConditionZkDTO condition, final ServerWebExchange exchange) { String realData = ""; if (condition.getParamType().equals(ParamTypeEnum.QUERY.getName())) { final MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); realData = queryParams.getFirst(condition.getParamName()); } else if (Objects.equals(ParamTypeEnum.HOST.getName(), condition.getParamType())) { realData = exchange.getRequest().getRemoteAddress().getHostString(); } else if (Objects.equals(ParamTypeEnum.IP.getName(), condition.getParamType())) { realData = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress(); } else if (Objects.equals(ParamTypeEnum.HEADER.getName(), condition.getParamType())) { final HttpHeaders headers = exchange.getRequest().getHeaders(); final List<String> list = headers.get(condition.getParamName()); if (CollectionUtils.isEmpty(list)) { return realData; } realData = headers.get(condition.getParamName()).stream().findFirst().orElse(""); } return realData; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code String buildRealData(final ConditionZkDTO condition, final ServerWebExchange exchange) { String realData = ""; if (condition.getParamType().equals(ParamTypeEnum.QUERY.getName())) { final MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); realData = queryParams.getFirst(condition.getParamName()); } else if (Objects.equals(ParamTypeEnum.HOST.getName(), condition.getParamType())) { realData = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getHostString(); } else if (Objects.equals(ParamTypeEnum.IP.getName(), condition.getParamType())) { realData = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress(); } else if (Objects.equals(ParamTypeEnum.HEADER.getName(), condition.getParamType())) { final HttpHeaders headers = exchange.getRequest().getHeaders(); final List<String> list = headers.get(condition.getParamName()); if (CollectionUtils.isEmpty(list)) { return realData; } realData = Objects.requireNonNull(headers.get(condition.getParamName())).stream().findFirst().orElse(""); } return realData; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void roundRobinLoadBalanceTest() { List<DivideUpstream> divideUpstreamList = Arrays.asList(50, 20, 30).stream() .map(weight -> { DivideUpstream divideUpstream = new DivideUpstream(); divideUpstream.setUpstreamUrl("divide-upstream-" + weight); divideUpstream.setWeight(weight); return divideUpstream; }) .collect(Collectors.toList()); RoundRobinLoadBalance roundRobinLoadBalance = new RoundRobinLoadBalance(); Map<String, Integer> countMap = new HashMap<>(); for(int i=0; i<100; i++) { DivideUpstream result = roundRobinLoadBalance.select(divideUpstreamList, ""); int count = countMap.getOrDefault(result.getUpstreamUrl(), 0); countMap.put(result.getUpstreamUrl(), ++count); } Assert.assertEquals(50, countMap.get("divide-upstream-50").intValue()); } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void roundRobinLoadBalanceTest() { List<DivideUpstream> divideUpstreamList = Stream.of(50, 20, 30) .map(weight -> { DivideUpstream divideUpstream = new DivideUpstream(); divideUpstream.setUpstreamUrl("divide-upstream-" + weight); divideUpstream.setWeight(weight); return divideUpstream; }) .collect(Collectors.toList()); RoundRobinLoadBalance roundRobinLoadBalance = new RoundRobinLoadBalance(); Map<String, Integer> countMap = new HashMap<>(); for (int i = 0; i < 120; i++) { DivideUpstream result = roundRobinLoadBalance.select(divideUpstreamList, ""); int count = countMap.getOrDefault(result.getUpstreamUrl(), 0); countMap.put(result.getUpstreamUrl(), ++count); } Assert.assertEquals(50, countMap.get("divide-upstream-50").intValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } int port; InetSocketAddress socket; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); socket = new InetSocketAddress(args[0], port); file = args[2]; } else { port = Integer.parseInt(args[0]); socket = new InetSocketAddress(port); file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); pool.setMaxThreads(10); pool.setName("jmx_exporter"); server = new Server(pool); ServerConnector cnx = new ServerConnector(server); cnx.setReuseAddress(true); cnx.setHost(socket.getHostName()); cnx.setPort(port); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addFilter(GzipFilter.class, "/*", null); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); } #location 34 #vulnerability type RESOURCE_LEAK
#fixed code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } String host; int port; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); host = args[0]; file = args[2]; } else { port = Integer.parseInt(args[0]); host = "0.0.0.0"; file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); pool.setMaxThreads(10); pool.setName("jmx_exporter"); server = new Server(pool); ServerConnector connector = new ServerConnector(server); connector.setReuseAddress(true); connector.setHost(host); connector.setPort(port); server.setConnectors(new Connector[]{connector}); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addFilter(GzipFilter.class, "/*", null); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void agentLoads() throws IOException, InterruptedException { // If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually. final String buildDirectory = (String) System.getProperties().get("buildDirectory"); final String finalName = (String) System.getProperties().get("finalName"); final int port = Integer.parseInt((String) System.getProperties().get("it.port")); final String config = getClass().getClassLoader().getResource("test.yml").getFile(); final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config; final String javaHome = System.getenv("JAVA_HOME"); final String java; if (javaHome != null && javaHome.equals("")) { java = javaHome + "/bin/java"; } else { java = "java"; } final Process app = new ProcessBuilder() .command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication") .start(); try { // Wait for application to start app.getInputStream().read(); InputStream stream = new URL("http://localhost:" + port + "/metrics").openStream(); BufferedReader contents = new BufferedReader(new InputStreamReader(stream)); boolean found = false; while (!found) { String line = contents.readLine(); if (line == null) { break; } if (line.contains("jmx_scrape_duration_seconds")) { found = true; } } assertThat("Expected metric not found", found); // Tell application to stop app.getOutputStream().write('\n'); try { app.getOutputStream().flush(); } catch (IOException ignored) { } } finally { final int exitcode = app.waitFor(); // Log any errors printed int len; byte[] buffer = new byte[100]; while ((len = app.getErrorStream().read(buffer)) != -1) { System.out.write(buffer, 0, len); } assertThat("Application did not exit cleanly", exitcode == 0); } } #location 47 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void agentLoads() throws IOException, InterruptedException { // If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually. final String buildDirectory = (String) System.getProperties().get("buildDirectory"); final String finalName = (String) System.getProperties().get("finalName"); final int port = Integer.parseInt((String) System.getProperties().get("it.port")); final String config = getClass().getClassLoader().getResource("test.yml").getFile(); final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config; final String javaHome = System.getenv("JAVA_HOME"); final String java; if (javaHome != null && javaHome.equals("")) { java = javaHome + "/bin/java"; } else { java = "java"; } final Process app = new ProcessBuilder() .command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication") .start(); try { // Wait for application to start app.getInputStream().read(); URL uri = new URL("http://localhost:" + port + "/metrics"); HttpURLConnection cnx = (HttpURLConnection) uri.openConnection(); InputStream stream = cnx.getInputStream(); BufferedReader contents = new BufferedReader(new InputStreamReader(stream)); boolean found = false; while (!found) { String line = contents.readLine(); if (line == null) { break; } if (line.contains("jmx_scrape_duration_seconds")) { found = true; } } assertThat("Expected metric not found", found); // Tell application to stop cnx.disconnect(); app.getOutputStream().write('\n'); try { app.getOutputStream().flush(); } catch (IOException ignored) { } } catch (Throwable ex) { assertThat("Expection caught during scraping", false); ex.printStackTrace(); } finally { final int exitcode = app.waitFor(); // Log any errors printed int len; byte[] buffer = new byte[100]; while ((len = app.getErrorStream().read(buffer)) != -1) { System.out.write(buffer, 0, len); } assertThat("Application did not exit cleanly", exitcode == 0); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: WebServer <port> <yaml configuration file>"); System.exit(1); } JmxCollector jc = new JmxCollector(new FileReader(args[1])).register(); int port = Integer.parseInt(args[0]); Server server = new Server(port); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); server.join(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: WebServer <port> <yaml configuration file>"); System.exit(1); } JmxCollector jc = new JmxCollector(new File(args[1])).register(); int port = Integer.parseInt(args[0]); Server server = new Server(port); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); server.join(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void agentLoads() throws IOException, InterruptedException { // If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually. final String buildDirectory = (String) System.getProperties().get("buildDirectory"); final String finalName = (String) System.getProperties().get("finalName"); final int port = Integer.parseInt((String) System.getProperties().get("it.port")); final String config = getClass().getClassLoader().getResource("test.yml").getFile(); final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config; final String javaHome = System.getenv("JAVA_HOME"); final String java; if (javaHome != null && javaHome.equals("")) { java = javaHome + "/bin/java"; } else { java = "java"; } final Process app = new ProcessBuilder() .command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication") .start(); try { // Wait for application to start app.getInputStream().read(); InputStream stream = new URL("http://localhost:" + port + "/metrics").openStream(); BufferedReader contents = new BufferedReader(new InputStreamReader(stream)); boolean found = false; while (!found) { String line = contents.readLine(); if (line == null) { break; } if (line.contains("jmx_scrape_duration_seconds")) { found = true; } } assertThat("Expected metric not found", found); // Tell application to stop app.getOutputStream().write('\n'); try { app.getOutputStream().flush(); } catch (IOException ignored) { } } finally { final int exitcode = app.waitFor(); // Log any errors printed int len; byte[] buffer = new byte[100]; while ((len = app.getErrorStream().read(buffer)) != -1) { System.out.write(buffer, 0, len); } assertThat("Application did not exit cleanly", exitcode == 0); } } #location 28 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void agentLoads() throws IOException, InterruptedException { // If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually. final String buildDirectory = (String) System.getProperties().get("buildDirectory"); final String finalName = (String) System.getProperties().get("finalName"); final int port = Integer.parseInt((String) System.getProperties().get("it.port")); final String config = getClass().getClassLoader().getResource("test.yml").getFile(); final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config; final String javaHome = System.getenv("JAVA_HOME"); final String java; if (javaHome != null && javaHome.equals("")) { java = javaHome + "/bin/java"; } else { java = "java"; } final Process app = new ProcessBuilder() .command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication") .start(); try { // Wait for application to start app.getInputStream().read(); URL uri = new URL("http://localhost:" + port + "/metrics"); HttpURLConnection cnx = (HttpURLConnection) uri.openConnection(); InputStream stream = cnx.getInputStream(); BufferedReader contents = new BufferedReader(new InputStreamReader(stream)); boolean found = false; while (!found) { String line = contents.readLine(); if (line == null) { break; } if (line.contains("jmx_scrape_duration_seconds")) { found = true; } } assertThat("Expected metric not found", found); // Tell application to stop cnx.disconnect(); app.getOutputStream().write('\n'); try { app.getOutputStream().flush(); } catch (IOException ignored) { } } catch (Throwable ex) { assertThat("Expection caught during scraping", false); ex.printStackTrace(); } finally { final int exitcode = app.waitFor(); // Log any errors printed int len; byte[] buffer = new byte[100]; while ((len = app.getErrorStream().read(buffer)) != -1) { System.out.write(buffer, 0, len); } assertThat("Application did not exit cleanly", exitcode == 0); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void agentLoads() throws IOException, InterruptedException { // If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually. final String buildDirectory = (String) System.getProperties().get("buildDirectory"); final String finalName = (String) System.getProperties().get("finalName"); final int port = Integer.parseInt((String) System.getProperties().get("it.port")); final String config = resolveRelativePathToResource("test.yml"); final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config; final String javaHome = System.getenv("JAVA_HOME"); final String java; if (javaHome != null && javaHome.equals("")) { java = javaHome + "/bin/java"; } else { java = "java"; } final Process app = new ProcessBuilder() .command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication") .start(); try { // Wait for application to start app.getInputStream().read(); InputStream stream = new URL("http://localhost:" + port + "/metrics").openStream(); BufferedReader contents = new BufferedReader(new InputStreamReader(stream)); boolean found = false; while (!found) { String line = contents.readLine(); if (line == null) { break; } if (line.contains("jmx_scrape_duration_seconds")) { found = true; } } assertThat("Expected metric not found", found); // Tell application to stop app.getOutputStream().write('\n'); try { app.getOutputStream().flush(); } catch (IOException ignored) { } } finally { final int exitcode = app.waitFor(); // Log any errors printed int len; byte[] buffer = new byte[100]; while ((len = app.getErrorStream().read(buffer)) != -1) { System.out.write(buffer, 0, len); } assertThat("Application did not exit cleanly", exitcode == 0); } } #location 28 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void agentLoads() throws IOException, InterruptedException { // If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually. final String buildDirectory = (String) System.getProperties().get("buildDirectory"); final String finalName = (String) System.getProperties().get("finalName"); final int port = Integer.parseInt((String) System.getProperties().get("it.port")); final String config = resolveRelativePathToResource("test.yml"); final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config; final String java = buildJavaPath(System.getenv("JAVA_HOME")); final Process app = new ProcessBuilder() .command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication") .start(); try { // Wait for application to start app.getInputStream().read(); InputStream stream = new URL("http://localhost:" + port + "/metrics").openStream(); BufferedReader contents = new BufferedReader(new InputStreamReader(stream)); boolean found = false; while (!found) { String line = contents.readLine(); if (line == null) { break; } if (line.contains("jmx_scrape_duration_seconds")) { found = true; } } assertThat("Expected metric not found", found); // Tell application to stop app.getOutputStream().write('\n'); try { app.getOutputStream().flush(); } catch (IOException ignored) { } } finally { final int exitcode = app.waitFor(); // Log any errors printed int len; byte[] buffer = new byte[100]; while ((len = app.getErrorStream().read(buffer)) != -1) { System.out.write(buffer, 0, len); } assertThat("Application did not exit cleanly", exitcode == 0); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } String host; int port; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); host = args[0]; file = args[2]; } else { port = Integer.parseInt(args[0]); host = "0.0.0.0"; file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); pool.setMaxThreads(10); pool.setName("jmx_exporter"); server = new Server(pool); ServerConnector connector = new ServerConnector(server); connector.setReuseAddress(true); connector.setHost(host); connector.setPort(port); server.setConnectors(new Connector[]{connector}); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addFilter(GzipFilter.class, "/*", null); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); } #location 35 #vulnerability type RESOURCE_LEAK
#fixed code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } int port; InetSocketAddress socket; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); socket = new InetSocketAddress(args[0], port); file = args[2]; } else { port = Integer.parseInt(args[0]); socket = new InetSocketAddress(port); file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); server = new Server(); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); pool.setMaxThreads(10); pool.setMaxQueued(10); pool.setName("jmx_exporter"); server.setThreadPool(pool); SelectChannelConnector connector = new SelectChannelConnector(); connector.setHost(socket.getHostName()); connector.setPort(socket.getPort()); connector.setAcceptors(1); server.addConnector(connector); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } int port; InetSocketAddress socket; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); socket = new InetSocketAddress(args[0], port); file = args[2]; } else { port = Integer.parseInt(args[0]); socket = new InetSocketAddress(port); file = args[1]; } new JmxCollector(new FileReader(file)).register(); DefaultExports.initialize(); server = new Server(socket); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); server.setThreadPool(pool); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } int port; InetSocketAddress socket; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); socket = new InetSocketAddress(args[0], port); file = args[2]; } else { port = Integer.parseInt(args[0]); socket = new InetSocketAddress(port); file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); server = new Server(socket); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); server.setThreadPool(pool); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @BeforeClass public static void beforeClass() { for (File file : customFileLog("").listFiles()) { if (file.getPath().contains("tracer-self.log") || file.getPath().contains("sync.log") || file.getPath().contains("rpc-profile.log") || file.getPath().contains("middleware_error.log")) { continue; } FileUtils.deleteQuietly(file); } } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @BeforeClass public static void beforeClass() { File[] traceFiles = customFileLog("").listFiles(); if (traceFiles == null) { return; } for (File file : traceFiles) { if (file.getPath().contains("tracer-self.log") || file.getPath().contains("sync.log") || file.getPath().contains("rpc-profile.log") || file.getPath().contains("middleware_error.log")) { continue; } FileUtils.deleteQuietly(file); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected Map<String, Object> customSettingsFlat() { return ImmutableMap.<String, Object>builder() .put(HTTP_INCOMING_AUTH_TYPE, IlpOverHttpLinkSettings.AuthType.JWT_HS_256.name()) .put(HTTP_INCOMING_TOKEN_ISSUER, "https://incoming-issuer.example.com/") .put(HTTP_INCOMING_SHARED_SECRET, "incoming-credential") .put(HTTP_INCOMING_TOKEN_AUDIENCE, "https://incoming-audience.example.com/") .put(HTTP_OUTGOING_AUTH_TYPE, IlpOverHttpLinkSettings.AuthType.SIMPLE.name()) .put(HTTP_OUTGOING_TOKEN_SUBJECT, "outgoing-subject") .put(HTTP_OUTGOING_SHARED_SECRET, "outgoing-credential") .put(HTTP_OUTGOING_TOKEN_ISSUER, "https://outgoing-issuer.example.com/") .put(HTTP_OUTGOING_TOKEN_AUDIENCE, "https://outgoing-audience.example.com/") .put(HTTP_OUTGOING_TOKEN_EXPIRY, Duration.ofDays(1).toString()) .put(HTTP_OUTGOING_URL, "https://outgoing.example.com") .build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
#fixed code protected Map<String, Object> customSettingsFlat() { return customSettingsFlat(IlpOverHttpLinkSettings.AuthType.JWT_HS_256, IlpOverHttpLinkSettings.AuthType.JWT_HS_256); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Node<S> next() { // Take the next node from the stack. Node<S> current = popUnvisited(); // Take the associated state S currentState = current.transition().to(); // Explore the adjacent neighbors for(Transition<S> successor : this.successors.from(currentState)){ // If the neighbor is still unexplored if (!this.visited.containsKey(successor.to())){ // Create the associated neighbor Node<S> successorNode = factory.node(current, successor); this.stack.push(successorNode); } } this.visited.put(currentState, current); return current; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public Node<S> next(){ if (next != null){ Node<S> e = next; next = nextUnvisited(); return e; } else { return nextUnvisited(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public GraphEdge<V,E> connect(V v1, V v2, E value){ //check input if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> edgeReverse = new GraphEdge<V, E>(v2, v1, value); //add edges to the graph (if not present before) connected.get(v1).add(edge); connected.get(v2).add(edgeReverse); return edge; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public GraphEdge<V,E> connect(V v1, V v2, E value){ // Check non-null arguments if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); // Ensure that the vertices are in the graph add(v1); add(v2); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> reversedEdge = new GraphEdge<V, E>(v2, v1, value); // Add edges to the graph connected.get(v1).add(edge); connected.get(v2).add(reversedEdge); return edge; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test() { String[] testMaze = { "XX@XXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "XX XXXXXXXXXXXXX XXXXXXXXXXX", "XX XXXXXXXXXX XXX XX XXXX", "XXXXX XXXXXX XXX XX XXX XXXX", "XXX XX XXXXXX XX XXX XX XX XXXX", "XXX XXXXX XXXXXX XXXXXX XXXX", "XXXXXXX XXXXXX XXXX", "XXXXXXXXXX XXXXX XXXXXXXXXXXXXXX", "XXXXXXXXXX XX XXXXX XXXX", "XXXXXXXXXX XXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXX XXXX", "XXXXXXXXXXXXXXXXXXXXXXXX XX XXXX", "XXXXXX XXXX XX XXXX", "XXXXXX XXXXXXXXXXXX XX XXXX", "XXXXXX XXO XXXXXX XXXX XXXXXXX", "XXXXXX XXXXX XXX XX", "XXXXXX XXXXXXX XXXXXXXXXXX XXXXX", "XXXXXX XXXXXXX XXXXXXXXXXXXXXXXX", "XXXXXX XXXXXXXXXXXXXX"}; StringMaze maze = new StringMaze(testMaze); // Valid cells assertTrue(maze.getMaze()[1][2]); assertTrue(maze.getMaze()[0][2]); assertTrue(maze.getMaze()[5][4]); // Invalid cells assertFalse(maze.getMaze()[0][0]); assertFalse(maze.getMaze()[1][1]); assertFalse(maze.getMaze()[5][12]); // Initial loc assertEquals(maze.getInitialLoc(), new Point(2, 0)); assertEquals(maze.getGoalLoc(), new Point(9, 15)); // Print valid moves from initial and goal System.out.println(maze.validLocationsFrom(maze.getInitialLoc())); System.out.println(maze.validLocationsFrom(maze.getGoalLoc())); System.out.println(maze.validLocationsFrom(new Point(14, 3))); } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void test() { String[] testMaze = { "XX@XXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "XX XXXXXXXXXXXXX XXXXXXXXXXX", "XX XXXXXXXXXX XXX XX XXXX", "XXXXX XXXXXX XXX XX XXX XXXX", "XXX XX XXXXXX XX XXX XX XX XXXX", "XXX XXXXX XXXXXX XXXXXX XXXX", "XXXXXXX XXXXXX XXXX", "XXXXXXXXXX XXXXX XXXXXXXXXXXXXXX", "XXXXXXXXXX XX XXXXX XXXX", "XXXXXXXXXX XXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXX XXXX", "XXXXXXXXXXXXXXXXXXXXXXXX XX XXXX", "XXXXXX XXXX XX XXXX", "XXXXXX XXXXXXXXXXXX XX XXXX", "XXXXXX XXO XXXXXX XXXX XXXXXXX", "XXXXXX XXXXX XXX XX", "XXXXXX XXXXXXX XXXXXXXXXXX XXXXX", "XXXXXX XXXXXXX XXXXXXXXXXXXXXXXX", "XXXXXX XXXXXXXXXXXXXX"}; StringMaze maze = new StringMaze(testMaze); // Valid cells assertTrue(maze.validLocation(new Point(2,1))); assertTrue(maze.validLocation(new Point(2,0))); assertTrue(maze.validLocation(new Point(4,5))); // Invalid cells assertTrue(!maze.validLocation(new Point(0,0))); assertTrue(!maze.validLocation(new Point(1,1))); assertTrue(!maze.validLocation(new Point(12,5))); // Initial loc assertEquals(maze.getInitialLoc(), new Point(2, 0)); assertEquals(maze.getGoalLoc(), new Point(9, 15)); // Print valid moves from initial and goal System.out.println(maze.validLocationsFrom(maze.getInitialLoc())); System.out.println(maze.validLocationsFrom(maze.getGoalLoc())); System.out.println(maze.validLocationsFrom(new Point(14, 3))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public GraphEdge<V,E> connect(V v1, V v2, E value){ //check input if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> edgeReverse = new GraphEdge<V, E>(v2, v1, value); //add edges to the graph (if not present before) connected.get(v1).add(edge); connected.get(v2).add(edgeReverse); return edge; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public GraphEdge<V,E> connect(V v1, V v2, E value){ // Check non-null arguments if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); // Ensure that the vertices are in the graph add(v1); add(v2); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> reversedEdge = new GraphEdge<V, E>(v2, v1, value); // Add edges to the graph connected.get(v1).add(edge); connected.get(v2).add(reversedEdge); return edge; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void benchmark() throws InterruptedException { System.out.println("Maze | Hipster-Dijkstra (ms) | JUNG-Dijkstra (ms)"); System.out.println("-------------------------------------------------"); final int times = 5; for (int i = 10; i < 300; i += 10) { Maze2D maze = Maze2D.random(i, 0.9); // Repeat 5 times //Double mean1 = 0d, mean2 = 0d; double min2 = Double.MAX_VALUE, min1 = Double.MAX_VALUE; DirectedGraph<Point, JungEdge<Point>> graph = JungDirectedGraphFromMazeCreator.create(maze); for (int j = 0; j < times; j++) { //AStar<Point> it = AStarIteratorFromMazeCreator.create(maze, false); AStar<Point> it = AlgorithmIteratorFromMazeCreator.astar(maze, false); Stopwatch w1 = new Stopwatch().start(); MazeSearch.Result resultJung = MazeSearch.executeJungSearch(graph, maze); //In case there is no possible result in the random maze if(resultJung.equals(MazeSearch.Result.NO_RESULT)){ maze = Maze2D.random(i, 0.9); graph = JungDirectedGraphFromMazeCreator.create(maze); j--; continue; } long result1 = w1.stop().elapsed(TimeUnit.MILLISECONDS); if (result1 < min1) { min1 = result1; } Stopwatch w2 = new Stopwatch().start(); MazeSearch.Result resultIterator = MazeSearch.executeIteratorSearch(it, maze); long result2 = w2.stop().elapsed(TimeUnit.MILLISECONDS); if (result2 < min2) { min2 = result2; } assertEquals(resultIterator.getCost(), resultJung.getCost(), 0.001); } System.out.println(String.format("%d \t\t %.5g \t\t %.5g", i, min2, min1)); } } #location 34 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void benchmark() throws InterruptedException { Benchmark bench = new Benchmark(); // Hipster-Dijkstra bench.add("Hipster-Dijkstra", new Algorithm() { AStar<Point> it; Maze2D maze; public void initialize(Maze2D maze) { it= AlgorithmIteratorFromMazeCreator.astar(maze, false); this.maze = maze; } public Result evaluate() { return MazeSearch.executeIteratorSearch(it, maze); } }); // JUNG-Dijkstra bench.add("JUNG-Dijkstra", new Algorithm() { Maze2D maze;DirectedGraph<Point, JungEdge<Point>> graph; public void initialize(Maze2D maze) { this.maze = maze; this.graph = JungDirectedGraphFromMazeCreator.create(maze); } public Result evaluate() { return MazeSearch.executeJungSearch(graph, maze); } }); int index = 0; for(String algName : bench.algorithms.keySet()){ System.out.println((++index) + " = " + algName); } for (int i = 10; i < 300; i += 10) { Maze2D maze = Maze2D.empty(i); // Test over an empty maze Map<String, Benchmark.Score> results = bench.run(maze); // Check results and print scores. We take JUNG as baseline Benchmark.Score jungScore = results.get("JUNG-Dijkstra"); String scores = ""; for(String algName : bench.algorithms.keySet()){ Benchmark.Score score = results.get(algName); assertEquals(jungScore.result.getCost(),score.result.getCost(), 0.0001); scores += score.time + " ms\t"; } System.out.println(scores); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRestartAuditorBookieAfterCrashing() throws Exception { BookieServer auditor = verifyAuditor(); shudownBookie(auditor); // restarting Bookie with same configurations. int indexOfDownBookie = bs.indexOf(auditor); ServerConfiguration serverConfiguration = bsConfs .get(indexOfDownBookie); bs.remove(indexOfDownBookie); bsConfs.remove(indexOfDownBookie); tmpDirs.remove(indexOfDownBookie); startBookie(serverConfiguration); // starting corresponding auditor elector StringBuilder sb = new StringBuilder(); StringUtils.addrToString(sb, auditor.getLocalAddress()); LOG.debug("Performing Auditor Election:" + sb.toString()); auditorElectors.get(sb.toString()).doElection(); // waiting for new auditor to come BookieServer newAuditor = waitForNewAuditor(auditor); Assert.assertNotSame( "Auditor re-election is not happened for auditor failure!", auditor, newAuditor); Assert.assertFalse("No relection after old auditor rejoins", auditor .getLocalAddress().getPort() == newAuditor.getLocalAddress() .getPort()); } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRestartAuditorBookieAfterCrashing() throws Exception { BookieServer auditor = verifyAuditor(); shudownBookie(auditor); // restarting Bookie with same configurations. int indexOfDownBookie = bs.indexOf(auditor); ServerConfiguration serverConfiguration = bsConfs .get(indexOfDownBookie); bs.remove(indexOfDownBookie); bsConfs.remove(indexOfDownBookie); tmpDirs.remove(indexOfDownBookie); startBookie(serverConfiguration); // starting corresponding auditor elector String addr = StringUtils.addrToString(auditor.getLocalAddress()); LOG.debug("Performing Auditor Election:" + addr); auditorElectors.get(addr).doElection(); // waiting for new auditor to come BookieServer newAuditor = waitForNewAuditor(auditor); Assert.assertNotSame( "Auditor re-election is not happened for auditor failure!", auditor, newAuditor); Assert.assertFalse("No relection after old auditor rejoins", auditor .getLocalAddress().getPort() == newAuditor.getLocalAddress() .getPort()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void handleSubscribeMessage(PubSubResponse response) { if (logger.isDebugEnabled()) logger.debug("Handling a Subscribe message in response: " + response + ", topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); Message message = response.getMessage(); synchronized (this) { // Consume the message asynchronously that the client is subscribed // to. Do this only if delivery for the subscription has started and // a MessageHandler has been registered for the TopicSubscriber. if (messageHandler != null) { asyncMessageConsume(message); } else { // MessageHandler has not yet been registered so queue up these // messages for the Topic Subscription. Make the initial lazy // creation of the message queue thread safe just so we don't // run into a race condition where two simultaneous threads process // a received message and both try to create a new instance of // the message queue. Performance overhead should be okay // because the delivery of the topic has not even started yet // so these messages are not consumed and just buffered up here. if (subscribeMsgQueue == null) subscribeMsgQueue = new LinkedList<Message>(); if (logger.isDebugEnabled()) logger .debug("Message has arrived but Subscribe channel does not have a registered MessageHandler yet so queueing up the message: " + message); subscribeMsgQueue.add(message); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void handleSubscribeMessage(PubSubResponse response) { if (logger.isDebugEnabled()) { logger.debug("Handling a Subscribe message in response: {}, topic: {}, subscriberId: {}", new Object[] { response, getOrigSubData().topic.toStringUtf8(), getOrigSubData().subscriberId.toStringUtf8() }); } Message message = response.getMessage(); synchronized (this) { // Consume the message asynchronously that the client is subscribed // to. Do this only if delivery for the subscription has started and // a MessageHandler has been registered for the TopicSubscriber. if (messageHandler != null) { asyncMessageConsume(message); } else { // MessageHandler has not yet been registered so queue up these // messages for the Topic Subscription. Make the initial lazy // creation of the message queue thread safe just so we don't // run into a race condition where two simultaneous threads process // a received message and both try to create a new instance of // the message queue. Performance overhead should be okay // because the delivery of the topic has not even started yet // so these messages are not consumed and just buffered up here. if (subscribeMsgQueue == null) subscribeMsgQueue = new LinkedList<Message>(); if (logger.isDebugEnabled()) logger .debug("Message has arrived but Subscribe channel does not have a registered MessageHandler yet so queueing up the message: " + message); subscribeMsgQueue.add(message); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void close() { synchronized (this) { state = ConnectionState.DISCONNECTED; } if (channel != null) { channel.close().awaitUninterruptibly(); } if (readTimeoutTimer != null) { readTimeoutTimer.stop(); readTimeoutTimer = null; } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void close() { closeInternal(true); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { while (running) { synchronized (this) { try { wait(gcWaitTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); continue; } } // Dependency check. if (null == zk) { continue; } // Extract all of the ledger ID's that comprise all of the entry logs // (except for the current new one which is still being written to). try { entryLogMetaMap = entryLogger.extractMetaFromEntryLogs(entryLogMetaMap); } catch (IOException ie) { LOG.warn("Exception when extracting entry log meta from entry logs : ", ie); } // gc inactive/deleted ledgers doGcLedgers(); // gc entry logs doGcEntryLogs(); long curTime = System.currentTimeMillis(); if (enableMajorCompaction && curTime - lastMajorCompactionTime > majorCompactionInterval) { // enter major compaction LOG.info("Enter major compaction"); doCompactEntryLogs(majorCompactionThreshold); lastMajorCompactionTime = System.currentTimeMillis(); // also move minor compaction time lastMinorCompactionTime = lastMajorCompactionTime; continue; } if (enableMinorCompaction && curTime - lastMinorCompactionTime > minorCompactionInterval) { // enter minor compaction LOG.info("Enter minor compaction"); doCompactEntryLogs(minorCompactionThreshold); lastMinorCompactionTime = System.currentTimeMillis(); } } } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { while (running) { synchronized (this) { try { wait(gcWaitTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); continue; } } // Dependency check. if (null == zk) { continue; } // Extract all of the ledger ID's that comprise all of the entry logs // (except for the current new one which is still being written to). try { entryLogMetaMap = extractMetaFromEntryLogs(entryLogMetaMap); } catch (IOException ie) { LOG.warn("Exception when extracting entry log meta from entry logs : ", ie); } // gc inactive/deleted ledgers doGcLedgers(); // gc entry logs doGcEntryLogs(); long curTime = System.currentTimeMillis(); if (enableMajorCompaction && curTime - lastMajorCompactionTime > majorCompactionInterval) { // enter major compaction LOG.info("Enter major compaction"); doCompactEntryLogs(majorCompactionThreshold); lastMajorCompactionTime = System.currentTimeMillis(); // also move minor compaction time lastMinorCompactionTime = lastMajorCompactionTime; continue; } if (enableMinorCompaction && curTime - lastMinorCompactionTime > minorCompactionInterval) { // enter minor compaction LOG.info("Enter minor compaction"); doCompactEntryLogs(minorCompactionThreshold); lastMinorCompactionTime = System.currentTimeMillis(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public byte[] readMasterKey(long ledgerId) throws IOException, BookieException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledgerId); if (fi == null) { File lf = findIndexFile(ledgerId); if (lf == null) { throw new Bookie.NoLedgerException(ledgerId); } if (openLedgers.size() > openFileLimit) { fileInfoCache.remove(openLedgers.removeFirst()).close(); } fi = new FileInfo(lf, null); byte[] key = fi.getMasterKey(); fileInfoCache.put(ledgerId, fi); openLedgers.add(ledgerId); return key; } return fi.getMasterKey(); } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public byte[] readMasterKey(long ledgerId) throws IOException, BookieException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledgerId); if (fi == null) { File lf = findIndexFile(ledgerId); if (lf == null) { throw new Bookie.NoLedgerException(ledgerId); } evictFileInfoIfNecessary(); fi = new FileInfo(lf, null); byte[] key = fi.getMasterKey(); fileInfoCache.put(ledgerId, fi); openLedgers.add(ledgerId); return key; } return fi.getMasterKey(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void writeIndexFileForLedger(File indexDir, long ledgerId, byte[] masterKey) throws Exception { File fn = new File(indexDir, LedgerCache.getLedgerName(ledgerId)); fn.getParentFile().mkdirs(); FileInfo fi = new FileInfo(fn); fi.writeMasterKey(masterKey); fi.close(); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code private void writeIndexFileForLedger(File indexDir, long ledgerId, byte[] masterKey) throws Exception { File fn = new File(indexDir, LedgerCache.getLedgerName(ledgerId)); fn.getParentFile().mkdirs(); FileInfo fi = new FileInfo(fn, masterKey); // force creation of index file fi.write(new ByteBuffer[]{ ByteBuffer.allocate(0) }, 0); fi.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { LOG.info("Disconnected from bookie: " + addr); errorOutOutstandingEntries(); channel.close(); state = ConnectionState.DISCONNECTED; // we don't want to reconnect right away. If someone sends a request to // this address, we will reconnect. } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { LOG.info("Disconnected from bookie: " + addr); errorOutOutstandingEntries(); channel.close(); synchronized (this) { state = ConnectionState.DISCONNECTED; } // we don't want to reconnect right away. If someone sends a request to // this address, we will reconnect. }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadWriteSyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); lh.addEntry(entry.array()); } lh.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); Integer origEntry = origbb.getInt(); ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testReadWriteSyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); lh.addEntry(entry.array()); } lh.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); Integer origEntry = origbb.getInt(); ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout=60000) public void testLastConfirmedAdd() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test(timeout=60000) public void testLastConfirmedAdd() throws Exception { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 48 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { SyncObj sync = new SyncObj(); LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void close() { synchronized (this) { state = ConnectionState.DISCONNECTED; } if (channel != null) { channel.close().awaitUninterruptibly(); } if (readTimeoutTimer != null) { readTimeoutTimer.stop(); readTimeoutTimer = null; } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void close() { closeInternal(true); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); ls = seq; synchronized (sync) { sync.value = true; sync.notify(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { SyncObj sync = (SyncObj) ctx; sync.setLedgerEntries(seq); sync.setReturnCode(rc); synchronized (sync) { sync.value = true; sync.notify(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public StatsLogger getStatsLogger(String name) { initIfNecessary(); return new CodahaleStatsLogger(metrics, name); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public StatsLogger getStatsLogger(String name) { initIfNecessary(); return new CodahaleStatsLogger(getMetrics(), name); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code FileInfo getFileInfo(Long ledger, byte masterKey[]) throws IOException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledger); if (fi == null) { File lf = findIndexFile(ledger); if (lf == null) { if (masterKey == null) { throw new Bookie.NoLedgerException(ledger); } File dir = pickDirs(ledgerDirectories); String ledgerName = getLedgerName(ledger); lf = new File(dir, ledgerName); // A new ledger index file has been created for this Bookie. // Add this new ledger to the set of active ledgers. if (LOG.isDebugEnabled()) { LOG.debug("New ledger index file created for ledgerId: " + ledger); } activeLedgerManager.addActiveLedger(ledger, true); } if (openLedgers.size() > openFileLimit) { fileInfoCache.remove(openLedgers.removeFirst()).close(); } fi = new FileInfo(lf, masterKey); fileInfoCache.put(ledger, fi); openLedgers.add(ledger); } if (fi != null) { fi.use(); } return fi; } } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code FileInfo getFileInfo(Long ledger, byte masterKey[]) throws IOException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledger); if (fi == null) { File lf = findIndexFile(ledger); if (lf == null) { if (masterKey == null) { throw new Bookie.NoLedgerException(ledger); } File dir = pickDirs(ledgerDirectories); String ledgerName = getLedgerName(ledger); lf = new File(dir, ledgerName); // A new ledger index file has been created for this Bookie. // Add this new ledger to the set of active ledgers. if (LOG.isDebugEnabled()) { LOG.debug("New ledger index file created for ledgerId: " + ledger); } activeLedgerManager.addActiveLedger(ledger, true); } evictFileInfoIfNecessary(); fi = new FileInfo(lf, masterKey); fileInfoCache.put(ledger, fi); openLedgers.add(ledger); } if (fi != null) { fi.use(); } return fi; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Latency min/avg/max: " + getMinLatency() + "/" + getAvgLatency() + "/" + getMaxLatency() + "\n"); sb.append("Received: " + getPacketsReceived() + "\n"); sb.append("Sent: " + getPacketsSent() + "\n"); if (provider != null) { sb.append("Outstanding: " + getOutstandingRequests() + "\n"); sb.append("Zxid: 0x" + Long.toHexString(getLastProcessedZxid()) + "\n"); } sb.append("Mode: " + getServerState() + "\n"); return sb.toString(); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Latency min/avg/max: " + getMinLatency() + "/" + getAvgLatency() + "/" + getMaxLatency() + "\n"); sb.append("Received: " + getPacketsReceived() + "\n"); sb.append("Sent: " + getPacketsSent() + "\n"); return sb.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void connectIfNeededAndDoOp(GenericCallback<Void> op) { boolean doOpNow; // common case without lock first if (channel != null && state == ConnectionState.CONNECTED) { doOpNow = true; } else { synchronized (this) { // check again under lock if (channel != null && state == ConnectionState.CONNECTED) { doOpNow = true; } else { // if reached here, channel is either null (first connection // attempt), // or the channel is disconnected doOpNow = false; // connection attempt is still in progress, queue up this // op. Op will be executed when connection attempt either // fails // or // succeeds pendingOps.add(op); connect(); } } } if (doOpNow) { op.operationComplete(BKException.Code.OK, null); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void connectIfNeededAndDoOp(GenericCallback<Void> op) { boolean doOpNow; synchronized (this) { if (channel != null && state == ConnectionState.CONNECTED) { doOpNow = true; } else { // if reached here, channel is either null (first connection // attempt), // or the channel is disconnected doOpNow = false; // connection attempt is still in progress, queue up this // op. Op will be executed when connection attempt either // fails // or // succeeds pendingOps.add(op); connect(); } } if (doOpNow) { op.operationComplete(BKException.Code.OK, null); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSimpleBookieLedgerMapping() throws Exception { LedgerManagerFactory newLedgerManagerFactory = LedgerManagerFactory .newLedgerManagerFactory(baseConf, zkc); LedgerManager ledgerManager = newLedgerManagerFactory .newLedgerManager(); List<Long> ledgerList = new ArrayList<Long>(3); LedgerHandle lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); Map<String, Set<Long>> bookieToLedgerIndex = bookieLedgerIndex .getBookieToLedgerIndex(); assertEquals("Missed few bookies in the bookie-ledger mapping!", 3, bookieToLedgerIndex.size()); Collection<Set<Long>> bk2ledgerEntry = bookieToLedgerIndex.values(); for (Set<Long> ledgers : bk2ledgerEntry) { assertEquals("Missed few ledgers in the bookie-ledger mapping!", 3, ledgers.size()); for (Long ledgerId : ledgers) { assertTrue("Unknown ledger-bookie mapping", ledgerList .contains(ledgerId)); } } } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSimpleBookieLedgerMapping() throws Exception { for (int i = 0; i < numberOfLedgers; i++) { createAndAddEntriesToLedger().close(); } BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); Map<String, Set<Long>> bookieToLedgerIndex = bookieLedgerIndex .getBookieToLedgerIndex(); assertEquals("Missed few bookies in the bookie-ledger mapping!", 3, bookieToLedgerIndex.size()); Collection<Set<Long>> bk2ledgerEntry = bookieToLedgerIndex.values(); for (Set<Long> ledgers : bk2ledgerEntry) { assertEquals("Missed few ledgers in the bookie-ledger mapping!", 3, ledgers.size()); for (Long ledgerId : ledgers) { assertTrue("Unknown ledger-bookie mapping", ledgerList .contains(ledgerId)); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadWriteZero() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); } /* * Write a non-zero entry */ ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); lh.addEntry(entry.array()); lh.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testReadWriteZero() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); } /* * Write a non-zero entry */ ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); lh.addEntry(entry.array()); lh.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void setMessageHandler(MessageHandler messageHandler) { if (logger.isDebugEnabled()) logger.debug("Setting the messageHandler for topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); synchronized (this) { this.messageHandler = messageHandler; // Once the MessageHandler is registered, see if we have any queued up // subscription messages sent to us already from the server. If so, // consume those first. Do this only if the MessageHandler registered is // not null (since that would be the HedwigSubscriber.stopDelivery // call). if (messageHandler != null && subscribeMsgQueue != null && subscribeMsgQueue.size() > 0) { if (logger.isDebugEnabled()) logger.debug("Consuming " + subscribeMsgQueue.size() + " queued up messages for topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); for (Message message : subscribeMsgQueue) { asyncMessageConsume(message); } // Now we can remove the queued up messages since they are all // consumed. subscribeMsgQueue.clear(); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void setMessageHandler(MessageHandler messageHandler) { if (logger.isDebugEnabled()) { logger.debug("Setting the messageHandler for topic: {}, subscriberId: {}", getOrigSubData().topic.toStringUtf8(), getOrigSubData().subscriberId.toStringUtf8()); } synchronized (this) { this.messageHandler = messageHandler; // Once the MessageHandler is registered, see if we have any queued up // subscription messages sent to us already from the server. If so, // consume those first. Do this only if the MessageHandler registered is // not null (since that would be the HedwigSubscriber.stopDelivery // call). if (messageHandler != null && subscribeMsgQueue != null && subscribeMsgQueue.size() > 0) { if (logger.isDebugEnabled()) logger.debug("Consuming " + subscribeMsgQueue.size() + " queued up messages for topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); for (Message message : subscribeMsgQueue) { asyncMessageConsume(message); } // Now we can remove the queued up messages since they are all // consumed. subscribeMsgQueue.clear(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); ls = seq; synchronized (sync) { sync.value = true; sync.notify(); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { SyncObj sync = (SyncObj) ctx; sync.setLedgerEntries(seq); sync.setReturnCode(rc); synchronized (sync) { sync.value = true; sync.notify(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadWriteAsyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 55 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testReadWriteAsyncSingleClient() throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; Enumeration<LedgerEntry> ls = sync.getLedgerEntries(); while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGarbageCollectLedgers() throws Exception { int numLedgers = 100; int numRemovedLedgers = 10; final Set<Long> createdLedgers = new HashSet<Long>(); final Set<Long> removedLedgers = new HashSet<Long>(); // create 100 ledgers createLedgers(numLedgers, createdLedgers); Random r = new Random(System.currentTimeMillis()); final List<Long> tmpList = new ArrayList<Long>(); tmpList.addAll(createdLedgers); Collections.shuffle(tmpList, r); // random remove several ledgers for (int i=0; i<numRemovedLedgers; i++) { long ledgerId = tmpList.get(i); getLedgerManager().deleteLedger(ledgerId, new GenericCallback<Void>() { @Override public void operationComplete(int rc, Void result) { synchronized (removedLedgers) { removedLedgers.notify(); } } }); synchronized (removedLedgers) { removedLedgers.wait(); } removedLedgers.add(ledgerId); createdLedgers.remove(ledgerId); } final CountDownLatch inGcProgress = new CountDownLatch(1); final CountDownLatch createLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(2); Thread gcThread = new Thread() { @Override public void run() { getActiveLedgerManager().garbageCollectLedgers(new GarbageCollector() { boolean paused = false; @Override public void gc(long ledgerId) { if (!paused) { inGcProgress.countDown(); try { createLatch.await(); } catch (InterruptedException ie) { } paused = true; } LOG.info("Garbage Collected ledger {}", ledgerId); } }); LOG.info("Gc Thread quits."); endLatch.countDown(); } }; Thread createThread = new Thread() { @Override public void run() { try { inGcProgress.await(); // create 10 more ledgers createLedgers(10, createdLedgers); LOG.info("Finished creating 10 more ledgers."); createLatch.countDown(); } catch (Exception e) { } LOG.info("Create Thread quits."); endLatch.countDown(); } }; createThread.start(); gcThread.start(); endLatch.await(); // test ledgers for (Long ledger : removedLedgers) { assertFalse(getActiveLedgerManager().containsActiveLedger(ledger)); } for (Long ledger : createdLedgers) { assertTrue(getActiveLedgerManager().containsActiveLedger(ledger)); } } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testGarbageCollectLedgers() throws Exception { int numLedgers = 100; int numRemovedLedgers = 10; final Set<Long> createdLedgers = new HashSet<Long>(); final Set<Long> removedLedgers = new HashSet<Long>(); // create 100 ledgers createLedgers(numLedgers, createdLedgers); Random r = new Random(System.currentTimeMillis()); final List<Long> tmpList = new ArrayList<Long>(); tmpList.addAll(createdLedgers); Collections.shuffle(tmpList, r); // random remove several ledgers for (int i=0; i<numRemovedLedgers; i++) { long ledgerId = tmpList.get(i); synchronized (removedLedgers) { getLedgerManager().deleteLedger(ledgerId, new GenericCallback<Void>() { @Override public void operationComplete(int rc, Void result) { synchronized (removedLedgers) { removedLedgers.notify(); } } }); removedLedgers.wait(); } removedLedgers.add(ledgerId); createdLedgers.remove(ledgerId); } final CountDownLatch inGcProgress = new CountDownLatch(1); final CountDownLatch createLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(2); Thread gcThread = new Thread() { @Override public void run() { getActiveLedgerManager().garbageCollectLedgers(new GarbageCollector() { boolean paused = false; @Override public void gc(long ledgerId) { if (!paused) { inGcProgress.countDown(); try { createLatch.await(); } catch (InterruptedException ie) { } paused = true; } LOG.info("Garbage Collected ledger {}", ledgerId); } }); LOG.info("Gc Thread quits."); endLatch.countDown(); } }; Thread createThread = new Thread() { @Override public void run() { try { inGcProgress.await(); // create 10 more ledgers createLedgers(10, createdLedgers); LOG.info("Finished creating 10 more ledgers."); createLatch.countDown(); } catch (Exception e) { } LOG.info("Create Thread quits."); endLatch.countDown(); } }; createThread.start(); gcThread.start(); endLatch.await(); // test ledgers for (Long ledger : removedLedgers) { assertFalse(getActiveLedgerManager().containsActiveLedger(ledger)); } for (Long ledger : createdLedgers) { assertTrue(getActiveLedgerManager().containsActiveLedger(ledger)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void start(Configuration conf) { initIfNecessary(); int metricsOutputFrequency = conf.getInt("codahaleStatsOutputFrequencySeconds", 60); String prefix = conf.getString("codahaleStatsPrefix", ""); String graphiteHost = conf.getString("codahaleStatsGraphiteEndpoint"); String csvDir = conf.getString("codahaleStatsCSVEndpoint"); String slf4jCat = conf.getString("codahaleStatsSlf4jEndpoint"); if (!Strings.isNullOrEmpty(graphiteHost)) { LOG.info("Configuring stats with graphite"); HostAndPort addr = HostAndPort.fromString(graphiteHost); final Graphite graphite = new Graphite( new InetSocketAddress(addr.getHostText(), addr.getPort())); reporters.add(GraphiteReporter.forRegistry(metrics) .prefixedWith(prefix) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(MetricFilter.ALL) .build(graphite)); } if (!Strings.isNullOrEmpty(csvDir)) { // NOTE: 1/ metrics output files are exclusive to a given process // 2/ the output directory must exist // 3/ if output files already exist they are not overwritten and there is no metrics output File outdir; if (Strings.isNullOrEmpty(prefix)) { outdir = new File(csvDir, prefix); } else { outdir = new File(csvDir); } LOG.info("Configuring stats with csv output to directory [{}]", outdir.getAbsolutePath()); reporters.add(CsvReporter.forRegistry(metrics) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(outdir)); } if (!Strings.isNullOrEmpty(slf4jCat)) { LOG.info("Configuring stats with slf4j"); reporters.add(Slf4jReporter.forRegistry(metrics) .outputTo(LoggerFactory.getLogger(slf4jCat)) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build()); } for (ScheduledReporter r : reporters) { r.start(metricsOutputFrequency, TimeUnit.SECONDS); } } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void start(Configuration conf) { initIfNecessary(); int metricsOutputFrequency = conf.getInt("codahaleStatsOutputFrequencySeconds", 60); String prefix = conf.getString("codahaleStatsPrefix", ""); String graphiteHost = conf.getString("codahaleStatsGraphiteEndpoint"); String csvDir = conf.getString("codahaleStatsCSVEndpoint"); String slf4jCat = conf.getString("codahaleStatsSlf4jEndpoint"); if (!Strings.isNullOrEmpty(graphiteHost)) { LOG.info("Configuring stats with graphite"); HostAndPort addr = HostAndPort.fromString(graphiteHost); final Graphite graphite = new Graphite( new InetSocketAddress(addr.getHostText(), addr.getPort())); reporters.add(GraphiteReporter.forRegistry(getMetrics()) .prefixedWith(prefix) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(MetricFilter.ALL) .build(graphite)); } if (!Strings.isNullOrEmpty(csvDir)) { // NOTE: 1/ metrics output files are exclusive to a given process // 2/ the output directory must exist // 3/ if output files already exist they are not overwritten and there is no metrics output File outdir; if (Strings.isNullOrEmpty(prefix)) { outdir = new File(csvDir, prefix); } else { outdir = new File(csvDir); } LOG.info("Configuring stats with csv output to directory [{}]", outdir.getAbsolutePath()); reporters.add(CsvReporter.forRegistry(getMetrics()) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(outdir)); } if (!Strings.isNullOrEmpty(slf4jCat)) { LOG.info("Configuring stats with slf4j"); reporters.add(Slf4jReporter.forRegistry(getMetrics()) .outputTo(LoggerFactory.getLogger(slf4jCat)) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build()); } for (ScheduledReporter r : reporters) { r.start(metricsOutputFrequency, TimeUnit.SECONDS); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { // get back to prev value lh.lastAddConfirmed--; if (rc == BKException.Code.OK) { LedgerEntry entry = seq.nextElement(); byte[] data = entry.getEntry(); /* * We will add this entry again to make sure it is written to enough * replicas. We subtract the length of the data itself, since it will * be added again when processing the call to add it. */ synchronized (lh) { lh.length = entry.getLength() - (long) data.length; } lh.asyncRecoveryAddEntry(data, 0, data.length, this, null); return; } if (rc == BKException.Code.NoSuchEntryException || rc == BKException.Code.NoSuchLedgerExistsException) { lh.asyncCloseInternal(new CloseCallback() { @Override public void closeComplete(int rc, LedgerHandle lh, Object ctx) { if (rc != KeeperException.Code.OK.intValue()) { LOG.warn("Close failed: " + BKException.getMessage(rc)); cb.operationComplete(BKException.Code.ZKException, null); } else { cb.operationComplete(BKException.Code.OK, null); LOG.debug("After closing length is: {}", lh.getLength()); } } }, null, BKException.Code.LedgerClosedException); return; } // otherwise, some other error, we can't handle LOG.error("Failure " + BKException.getMessage(rc) + " while reading entry: " + (lh.lastAddConfirmed + 1) + " ledger: " + lh.ledgerId + " while recovering ledger"); cb.operationComplete(rc, null); return; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if (rc == BKException.Code.OK) { LedgerEntry entry = seq.nextElement(); byte[] data = entry.getEntry(); /* * We will add this entry again to make sure it is written to enough * replicas. We subtract the length of the data itself, since it will * be added again when processing the call to add it. */ synchronized (lh) { lh.length = entry.getLength() - (long) data.length; } lh.asyncRecoveryAddEntry(data, 0, data.length, this, null); return; } if (rc == BKException.Code.NoSuchEntryException || rc == BKException.Code.NoSuchLedgerExistsException) { lh.asyncCloseInternal(new CloseCallback() { @Override public void closeComplete(int rc, LedgerHandle lh, Object ctx) { if (rc != KeeperException.Code.OK.intValue()) { LOG.warn("Close failed: " + BKException.getMessage(rc)); cb.operationComplete(BKException.Code.ZKException, null); } else { cb.operationComplete(BKException.Code.OK, null); LOG.debug("After closing length is: {}", lh.getLength()); } } }, null, BKException.Code.LedgerClosedException); return; } // otherwise, some other error, we can't handle LOG.error("Failure " + BKException.getMessage(rc) + " while reading entry: " + (lh.lastAddConfirmed + 1) + " ledger: " + lh.ledgerId + " while recovering ledger"); cb.operationComplete(rc, null); return; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void doPublish(PubSubData pubSubData, Channel channel) { // Create a PubSubRequest PubSubRequest.Builder pubsubRequestBuilder = PubSubRequest.newBuilder(); pubsubRequestBuilder.setProtocolVersion(ProtocolVersion.VERSION_ONE); pubsubRequestBuilder.setType(OperationType.PUBLISH); if (pubSubData.triedServers != null && pubSubData.triedServers.size() > 0) { pubsubRequestBuilder.addAllTriedServers(pubSubData.triedServers); } long txnId = client.globalCounter.incrementAndGet(); pubsubRequestBuilder.setTxnId(txnId); pubsubRequestBuilder.setShouldClaim(pubSubData.shouldClaim); pubsubRequestBuilder.setTopic(pubSubData.topic); // Now create the PublishRequest PublishRequest.Builder publishRequestBuilder = PublishRequest.newBuilder(); publishRequestBuilder.setMsg(pubSubData.msg); // Set the PublishRequest into the outer PubSubRequest pubsubRequestBuilder.setPublishRequest(publishRequestBuilder); // Update the PubSubData with the txnId and the requestWriteTime pubSubData.txnId = txnId; pubSubData.requestWriteTime = MathUtils.now(); // Before we do the write, store this information into the // ResponseHandler so when the server responds, we know what // appropriate Callback Data to invoke for the given txn ID. HedwigClientImpl.getResponseHandlerFromChannel(channel).txn2PubSubData.put(txnId, pubSubData); // Finally, write the Publish request through the Channel. if (logger.isDebugEnabled()) logger.debug("Writing a Publish request to host: " + HedwigClientImpl.getHostFromChannel(channel) + " for pubSubData: " + pubSubData); ChannelFuture future = channel.write(pubsubRequestBuilder.build()); future.addListener(new WriteCallback(pubSubData, client)); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void doPublish(PubSubData pubSubData, Channel channel) { // Create a PubSubRequest PubSubRequest.Builder pubsubRequestBuilder = PubSubRequest.newBuilder(); pubsubRequestBuilder.setProtocolVersion(ProtocolVersion.VERSION_ONE); pubsubRequestBuilder.setType(OperationType.PUBLISH); if (pubSubData.triedServers != null && pubSubData.triedServers.size() > 0) { pubsubRequestBuilder.addAllTriedServers(pubSubData.triedServers); } long txnId = client.globalCounter.incrementAndGet(); pubsubRequestBuilder.setTxnId(txnId); pubsubRequestBuilder.setShouldClaim(pubSubData.shouldClaim); pubsubRequestBuilder.setTopic(pubSubData.topic); // Now create the PublishRequest PublishRequest.Builder publishRequestBuilder = PublishRequest.newBuilder(); publishRequestBuilder.setMsg(pubSubData.msg); // Set the PublishRequest into the outer PubSubRequest pubsubRequestBuilder.setPublishRequest(publishRequestBuilder); // Update the PubSubData with the txnId and the requestWriteTime pubSubData.txnId = txnId; pubSubData.requestWriteTime = MathUtils.now(); // Before we do the write, store this information into the // ResponseHandler so when the server responds, we know what // appropriate Callback Data to invoke for the given txn ID. try { HedwigClientImpl.getResponseHandlerFromChannel(channel).txn2PubSubData.put(txnId, pubSubData); } catch (NoResponseHandlerException e) { logger.error("No response handler found while storing the publish callback."); // Callback on pubsubdata indicating failure. pubSubData.getCallback().operationFailed(pubSubData.context, new CouldNotConnectException("No response " + "handler found while attempting to publish. So could not connect.")); return; } // Finally, write the Publish request through the Channel. if (logger.isDebugEnabled()) logger.debug("Writing a Publish request to host: " + HedwigClientImpl.getHostFromChannel(channel) + " for pubSubData: " + pubSubData); ChannelFuture future = channel.write(pubsubRequestBuilder.build()); future.addListener(new WriteCallback(pubSubData, client)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void setLastLogId(File dir, long logId) throws IOException { FileOutputStream fos; fos = new FileOutputStream(new File(dir, "lastId")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try { bw.write(Long.toHexString(logId) + "\n"); bw.flush(); } finally { try { fos.close(); } catch (IOException e) { } } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code private void setLastLogId(File dir, long logId) throws IOException { FileOutputStream fos; fos = new FileOutputStream(new File(dir, "lastId")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try { bw.write(Long.toHexString(logId) + "\n"); bw.flush(); } finally { try { bw.close(); } catch (IOException e) { } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadWriteRangeAsyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi int numEntries = 4; // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntries) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } try { lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); fail("Shouldn't be able to use negative offset"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); fail("Shouldn't be able to use that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); fail("Shouldn't be able to use negative offset " + "with that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 4, -3, this, sync); fail("Shouldn't be able to use negative length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -4, -3, this, sync); fail("Shouldn't be able to use negative offset & length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntries - 1)); // read entries lh.asyncReadEntries(0, numEntries - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] expected = null; byte[] entry = ls.nextElement().getEntry(); switch (i) { case 0: expected = Arrays.copyOfRange(bytes, 0, bytes.length); break; case 1: expected = Arrays.copyOfRange(bytes, 0, 4); break; case 2: expected = Arrays.copyOfRange(bytes, 3, 3+4); break; case 3: expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); break; } assertNotNull("There are more checks than writes", expected); String message = "Checking entry " + i + " for equality [" + new String(entry, "UTF-8") + "," + new String(expected, "UTF-8") + "]"; assertTrue(message, Arrays.equals(entry, expected)); i++; } assertTrue("Checking number of read entries", i == numEntries); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 86 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testReadWriteRangeAsyncSingleClient() throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi int numEntries = 4; // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntries) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } try { lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); fail("Shouldn't be able to use negative offset"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); fail("Shouldn't be able to use that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); fail("Shouldn't be able to use negative offset " + "with that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 4, -3, this, sync); fail("Shouldn't be able to use negative length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -4, -3, this, sync); fail("Shouldn't be able to use negative offset & length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntries - 1)); // read entries lh.asyncReadEntries(0, numEntries - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; Enumeration<LedgerEntry> ls = sync.getLedgerEntries(); while (ls.hasMoreElements()) { byte[] expected = null; byte[] entry = ls.nextElement().getEntry(); switch (i) { case 0: expected = Arrays.copyOfRange(bytes, 0, bytes.length); break; case 1: expected = Arrays.copyOfRange(bytes, 0, 4); break; case 2: expected = Arrays.copyOfRange(bytes, 3, 3+4); break; case 3: expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); break; } assertNotNull("There are more checks than writes", expected); String message = "Checking entry " + i + " for equality [" + new String(entry, "UTF-8") + "," + new String(expected, "UTF-8") + "]"; assertTrue(message, Arrays.equals(entry, expected)); i++; } assertTrue("Checking number of read entries", i == numEntries); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if (rc != 0) fail("Failed to write entry"); ls = seq; synchronized (sync) { sync.value = true; sync.notify(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { SyncObj x = (SyncObj) ctx; if (rc != 0) { LOG.error("Failure during add {}", rc); x.failureOccurred = true; } synchronized (x) { x.value = true; x.ls = seq; x.notify(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected synchronized void messageConsumed(Message message) { if (logger.isDebugEnabled()) logger.debug("Message has been successfully consumed by the client app for message: " + message + ", topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); // Update the consumed messages buffer variables if (responseHandler.getConfiguration().isAutoSendConsumeMessageEnabled()) { // Update these variables only if we are auto-sending consume // messages to the server. Otherwise the onus is on the client app // to call the Subscriber consume API to let the server know which // messages it has successfully consumed. numConsumedMessagesInBuffer++; lastMessageSeqId = message.getMsgId(); } // Remove this consumed message from the outstanding Message Set. outstandingMsgSet.remove(message); // For consume response to server, there is a config param on how many // messages to consume and buffer up before sending the consume request. // We just need to keep a count of the number of messages consumed // and the largest/latest msg ID seen so far in this batch. Messages // should be delivered in order and without gaps. Do this only if // auto-sending of consume messages is enabled. if (responseHandler.getConfiguration().isAutoSendConsumeMessageEnabled() && numConsumedMessagesInBuffer >= responseHandler.getConfiguration().getConsumedMessagesBufferSize()) { // Send the consume request and reset the consumed messages buffer // variables. We will use the same Channel created from the // subscribe request for the TopicSubscriber. if (logger.isDebugEnabled()) logger .debug("Consumed message buffer limit reached so send the Consume Request to the server with lastMessageSeqId: " + lastMessageSeqId); responseHandler.getSubscriber().doConsume(origSubData, subscribeChannel, lastMessageSeqId); numConsumedMessagesInBuffer = 0; lastMessageSeqId = null; } // Check if we throttled message consumption previously when the // outstanding message limit was reached. For now, only turn the // delivery back on if there are no more outstanding messages to // consume. We could make this a configurable parameter if needed. if (!subscribeChannel.isReadable() && outstandingMsgSet.isEmpty()) { if (logger.isDebugEnabled()) logger .debug("Message consumption has caught up so okay to turn off throttling of messages on the subscribe channel for topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); subscribeChannel.setReadable(true); } } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected synchronized void messageConsumed(Message message) { if (logger.isDebugEnabled()) logger.debug("Message has been successfully consumed by the client app for message: " + message + ", topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); // Update the consumed messages buffer variables if (responseHandler.getConfiguration().isAutoSendConsumeMessageEnabled()) { // Update these variables only if we are auto-sending consume // messages to the server. Otherwise the onus is on the client app // to call the Subscriber consume API to let the server know which // messages it has successfully consumed. numConsumedMessagesInBuffer++; lastMessageSeqId = message.getMsgId(); } // Remove this consumed message from the outstanding Message Set. outstandingMsgSet.remove(message); // For consume response to server, there is a config param on how many // messages to consume and buffer up before sending the consume request. // We just need to keep a count of the number of messages consumed // and the largest/latest msg ID seen so far in this batch. Messages // should be delivered in order and without gaps. Do this only if // auto-sending of consume messages is enabled. if (responseHandler.getConfiguration().isAutoSendConsumeMessageEnabled() && numConsumedMessagesInBuffer >= responseHandler.getConfiguration().getConsumedMessagesBufferSize()) { // Send the consume request and reset the consumed messages buffer // variables. We will use the same Channel created from the // subscribe request for the TopicSubscriber. logger.debug("Consumed message buffer limit reached so send the Consume Request to the " + "server with lastMessageSeqId: {}", lastMessageSeqId); responseHandler.getSubscriber().doConsume(origSubData, subscribeChannel, lastMessageSeqId); numConsumedMessagesInBuffer = 0; lastMessageSeqId = null; } // Check if we throttled message consumption previously when the // outstanding message limit was reached. For now, only turn the // delivery back on if there are no more outstanding messages to // consume. We could make this a configurable parameter if needed. if (!subscribeChannel.isReadable() && outstandingMsgSet.isEmpty()) { if (logger.isDebugEnabled()) logger.debug("Message consumption has caught up so okay to turn off throttling of " + "messages on the subscribe channel for topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); subscribeChannel.setReadable(true); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout=60000) public void testReadFromOpenLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); if(i == numEntriesToWrite/2) { LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); // no recovery opened ledger 's last confirmed entry id is less than written // and it just can read until (i-1) int toRead = i - 1; Enumeration<LedgerEntry> readEntry = lhOpen.readEntries(toRead, toRead); assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); LedgerEntry e = readEntry.nextElement(); assertEquals(toRead, e.getEntryId()); Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); // should not written to a read only ledger try { lhOpen.addEntry(entry.array()); fail("Should have thrown an exception here"); } catch (BKException.BKIllegalOpException bkioe) { // this is the correct response } catch (Exception ex) { LOG.error("Unexpected exception", ex); fail("Unexpected exception"); } // close read only ledger should not change metadata lhOpen.close(); } } long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == -1) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test(timeout=60000) public void testReadFromOpenLedger() throws Exception { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); long lac = writeNEntriesLastWriteSync(lh, numEntriesToWrite); LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); // no recovery opened ledger 's last confirmed entry id is less than written // and it just can read until (i-1) long toRead = lac - 1; Enumeration<LedgerEntry> readEntry = lhOpen.readEntries(toRead, toRead); assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); LedgerEntry e = readEntry.nextElement(); assertEquals(toRead, e.getEntryId()); Assert.assertArrayEquals(entries.get((int)toRead), e.getEntry()); // should not written to a read only ledger try { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); lhOpen.addEntry(entry.array()); fail("Should have thrown an exception here"); } catch (BKException.BKIllegalOpException bkioe) { // this is the correct response } catch (Exception ex) { LOG.error("Unexpected exception", ex); fail("Unexpected exception"); } // close read only ledger should not change metadata lhOpen.close(); lac = writeNEntriesLastWriteSync(lh, numEntriesToWrite); assertEquals("Last confirmed add: ", lac, (numEntriesToWrite * 2) - 1); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); writeNEntriesLastWriteSync(lh, numEntriesToWrite); SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == -1) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertEquals("Last confirmed add", sync.lastConfirmed, (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void processResult(int rc, String path, Object ctx, List<String> children) { if (rc != KeeperException.Code.OK.intValue()) { //logger.error("Error while reading bookies", KeeperException.create(Code.get(rc), path)); // try the read after a second again scheduler.schedule(reReadTask, ZK_CONNECT_BACKOFF_SEC, TimeUnit.SECONDS); return; } // Read the bookie addresses into a set for efficient lookup HashSet<InetSocketAddress> newBookieAddrs = new HashSet<InetSocketAddress>(); for (String bookieAddrString : children) { InetSocketAddress bookieAddr; try { bookieAddr = StringUtils.parseAddr(bookieAddrString); } catch (IOException e) { logger.error("Could not parse bookie address: " + bookieAddrString + ", ignoring this bookie"); continue; } newBookieAddrs.add(bookieAddr); } HashSet<InetSocketAddress> deadBookies = (HashSet<InetSocketAddress>)knownBookies.clone(); deadBookies.removeAll(newBookieAddrs); synchronized (this) { knownBookies = newBookieAddrs; } if (bk.getBookieClient() != null) { bk.getBookieClient().closeClients(deadBookies); } } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void processResult(int rc, String path, Object ctx, List<String> children) { if (rc != KeeperException.Code.OK.intValue()) { //logger.error("Error while reading bookies", KeeperException.create(Code.get(rc), path)); // try the read after a second again scheduler.schedule(reReadTask, ZK_CONNECT_BACKOFF_SEC, TimeUnit.SECONDS); return; } // Read the bookie addresses into a set for efficient lookup HashSet<InetSocketAddress> newBookieAddrs = new HashSet<InetSocketAddress>(); for (String bookieAddrString : children) { InetSocketAddress bookieAddr; try { bookieAddr = StringUtils.parseAddr(bookieAddrString); } catch (IOException e) { logger.error("Could not parse bookie address: " + bookieAddrString + ", ignoring this bookie"); continue; } newBookieAddrs.add(bookieAddr); } final HashSet<InetSocketAddress> deadBookies; synchronized (this) { deadBookies = (HashSet<InetSocketAddress>)knownBookies.clone(); deadBookies.removeAll(newBookieAddrs); knownBookies = newBookieAddrs; } if (bk.getBookieClient() != null) { bk.getBookieClient().closeClients(deadBookies); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { SyncObj sync = new SyncObj(); LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void auxTestReadWriteAsyncSingleClient(BookieServer bs) throws IOException { try { // Create a ledger lh = bkc.createLedger(3, 2, digestType, ledgerPassword); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } LOG.info("Wrote " + numEntriesToWrite + " and now going to fail bookie."); // Bookie fail bs.shutdown(); // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger bkc.close(); bkc = new BookKeeperTestClient(baseClientConf); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(10000); assertTrue("Haven't received entries", sync.value); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + i); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); LOG.info("Verified that entries are ok, and now closing ledger"); lh.close(); } catch (KeeperException e) { LOG.error("Caught KeeperException", e); fail(e.toString()); } catch (BKException e) { LOG.error("Caught BKException", e); fail(e.toString()); } catch (InterruptedException e) { LOG.error("Caught InterruptedException", e); fail(e.toString()); } } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void auxTestReadWriteAsyncSingleClient(BookieServer bs) throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(3, 2, digestType, ledgerPassword); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } LOG.info("Wrote " + numEntriesToWrite + " and now going to fail bookie."); // Bookie fail bs.shutdown(); // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(10000); assertFalse("Failure occurred during write", sync.failureOccurred); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger bkc.close(); bkc = new BookKeeperTestClient(baseClientConf); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(10000); assertTrue("Haven't received entries", sync.value); assertFalse("Failure occurred during read", sync.failureOccurred); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (sync.ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = sync.ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + i); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); LOG.info("Verified that entries are ok, and now closing ledger"); lh.close(); } catch (KeeperException e) { LOG.error("Caught KeeperException", e); fail(e.toString()); } catch (BKException e) { LOG.error("Caught BKException", e); fail(e.toString()); } catch (InterruptedException e) { LOG.error("Caught InterruptedException", e); fail(e.toString()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout=60000) public void testLastConfirmedAdd() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test(timeout=60000) public void testLastConfirmedAdd() throws Exception { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void doPublish(PubSubData pubSubData, Channel channel) { // Create a PubSubRequest PubSubRequest.Builder pubsubRequestBuilder = PubSubRequest.newBuilder(); pubsubRequestBuilder.setProtocolVersion(ProtocolVersion.VERSION_ONE); pubsubRequestBuilder.setType(OperationType.PUBLISH); if (pubSubData.triedServers != null && pubSubData.triedServers.size() > 0) { pubsubRequestBuilder.addAllTriedServers(pubSubData.triedServers); } long txnId = client.globalCounter.incrementAndGet(); pubsubRequestBuilder.setTxnId(txnId); pubsubRequestBuilder.setShouldClaim(pubSubData.shouldClaim); pubsubRequestBuilder.setTopic(pubSubData.topic); // Now create the PublishRequest PublishRequest.Builder publishRequestBuilder = PublishRequest.newBuilder(); publishRequestBuilder.setMsg(pubSubData.msg); // Set the PublishRequest into the outer PubSubRequest pubsubRequestBuilder.setPublishRequest(publishRequestBuilder); // Update the PubSubData with the txnId and the requestWriteTime pubSubData.txnId = txnId; pubSubData.requestWriteTime = MathUtils.now(); // Before we do the write, store this information into the // ResponseHandler so when the server responds, we know what // appropriate Callback Data to invoke for the given txn ID. HedwigClientImpl.getResponseHandlerFromChannel(channel).txn2PubSubData.put(txnId, pubSubData); // Finally, write the Publish request through the Channel. if (logger.isDebugEnabled()) logger.debug("Writing a Publish request to host: " + HedwigClientImpl.getHostFromChannel(channel) + " for pubSubData: " + pubSubData); ChannelFuture future = channel.write(pubsubRequestBuilder.build()); future.addListener(new WriteCallback(pubSubData, client)); } #location 35 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void doPublish(PubSubData pubSubData, Channel channel) { // Create a PubSubRequest PubSubRequest.Builder pubsubRequestBuilder = PubSubRequest.newBuilder(); pubsubRequestBuilder.setProtocolVersion(ProtocolVersion.VERSION_ONE); pubsubRequestBuilder.setType(OperationType.PUBLISH); if (pubSubData.triedServers != null && pubSubData.triedServers.size() > 0) { pubsubRequestBuilder.addAllTriedServers(pubSubData.triedServers); } long txnId = client.globalCounter.incrementAndGet(); pubsubRequestBuilder.setTxnId(txnId); pubsubRequestBuilder.setShouldClaim(pubSubData.shouldClaim); pubsubRequestBuilder.setTopic(pubSubData.topic); // Now create the PublishRequest PublishRequest.Builder publishRequestBuilder = PublishRequest.newBuilder(); publishRequestBuilder.setMsg(pubSubData.msg); // Set the PublishRequest into the outer PubSubRequest pubsubRequestBuilder.setPublishRequest(publishRequestBuilder); // Update the PubSubData with the txnId and the requestWriteTime pubSubData.txnId = txnId; pubSubData.requestWriteTime = MathUtils.now(); // Before we do the write, store this information into the // ResponseHandler so when the server responds, we know what // appropriate Callback Data to invoke for the given txn ID. try { HedwigClientImpl.getResponseHandlerFromChannel(channel).txn2PubSubData.put(txnId, pubSubData); } catch (NoResponseHandlerException e) { logger.error("No response handler found while storing the publish callback."); // Callback on pubsubdata indicating failure. pubSubData.getCallback().operationFailed(pubSubData.context, new CouldNotConnectException("No response " + "handler found while attempting to publish. So could not connect.")); return; } // Finally, write the Publish request through the Channel. if (logger.isDebugEnabled()) logger.debug("Writing a Publish request to host: " + HedwigClientImpl.getHostFromChannel(channel) + " for pubSubData: " + pubSubData); ChannelFuture future = channel.write(pubsubRequestBuilder.build()); future.addListener(new WriteCallback(pubSubData, client)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private long readLastLogId(File f) { FileInputStream fis; try { fis = new FileInputStream(new File(f, "lastId")); } catch (FileNotFoundException e) { return -1; } BufferedReader br = new BufferedReader(new InputStreamReader(fis)); try { String lastIdString = br.readLine(); return Long.parseLong(lastIdString, 16); } catch (IOException e) { return -1; } catch(NumberFormatException e) { return -1; } finally { try { fis.close(); } catch (IOException e) { } } } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code private long readLastLogId(File f) { FileInputStream fis; try { fis = new FileInputStream(new File(f, "lastId")); } catch (FileNotFoundException e) { return -1; } BufferedReader br = new BufferedReader(new InputStreamReader(fis)); try { String lastIdString = br.readLine(); return Long.parseLong(lastIdString, 16); } catch (IOException e) { return -1; } catch(NumberFormatException e) { return -1; } finally { try { br.close(); } catch (IOException e) { } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 39 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { SyncObj sync = new SyncObj(); LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { // get back to prev value lh.lastAddConfirmed--; if (rc == BKException.Code.OK) { LedgerEntry entry = seq.nextElement(); byte[] data = entry.getEntry(); /* * We will add this entry again to make sure it is written to enough * replicas. We subtract the length of the data itself, since it will * be added again when processing the call to add it. */ synchronized (lh) { lh.length = entry.getLength() - (long) data.length; } lh.asyncRecoveryAddEntry(data, 0, data.length, this, null); return; } if (rc == BKException.Code.NoSuchEntryException || rc == BKException.Code.NoSuchLedgerExistsException) { lh.asyncCloseInternal(new CloseCallback() { @Override public void closeComplete(int rc, LedgerHandle lh, Object ctx) { if (rc != KeeperException.Code.OK.intValue()) { LOG.warn("Close failed: " + BKException.getMessage(rc)); cb.operationComplete(BKException.Code.ZKException, null); } else { cb.operationComplete(BKException.Code.OK, null); LOG.debug("After closing length is: {}", lh.getLength()); } } }, null, BKException.Code.LedgerClosedException); return; } // otherwise, some other error, we can't handle LOG.error("Failure " + BKException.getMessage(rc) + " while reading entry: " + (lh.lastAddConfirmed + 1) + " ledger: " + lh.ledgerId + " while recovering ledger"); cb.operationComplete(rc, null); return; } #location 38 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if (rc == BKException.Code.OK) { LedgerEntry entry = seq.nextElement(); byte[] data = entry.getEntry(); /* * We will add this entry again to make sure it is written to enough * replicas. We subtract the length of the data itself, since it will * be added again when processing the call to add it. */ synchronized (lh) { lh.length = entry.getLength() - (long) data.length; } lh.asyncRecoveryAddEntry(data, 0, data.length, this, null); return; } if (rc == BKException.Code.NoSuchEntryException || rc == BKException.Code.NoSuchLedgerExistsException) { lh.asyncCloseInternal(new CloseCallback() { @Override public void closeComplete(int rc, LedgerHandle lh, Object ctx) { if (rc != KeeperException.Code.OK.intValue()) { LOG.warn("Close failed: " + BKException.getMessage(rc)); cb.operationComplete(BKException.Code.ZKException, null); } else { cb.operationComplete(BKException.Code.OK, null); LOG.debug("After closing length is: {}", lh.getLength()); } } }, null, BKException.Code.LedgerClosedException); return; } // otherwise, some other error, we can't handle LOG.error("Failure " + BKException.getMessage(rc) + " while reading entry: " + (lh.lastAddConfirmed + 1) + " ledger: " + lh.ledgerId + " while recovering ledger"); cb.operationComplete(rc, null); return; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadWriteRangeAsyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi int numEntries = 4; // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntries) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } try { lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); fail("Shouldn't be able to use negative offset"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); fail("Shouldn't be able to use that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); fail("Shouldn't be able to use negative offset " + "with that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 4, -3, this, sync); fail("Shouldn't be able to use negative length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -4, -3, this, sync); fail("Shouldn't be able to use negative offset & length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntries - 1)); // read entries lh.asyncReadEntries(0, numEntries - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] expected = null; byte[] entry = ls.nextElement().getEntry(); switch (i) { case 0: expected = Arrays.copyOfRange(bytes, 0, bytes.length); break; case 1: expected = Arrays.copyOfRange(bytes, 0, 4); break; case 2: expected = Arrays.copyOfRange(bytes, 3, 3+4); break; case 3: expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); break; } assertNotNull("There are more checks than writes", expected); String message = "Checking entry " + i + " for equality [" + new String(entry, "UTF-8") + "," + new String(expected, "UTF-8") + "]"; assertTrue(message, Arrays.equals(entry, expected)); i++; } assertTrue("Checking number of read entries", i == numEntries); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testReadWriteRangeAsyncSingleClient() throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi int numEntries = 4; // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntries) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } try { lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); fail("Shouldn't be able to use negative offset"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); fail("Shouldn't be able to use that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); fail("Shouldn't be able to use negative offset " + "with that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 4, -3, this, sync); fail("Shouldn't be able to use negative length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -4, -3, this, sync); fail("Shouldn't be able to use negative offset & length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntries - 1)); // read entries lh.asyncReadEntries(0, numEntries - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; Enumeration<LedgerEntry> ls = sync.getLedgerEntries(); while (ls.hasMoreElements()) { byte[] expected = null; byte[] entry = ls.nextElement().getEntry(); switch (i) { case 0: expected = Arrays.copyOfRange(bytes, 0, bytes.length); break; case 1: expected = Arrays.copyOfRange(bytes, 0, 4); break; case 2: expected = Arrays.copyOfRange(bytes, 3, 3+4); break; case 3: expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); break; } assertNotNull("There are more checks than writes", expected); String message = "Checking entry " + i + " for equality [" + new String(entry, "UTF-8") + "," + new String(expected, "UTF-8") + "]"; assertTrue(message, Arrays.equals(entry, expected)); i++; } assertTrue("Checking number of read entries", i == numEntries); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadWriteAsyncLength() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } long length = numEntriesToWrite * 4; assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testReadWriteAsyncLength() throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } long length = numEntriesToWrite * 4; assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { LOG.info("Running..."); long start = previous = System.currentTimeMillis(); byte messageCount = 0; int sent = 0; Thread reporter = new Thread() { public void run() { try { while(true) { Thread.sleep(200); LOG.info("ms: {} req: {}", System.currentTimeMillis(), completedRequests.getAndSet(0)); } } catch (InterruptedException ie) { LOG.info("Caught interrupted exception, going away"); } } }; reporter.start(); long beforeSend = System.nanoTime(); while(!Thread.currentThread().isInterrupted() && sent < sendLimit) { try { sem.acquire(); if (sent == 10000) { long afterSend = System.nanoTime(); long time = afterSend - beforeSend; LOG.info("Time to send first batch: {}s {}ns ", time/1000/1000/1000, time); } } catch (InterruptedException e) { break; } final int index = getRandomLedger(); LedgerHandle h = lh[index]; if (h == null) { LOG.error("Handle " + index + " is null!"); } else { long nanoTime = System.nanoTime(); lh[index].asyncAddEntry(bytes, this, new Context(sent, nanoTime)); counter.incrementAndGet(); } sent++; } LOG.info("Sent: " + sent); try { synchronized (this) { while(this.counter.get() > 0) Thread.sleep(1000); } } catch(InterruptedException e) { LOG.error("Interrupted while waiting", e); } synchronized(this) { duration = System.currentTimeMillis() - start; } throughput = sent*1000/duration; reporter.interrupt(); try { reporter.join(); } catch (InterruptedException ie) { // ignore } LOG.info("Finished processing in ms: " + duration + " tp = " + throughput); } #location 67 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { LOG.info("Running..."); long start = previous = System.currentTimeMillis(); int sent = 0; Thread reporter = new Thread() { public void run() { try { while(true) { Thread.sleep(200); LOG.info("ms: {} req: {}", System.currentTimeMillis(), completedRequests.getAndSet(0)); } } catch (InterruptedException ie) { LOG.info("Caught interrupted exception, going away"); } } }; reporter.start(); long beforeSend = System.nanoTime(); while(!Thread.currentThread().isInterrupted() && sent < sendLimit) { try { sem.acquire(); if (sent == 10000) { long afterSend = System.nanoTime(); long time = afterSend - beforeSend; LOG.info("Time to send first batch: {}s {}ns ", time/1000/1000/1000, time); } } catch (InterruptedException e) { break; } final int index = getRandomLedger(); LedgerHandle h = lh[index]; if (h == null) { LOG.error("Handle " + index + " is null!"); } else { long nanoTime = System.nanoTime(); lh[index].asyncAddEntry(bytes, this, new Context(sent, nanoTime)); counter.incrementAndGet(); } sent++; } LOG.info("Sent: " + sent); try { synchronized (this) { while (this.counter.get() > 0) { waitFor(1000); } } } catch(InterruptedException e) { LOG.error("Interrupted while waiting", e); } synchronized(this) { duration = System.currentTimeMillis() - start; } throughput = sent*1000/getDuration(); reporter.interrupt(); try { reporter.join(); } catch (InterruptedException ie) { // ignore } LOG.info("Finished processing in ms: " + getDuration() + " tp = " + throughput); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEnsembleReformation() throws Exception { try { LedgerManagerFactory newLedgerManagerFactory = LedgerManagerFactory .newLedgerManagerFactory(baseConf, zkc); LedgerManager ledgerManager = newLedgerManagerFactory .newLedgerManager(); List<Long> ledgerList = new ArrayList<Long>(3); LedgerHandle lh1 = createAndAddEntriesToLedger(); ledgerList.add(lh1.getId()); LedgerHandle lh2 = createAndAddEntriesToLedger(); ledgerList.add(lh2.getId()); startNewBookie(); shutdownBookie(bs.size() - 2); // add few more entries after ensemble reformation for (int i = 0; i < 10; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(Integer.MAX_VALUE)); entry.position(0); entries.add(entry.array()); lh1.addEntry(entry.array()); lh2.addEntry(entry.array()); } BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); Map<String, Set<Long>> bookieToLedgerIndex = bookieLedgerIndex .getBookieToLedgerIndex(); assertEquals("Missed few bookies in the bookie-ledger mapping!", 4, bookieToLedgerIndex.size()); Collection<Set<Long>> bk2ledgerEntry = bookieToLedgerIndex.values(); for (Set<Long> ledgers : bk2ledgerEntry) { assertEquals( "Missed few ledgers in the bookie-ledger mapping!", 2, ledgers.size()); for (Long ledgerNode : ledgers) { assertTrue("Unknown ledger-bookie mapping", ledgerList .contains(ledgerNode)); } } } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 46 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEnsembleReformation() throws Exception { try { LedgerHandle lh1 = createAndAddEntriesToLedger(); LedgerHandle lh2 = createAndAddEntriesToLedger(); startNewBookie(); shutdownBookie(bs.size() - 2); // add few more entries after ensemble reformation for (int i = 0; i < 10; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(Integer.MAX_VALUE)); entry.position(0); entries.add(entry.array()); lh1.addEntry(entry.array()); lh2.addEntry(entry.array()); } BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); Map<String, Set<Long>> bookieToLedgerIndex = bookieLedgerIndex .getBookieToLedgerIndex(); assertEquals("Missed few bookies in the bookie-ledger mapping!", 4, bookieToLedgerIndex.size()); Collection<Set<Long>> bk2ledgerEntry = bookieToLedgerIndex.values(); for (Set<Long> ledgers : bk2ledgerEntry) { assertEquals( "Missed few ledgers in the bookie-ledger mapping!", 2, ledgers.size()); for (Long ledgerNode : ledgers) { assertTrue("Unknown ledger-bookie mapping", ledgerList .contains(ledgerNode)); } } } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void handleBookieFailure(InetSocketAddress addr, final int bookieIndex) { InetSocketAddress newBookie; if (LOG.isDebugEnabled()) { LOG.debug("Handling failure of bookie: " + addr + " index: " + bookieIndex); } try { newBookie = bk.bookieWatcher .getAdditionalBookie(metadata.currentEnsemble); } catch (BKNotEnoughBookiesException e) { LOG .error("Could not get additional bookie to remake ensemble, closing ledger: " + ledgerId); handleUnrecoverableErrorDuringAdd(e.getCode()); return; } final ArrayList<InetSocketAddress> newEnsemble = new ArrayList<InetSocketAddress>( metadata.currentEnsemble); newEnsemble.set(bookieIndex, newBookie); if (LOG.isDebugEnabled()) { LOG.debug("Changing ensemble from: " + metadata.currentEnsemble + " to: " + newEnsemble + " for ledger: " + ledgerId + " starting at entry: " + (lastAddConfirmed + 1)); } final long newEnsembleStartEntry = lastAddConfirmed + 1; metadata.addEnsemble(newEnsembleStartEntry, newEnsemble); final class ChangeEnsembleCb implements GenericCallback<Void> { @Override public void operationComplete(final int rc, Void result) { bk.mainWorkerPool.submitOrdered(ledgerId, new SafeRunnable() { @Override public void safeRun() { if (rc == BKException.Code.MetadataVersionException) { rereadMetadata(new GenericCallback<LedgerMetadata>() { @Override public void operationComplete(int newrc, LedgerMetadata newMeta) { if (newrc != BKException.Code.OK) { LOG.error("Error reading new metadata from ledger after changing ensemble, code=" + newrc); handleUnrecoverableErrorDuringAdd(rc); } else { // a new ensemble is added only when the start entry is larger than zero if (newEnsembleStartEntry > 0) { metadata.getEnsembles().remove(newEnsembleStartEntry); } if (metadata.resolveConflict(newMeta)) { metadata.addEnsemble(newEnsembleStartEntry, newEnsemble); writeLedgerConfig(new ChangeEnsembleCb()); return; } else { LOG.error("Could not resolve ledger metadata conflict while changing ensemble to: " + newEnsemble + ", old meta data is \n" + new String(metadata.serialize()) + "\n, new meta data is \n" + new String(newMeta.serialize()) + "\n ,closing ledger"); handleUnrecoverableErrorDuringAdd(rc); } } } }); return; } else if (rc != BKException.Code.OK) { LOG.error("Could not persist ledger metadata while changing ensemble to: " + newEnsemble + " , closing ledger"); handleUnrecoverableErrorDuringAdd(rc); return; } for (PendingAddOp pendingAddOp : pendingAddOps) { pendingAddOp.unsetSuccessAndSendWriteRequest(bookieIndex); } } }); } }; writeLedgerConfig(new ChangeEnsembleCb()); } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code LedgerHandle(BookKeeper bk, long ledgerId, LedgerMetadata metadata, DigestType digestType, byte[] password) throws GeneralSecurityException, NumberFormatException { this.bk = bk; this.metadata = metadata; if (metadata.isClosed()) { lastAddConfirmed = lastAddPushed = metadata.getLastEntryId(); length = metadata.getLength(); } else { lastAddConfirmed = lastAddPushed = INVALID_ENTRY_ID; length = 0; } this.ledgerId = ledgerId; this.throttling = bk.getConf().getThrottleValue(); this.opCounterSem = new Semaphore(throttling); macManager = DigestManager.instantiate(ledgerId, password, digestType); this.ledgerKey = MacDigestManager.genDigest("ledger", password); distributionSchedule = new RoundRobinDistributionSchedule( metadata.getQuorumSize(), metadata.getEnsembleSize()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void setLastLogId(File dir, long logId) throws IOException { FileOutputStream fos; fos = new FileOutputStream(new File(dir, "lastId")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try { bw.write(Long.toHexString(logId) + "\n"); bw.flush(); } finally { try { fos.close(); } catch (IOException e) { } } } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code private void setLastLogId(File dir, long logId) throws IOException { FileOutputStream fos; fos = new FileOutputStream(new File(dir, "lastId")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try { bw.write(Long.toHexString(logId) + "\n"); bw.flush(); } finally { try { bw.close(); } catch (IOException e) { } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if (rc != 0) fail("Failed to write entry"); ls = seq; synchronized (sync) { sync.value = true; sync.notify(); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { SyncObj x = (SyncObj) ctx; if (rc != 0) { LOG.error("Failure during add {}", rc); x.failureOccurred = true; } synchronized (x) { x.value = true; x.ls = seq; x.notify(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 60000) public void testWhenNoLogsToCompact() throws Exception { tearDown(); // I dont want the test infrastructure ServerConfiguration conf = new ServerConfiguration(); File tmpDir = File.createTempFile("bkTest", ".dir"); tmpDir.delete(); tmpDir.mkdir(); File curDir = Bookie.getCurrentDirectory(tmpDir); Bookie.checkDirectoryStructure(curDir); conf.setLedgerDirNames(new String[] { tmpDir.toString() }); LedgerDirsManager dirs = new LedgerDirsManager(conf); final Set<Long> ledgers = Collections .newSetFromMap(new ConcurrentHashMap<Long, Boolean>()); LedgerManager manager = getLedgerManager(ledgers); CheckpointSource checkpointSource = new CheckpointSource() { @Override public Checkpoint newCheckpoint() { return null; } @Override public void checkpointComplete(Checkpoint checkpoint, boolean compact) throws IOException { } }; InterleavedLedgerStorage storage = new InterleavedLedgerStorage(conf, manager, dirs, checkpointSource); double threshold = 0.1; // shouldn't throw exception storage.gcThread.doCompactEntryLogs(threshold); } #location 28 #vulnerability type RESOURCE_LEAK
#fixed code @Test(timeout = 60000) public void testWhenNoLogsToCompact() throws Exception { tearDown(); // I dont want the test infrastructure ServerConfiguration conf = new ServerConfiguration(); File tmpDir = File.createTempFile("bkTest", ".dir"); tmpDir.delete(); tmpDir.mkdir(); File curDir = Bookie.getCurrentDirectory(tmpDir); Bookie.checkDirectoryStructure(curDir); conf.setLedgerDirNames(new String[] { tmpDir.toString() }); LedgerDirsManager dirs = new LedgerDirsManager(conf, conf.getLedgerDirs()); final Set<Long> ledgers = Collections .newSetFromMap(new ConcurrentHashMap<Long, Boolean>()); LedgerManager manager = getLedgerManager(ledgers); CheckpointSource checkpointSource = new CheckpointSource() { @Override public Checkpoint newCheckpoint() { return null; } @Override public void checkpointComplete(Checkpoint checkpoint, boolean compact) throws IOException { } }; InterleavedLedgerStorage storage = new InterleavedLedgerStorage(conf, manager, dirs, checkpointSource); double threshold = 0.1; // shouldn't throw exception storage.gcThread.doCompactEntryLogs(threshold); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void handleBookieFailure(final InetSocketAddress addr, final int bookieIndex) { InetSocketAddress newBookie; LOG.debug("Handling failure of bookie: {} index: {}", addr, bookieIndex); final ArrayList<InetSocketAddress> newEnsemble = new ArrayList<InetSocketAddress>(); blockAddCompletions.incrementAndGet(); final long newEnsembleStartEntry = lastAddConfirmed + 1; // avoid parallel ensemble changes to same ensemble. synchronized (metadata) { if (!metadata.currentEnsemble.get(bookieIndex).equals(addr)) { // ensemble has already changed, failure of this addr is immaterial LOG.warn("Write did not succeed to {}, bookieIndex {}, but we have already fixed it.", addr, bookieIndex); blockAddCompletions.decrementAndGet(); return; } try { newBookie = bk.bookieWatcher .getAdditionalBookie(metadata.currentEnsemble); } catch (BKNotEnoughBookiesException e) { LOG.error("Could not get additional bookie to " + "remake ensemble, closing ledger: " + ledgerId); handleUnrecoverableErrorDuringAdd(e.getCode()); return; } newEnsemble.addAll(metadata.currentEnsemble); newEnsemble.set(bookieIndex, newBookie); if (LOG.isDebugEnabled()) { LOG.debug("Changing ensemble from: " + metadata.currentEnsemble + " to: " + newEnsemble + " for ledger: " + ledgerId + " starting at entry: " + (lastAddConfirmed + 1)); } metadata.addEnsemble(newEnsembleStartEntry, newEnsemble); } EnsembleInfo ensembleInfo = new EnsembleInfo(newEnsemble, bookieIndex, addr); writeLedgerConfig(new ChangeEnsembleCb(ensembleInfo)); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code LedgerHandle(BookKeeper bk, long ledgerId, LedgerMetadata metadata, DigestType digestType, byte[] password) throws GeneralSecurityException, NumberFormatException { this.bk = bk; this.metadata = metadata; if (metadata.isClosed()) { lastAddConfirmed = lastAddPushed = metadata.getLastEntryId(); length = metadata.getLength(); } else { lastAddConfirmed = lastAddPushed = INVALID_ENTRY_ID; length = 0; } this.ledgerId = ledgerId; this.throttler = RateLimiter.create(bk.getConf().getThrottleValue()); macManager = DigestManager.instantiate(ledgerId, password, digestType); this.ledgerKey = MacDigestManager.genDigest("ledger", password); distributionSchedule = new RoundRobinDistributionSchedule( metadata.getWriteQuorumSize(), metadata.getAckQuorumSize(), metadata.getEnsembleSize()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout=60000) public void testLastConfirmedAdd() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test(timeout=60000) public void testLastConfirmedAdd() throws Exception { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void compactEntryLog(long entryLogId) { EntryLogMetadata entryLogMeta = entryLogMetaMap.get(entryLogId); if (null == entryLogMeta) { LOG.warn("Can't get entry log meta when compacting entry log " + entryLogId + "."); return; } // Similar with Sync Thread // try to mark compacting flag to make sure it would not be interrupted // by shutdown during compaction. otherwise it will receive // ClosedByInterruptException which may cause index file & entry logger // closed and corrupted. if (!compacting.compareAndSet(false, true)) { // set compacting flag failed, means compacting is true now // indicates another thread wants to interrupt gc thread to exit return; } LOG.info("Compacting entry log : " + entryLogId); try { entryLogger.scanEntryLog(entryLogId, new CompactionScanner(entryLogMeta)); // after moving entries to new entry log, remove this old one removeEntryLog(entryLogId); } catch (IOException e) { LOG.info("Premature exception when compacting " + entryLogId, e); } finally { // clear compacting flag compacting.set(false); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void compactEntryLog(long entryLogId) { EntryLogMetadata entryLogMeta = entryLogMetaMap.get(entryLogId); if (null == entryLogMeta) { LOG.warn("Can't get entry log meta when compacting entry log " + entryLogId + "."); return; } // Similar with Sync Thread // try to mark compacting flag to make sure it would not be interrupted // by shutdown during compaction. otherwise it will receive // ClosedByInterruptException which may cause index file & entry logger // closed and corrupted. if (!compacting.compareAndSet(false, true)) { // set compacting flag failed, means compacting is true now // indicates another thread wants to interrupt gc thread to exit return; } LOG.info("Compacting entry log : " + entryLogId); try { CompactionScanner scanner = new CompactionScanner(entryLogMeta); entryLogger.scanEntryLog(entryLogId, scanner); scanner.awaitComplete(); // after moving entries to new entry log, remove this old one removeEntryLog(entryLogId); } catch (IOException e) { LOG.info("Premature exception when compacting " + entryLogId, e); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.warn("Interrupted while compacting", ie); } finally { // clear compacting flag compacting.set(false); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMultiLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); lh2 = bkc.createLedger(digestType, ledgerPassword); long ledgerId = lh.getId(); long ledgerId2 = lh2.getId(); // bkc.initMessageDigest("SHA1"); LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); lh2.addEntry(new byte[0]); } lh.close(); lh2.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh .getLastAddConfirmed() == (numEntriesToWrite - 1)); assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 .getLastAddConfirmed() == (numEntriesToWrite - 1)); ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); ls = lh2.readEntries(0, numEntriesToWrite - 1); i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh2.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testMultiLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); lh2 = bkc.createLedger(digestType, ledgerPassword); long ledgerId = lh.getId(); long ledgerId2 = lh2.getId(); // bkc.initMessageDigest("SHA1"); LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); lh2.addEntry(new byte[0]); } lh.close(); lh2.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh .getLastAddConfirmed() == (numEntriesToWrite - 1)); assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 .getLastAddConfirmed() == (numEntriesToWrite - 1)); Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); ls = lh2.readEntries(0, numEntriesToWrite - 1); i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh2.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void auxTestReadWriteAsyncSingleClient(BookieServer bs) throws IOException { try { // Create a ledger lh = bkc.createLedger(3, 2, digestType, ledgerPassword); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } LOG.info("Wrote " + numEntriesToWrite + " and now going to fail bookie."); // Bookie fail bs.shutdown(); // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger bkc.close(); bkc = new BookKeeperTestClient(baseClientConf); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(10000); assertTrue("Haven't received entries", sync.value); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + i); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); LOG.info("Verified that entries are ok, and now closing ledger"); lh.close(); } catch (KeeperException e) { LOG.error("Caught KeeperException", e); fail(e.toString()); } catch (BKException e) { LOG.error("Caught BKException", e); fail(e.toString()); } catch (InterruptedException e) { LOG.error("Caught InterruptedException", e); fail(e.toString()); } } #location 63 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void auxTestReadWriteAsyncSingleClient(BookieServer bs) throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(3, 2, digestType, ledgerPassword); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } LOG.info("Wrote " + numEntriesToWrite + " and now going to fail bookie."); // Bookie fail bs.shutdown(); // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(10000); assertFalse("Failure occurred during write", sync.failureOccurred); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger bkc.close(); bkc = new BookKeeperTestClient(baseClientConf); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(10000); assertTrue("Haven't received entries", sync.value); assertFalse("Failure occurred during read", sync.failureOccurred); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (sync.ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = sync.ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + i); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); LOG.info("Verified that entries are ok, and now closing ledger"); lh.close(); } catch (KeeperException e) { LOG.error("Caught KeeperException", e); fail(e.toString()); } catch (BKException e) { LOG.error("Caught BKException", e); fail(e.toString()); } catch (InterruptedException e) { LOG.error("Caught InterruptedException", e); fail(e.toString()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWithoutZookeeper() throws Exception { LedgerManagerFactory newLedgerManagerFactory = LedgerManagerFactory .newLedgerManagerFactory(baseConf, zkc); LedgerManager ledgerManager = newLedgerManagerFactory .newLedgerManager(); List<Long> ledgerList = new ArrayList<Long>(3); LedgerHandle lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); stopZKCluster(); try { bookieLedgerIndex.getBookieToLedgerIndex(); fail("Must throw exception as bookies are not running!"); } catch (BKAuditException bkAuditException) { // expected behaviour } } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWithoutZookeeper() throws Exception { for (int i = 0; i < numberOfLedgers; i++) { createAndAddEntriesToLedger().close(); } BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); stopZKCluster(); try { bookieLedgerIndex.getBookieToLedgerIndex(); fail("Must throw exception as bookies are not running!"); } catch (BKAuditException bkAuditException) { // expected behaviour } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadWriteAsyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testReadWriteAsyncSingleClient() throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; Enumeration<LedgerEntry> ls = sync.getLedgerEntries(); while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initiate() { /** * Enable fencing on this op. When the read request reaches the bookies * server it will fence off the ledger, stopping any subsequent operation * from writing to it. */ int flags = BookieProtocol.FLAG_DO_FENCING; for (int i = 0; i < lh.metadata.currentEnsemble.size(); i++) { lh.bk.bookieClient.readEntry(lh.metadata.currentEnsemble.get(i), lh.ledgerId, BookieProtocol.LAST_ADD_CONFIRMED, this, i, flags); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initiate() { ReadLastConfirmedOp rlcop = new ReadLastConfirmedOp(lh, new ReadLastConfirmedOp.LastConfirmedDataCallback() { public void readLastConfirmedDataComplete(int rc, RecoveryData data) { if (rc == BKException.Code.OK) { lh.lastAddPushed = lh.lastAddConfirmed = data.lastAddConfirmed; lh.length = data.length; doRecoveryRead(); } else { cb.operationComplete(BKException.Code.ReadException, null); } } }); /** * Enable fencing on this op. When the read request reaches the bookies * server it will fence off the ledger, stopping any subsequent operation * from writing to it. */ rlcop.initiateWithFencing(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadWriteAsyncSingleClientThrottle() throws IOException, NoSuchFieldException, IllegalAccessException { try { Integer throttle = 100; ThrottleTestCallback tcb = new ThrottleTestCallback(throttle); // Create a ledger bkc.getConf().setThrottleValue(throttle); lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); numEntriesToWrite = 8000; for (int i = 0; i < (numEntriesToWrite - 2000); i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); /* * Check that the difference is no larger than the throttling threshold */ int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } for (int i = 0; i < 2000; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); /* * Check that the difference is no larger than the throttling threshold */ int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries sync.counter = 0; for (int i = 0; i < numEntriesToWrite; i+=throttle) { lh.asyncReadEntries(i, i + throttle - 1, tcb, sync); int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.info("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** READ COMPLETE ***"); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 49 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testReadWriteAsyncSingleClientThrottle() throws IOException, NoSuchFieldException, IllegalAccessException { SyncObj sync = new SyncObj(); try { Integer throttle = 100; ThrottleTestCallback tcb = new ThrottleTestCallback(throttle); // Create a ledger bkc.getConf().setThrottleValue(throttle); lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); numEntriesToWrite = 8000; for (int i = 0; i < (numEntriesToWrite - 2000); i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); /* * Check that the difference is no larger than the throttling threshold */ int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } for (int i = 0; i < 2000; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); /* * Check that the difference is no larger than the throttling threshold */ int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries sync.counter = 0; for (int i = 0; i < numEntriesToWrite; i+=throttle) { lh.asyncReadEntries(i, i + throttle - 1, tcb, sync); int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.info("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** READ COMPLETE ***"); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMultiLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); lh2 = bkc.createLedger(digestType, ledgerPassword); long ledgerId = lh.getId(); long ledgerId2 = lh2.getId(); // bkc.initMessageDigest("SHA1"); LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); lh2.addEntry(new byte[0]); } lh.close(); lh2.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh .getLastAddConfirmed() == (numEntriesToWrite - 1)); assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 .getLastAddConfirmed() == (numEntriesToWrite - 1)); ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); ls = lh2.readEntries(0, numEntriesToWrite - 1); i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh2.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testMultiLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); lh2 = bkc.createLedger(digestType, ledgerPassword); long ledgerId = lh.getId(); long ledgerId2 = lh2.getId(); // bkc.initMessageDigest("SHA1"); LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); lh2.addEntry(new byte[0]); } lh.close(); lh2.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh .getLastAddConfirmed() == (numEntriesToWrite - 1)); assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 .getLastAddConfirmed() == (numEntriesToWrite - 1)); Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); ls = lh2.readEntries(0, numEntriesToWrite - 1); i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh2.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Around("within(@org.springframework.stereotype.Repository *)") public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { if (this.isEnabled) { StopWatch sw = new StopWatch(joinPoint.toShortString()); sw.start("invoke"); try { return joinPoint.proceed(); } finally { sw.stop(); synchronized (this) { this.callCount++; this.accumulatedCallTime += sw.getTotalTimeMillis(); } } } else { return joinPoint.proceed(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Around("within(@org.springframework.stereotype.Repository *)") public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { if (this.enabled) { StopWatch sw = new StopWatch(joinPoint.toShortString()); sw.start("invoke"); try { return joinPoint.proceed(); } finally { sw.stop(); synchronized (this) { this.callCount++; this.accumulatedCallTime += sw.getTotalTimeMillis(); } } } else { return joinPoint.proceed(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Object eval(final String js) { try { Object _xblockexpression = null; { this.assertScriptEngine(); if (((this.maxCPUTimeInMs).longValue() == 0)) { return this.scriptEngine.eval(js); } Object _xsynchronizedexpression = null; synchronized (this) { Object _xblockexpression_1 = null; { final Value<Object> resVal = new Value<Object>(null); final Value<Throwable> exceptionVal = new Value<Throwable>(null); final MonitorThread monitorThread = new MonitorThread(((this.maxCPUTimeInMs).longValue() * 1000000)); if ((this.exectuor == null)) { throw new IllegalStateException( "When a CPU time limit is set, an executor needs to be provided by calling .setExecutor(...)"); } final Object monitor = new Object(); final Runnable _function = new Runnable() { @Override public void run() { try { boolean _contains = js.contains("intCheckForInterruption"); if (_contains) { throw new IllegalArgumentException( "Script contains the illegal string [intCheckForInterruption]"); } Object _eval = NashornSandboxImpl.this.scriptEngine.eval("window.js_beautify;"); final ScriptObjectMirror jsBeautify = ((ScriptObjectMirror) _eval); Object _call = jsBeautify.call("beautify", js); final String beautifiedJs = ((String) _call); Random _random = new Random(); int _nextInt = _random.nextInt(); final int randomToken = Math.abs(_nextInt); StringConcatenation _builder = new StringConcatenation(); _builder.append("var InterruptTest = Java.type(\'"); String _name = InterruptTest.class.getName(); _builder.append(_name, ""); _builder.append("\');"); _builder.newLineIfNotEmpty(); _builder.append("var isInterrupted = InterruptTest.isInterrupted;"); _builder.newLine(); _builder.append("var intCheckForInterruption"); _builder.append(randomToken, ""); _builder.append(" = function() {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); _builder.append("if (isInterrupted()) {"); _builder.newLine(); _builder.append("\t "); _builder.append("throw new Error(\'Interrupted"); _builder.append(randomToken, "\t "); _builder.append("\')"); _builder.newLineIfNotEmpty(); _builder.append("\t"); _builder.append("}"); _builder.newLine(); _builder.append("};"); _builder.newLine(); String preamble = _builder.toString(); String _replace = preamble.replace("\n", ""); preamble = _replace; String _injectInterruptionCalls = NashornSandboxImpl.injectInterruptionCalls(beautifiedJs, randomToken); final String securedJs = (preamble + _injectInterruptionCalls); final Thread mainThread = Thread.currentThread(); Thread _currentThread = Thread.currentThread(); monitorThread.setThreadToMonitor(_currentThread); final Runnable _function = new Runnable() { @Override public void run() { mainThread.interrupt(); } }; monitorThread.setOnInvalidHandler(_function); monitorThread.start(); try { if (NashornSandboxImpl.this.debug) { InputOutput.<String>println("--- Running JS ---"); InputOutput.<String>println(securedJs); InputOutput.<String>println("--- JS END ---"); } final Object res = NashornSandboxImpl.this.scriptEngine.eval(securedJs); resVal.set(res); } catch (final Throwable _t) { if (_t instanceof ScriptException) { final ScriptException e = (ScriptException)_t; String _message = e.getMessage(); boolean _contains_1 = _message.contains(("Interrupted" + Integer.valueOf(randomToken))); if (_contains_1) { monitorThread.notifyOperationInterrupted(); } else { exceptionVal.set(e); monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } return; } } else { throw Exceptions.sneakyThrow(_t); } } finally { monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } } } catch (final Throwable _t_1) { if (_t_1 instanceof Throwable) { final Throwable t = (Throwable)_t_1; exceptionVal.set(t); monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } } else { throw Exceptions.sneakyThrow(_t_1); } } } }; this.exectuor.execute(_function); synchronized (monitor) { monitor.wait(); } boolean _isCPULimitExceeded = monitorThread.isCPULimitExceeded(); if (_isCPULimitExceeded) { String notGraceful = ""; boolean _gracefullyInterrputed = monitorThread.gracefullyInterrputed(); boolean _not = (!_gracefullyInterrputed); if (_not) { notGraceful = " The operation could not be gracefully interrupted."; } Throwable _get = exceptionVal.get(); throw new ScriptCPUAbuseException( ((("Script used more than the allowed [" + this.maxCPUTimeInMs) + " ms] of CPU time. ") + notGraceful), _get); } Throwable _get_1 = exceptionVal.get(); boolean _tripleNotEquals = (_get_1 != null); if (_tripleNotEquals) { throw exceptionVal.get(); } _xblockexpression_1 = resVal.get(); } _xsynchronizedexpression = _xblockexpression_1; } _xblockexpression = _xsynchronizedexpression; } return _xblockexpression; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Object eval(final String js) { try { Object _xblockexpression = null; { this.assertScriptEngine(); if (((this.maxCPUTimeInMs).longValue() == 0)) { if (this.debug) { InputOutput.<String>println("--- Running JS ---"); InputOutput.<String>println(js); InputOutput.<String>println("--- JS END ---"); } return this.scriptEngine.eval(js); } Object _xsynchronizedexpression = null; synchronized (this) { Object _xblockexpression_1 = null; { final Value<Object> resVal = new Value<Object>(null); final Value<Throwable> exceptionVal = new Value<Throwable>(null); final MonitorThread monitorThread = new MonitorThread(((this.maxCPUTimeInMs).longValue() * 1000000)); if ((this.exectuor == null)) { throw new IllegalStateException( "When a CPU time limit is set, an executor needs to be provided by calling .setExecutor(...)"); } final Object monitor = new Object(); final Runnable _function = new Runnable() { @Override public void run() { try { boolean _contains = js.contains("intCheckForInterruption"); if (_contains) { throw new IllegalArgumentException( "Script contains the illegal string [intCheckForInterruption]"); } Object _eval = NashornSandboxImpl.this.scriptEngine.eval("window.js_beautify;"); final ScriptObjectMirror jsBeautify = ((ScriptObjectMirror) _eval); Object _call = jsBeautify.call("beautify", js); final String beautifiedJs = ((String) _call); Random _random = new Random(); int _nextInt = _random.nextInt(); final int randomToken = Math.abs(_nextInt); StringConcatenation _builder = new StringConcatenation(); _builder.append("var InterruptTest = Java.type(\'"); String _name = InterruptTest.class.getName(); _builder.append(_name, ""); _builder.append("\');"); _builder.newLineIfNotEmpty(); _builder.append("var isInterrupted = InterruptTest.isInterrupted;"); _builder.newLine(); _builder.append("var intCheckForInterruption"); _builder.append(randomToken, ""); _builder.append(" = function() {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); _builder.append("if (isInterrupted()) {"); _builder.newLine(); _builder.append("\t "); _builder.append("throw new Error(\'Interrupted"); _builder.append(randomToken, "\t "); _builder.append("\')"); _builder.newLineIfNotEmpty(); _builder.append("\t"); _builder.append("}"); _builder.newLine(); _builder.append("};"); _builder.newLine(); String preamble = _builder.toString(); String _replace = preamble.replace("\n", ""); preamble = _replace; String _injectInterruptionCalls = NashornSandboxImpl.injectInterruptionCalls(beautifiedJs, randomToken); final String securedJs = (preamble + _injectInterruptionCalls); final Thread mainThread = Thread.currentThread(); Thread _currentThread = Thread.currentThread(); monitorThread.setThreadToMonitor(_currentThread); final Runnable _function = new Runnable() { @Override public void run() { mainThread.interrupt(); } }; monitorThread.setOnInvalidHandler(_function); monitorThread.start(); try { if (NashornSandboxImpl.this.debug) { InputOutput.<String>println("--- Running JS ---"); InputOutput.<String>println(securedJs); InputOutput.<String>println("--- JS END ---"); } final Object res = NashornSandboxImpl.this.scriptEngine.eval(securedJs); resVal.set(res); } catch (final Throwable _t) { if (_t instanceof ScriptException) { final ScriptException e = (ScriptException)_t; String _message = e.getMessage(); boolean _contains_1 = _message.contains(("Interrupted" + Integer.valueOf(randomToken))); if (_contains_1) { monitorThread.notifyOperationInterrupted(); } else { exceptionVal.set(e); monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } return; } } else { throw Exceptions.sneakyThrow(_t); } } finally { monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } } } catch (final Throwable _t_1) { if (_t_1 instanceof Throwable) { final Throwable t = (Throwable)_t_1; exceptionVal.set(t); monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } } else { throw Exceptions.sneakyThrow(_t_1); } } } }; this.exectuor.execute(_function); synchronized (monitor) { monitor.wait(); } boolean _isCPULimitExceeded = monitorThread.isCPULimitExceeded(); if (_isCPULimitExceeded) { String notGraceful = ""; boolean _gracefullyInterrputed = monitorThread.gracefullyInterrputed(); boolean _not = (!_gracefullyInterrputed); if (_not) { notGraceful = " The operation could not be gracefully interrupted."; } Throwable _get = exceptionVal.get(); throw new ScriptCPUAbuseException( ((("Script used more than the allowed [" + this.maxCPUTimeInMs) + " ms] of CPU time. ") + notGraceful), _get); } Throwable _get_1 = exceptionVal.get(); boolean _tripleNotEquals = (_get_1 != null); if (_tripleNotEquals) { throw exceptionVal.get(); } _xblockexpression_1 = resVal.get(); } _xsynchronizedexpression = _xblockexpression_1; } _xblockexpression = _xsynchronizedexpression; } return _xblockexpression; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void callOnError(final ExecutionError error) { if (onError != null) { onError.call(error); } synchronized (error.getContext()) { callOnTerminate((C) error.getContext()); error.getContext().notifyAll(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void callOnError(final ExecutionError error) { if (onError != null) { onError.call(error); } callOnTerminate((C) error.getContext()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void callOnFinalState(final State<C> state, final C context) { try { if (onFinalStateHandler != null) { if (isTrace()) log.debug("when final state {} for {} <<<", state, context); onFinalStateHandler.call(state, context); if (isTrace()) log.debug("when final state {} for {} >>>", state, context); } synchronized (context) { callOnTerminate(context); context.notifyAll(); } } catch (Exception e) { callOnError(new ExecutionError(state, null, e, "Execution Error in [EasyFlow.whenFinalState] handler", context)); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void callOnFinalState(final State<C> state, final C context) { try { if (onFinalStateHandler != null) { if (isTrace()) log.debug("when final state {} for {} <<<", state, context); onFinalStateHandler.call(state, context); if (isTrace()) log.debug("when final state {} for {} >>>", state, context); } callOnTerminate(context); } catch (Exception e) { callOnError(new ExecutionError(state, null, e, "Execution Error in [EasyFlow.whenFinalState] handler", context)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void callOnFinalState(final State<C> state, final C context) { try { if (onFinalStateHandler != null) { if (isTrace()) log.debug("when final state {} for {} <<<", state, context); onFinalStateHandler.call(state, context); if (isTrace()) log.debug("when final state {} for {} >>>", state, context); } synchronized (context) { callOnTerminate(context); context.notifyAll(); } } catch (Exception e) { callOnError(new ExecutionError(state, null, e, "Execution Error in [EasyFlow.whenFinalState] handler", context)); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void callOnFinalState(final State<C> state, final C context) { try { if (onFinalStateHandler != null) { if (isTrace()) log.debug("when final state {} for {} <<<", state, context); onFinalStateHandler.call(state, context); if (isTrace()) log.debug("when final state {} for {} >>>", state, context); } callOnTerminate(context); } catch (Exception e) { callOnError(new ExecutionError(state, null, e, "Execution Error in [EasyFlow.whenFinalState] handler", context)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void tableWrite() { String fileName = TestFileUtil.getPath() + "tableWrite" + System.currentTimeMillis() + ".xlsx"; // 这里直接写多个table的案例了,如果只有一个 也可以直一行代码搞定,参照其他案例 // 这里 需要指定写用哪个class去写 ExcelWriter excelWriter = null; try { EasyExcel.write(fileName, DemoData.class).build(); // 把sheet设置为不需要头 不然会输出sheet的头 这样看起来第一个table 就有2个头了 WriteSheet writeSheet = EasyExcel.writerSheet("模板").needHead(Boolean.FALSE).build(); // 这里必须指定需要头,table 会继承sheet的配置,sheet配置了不需要,table 默认也是不需要 WriteTable writeTable0 = EasyExcel.writerTable(0).needHead(Boolean.TRUE).build(); WriteTable writeTable1 = EasyExcel.writerTable(1).needHead(Boolean.TRUE).build(); // 第一次写入会创建头 excelWriter.write(data(), writeSheet, writeTable0); // 第二次写如也会创建头,然后在第一次的后面写入数据 excelWriter.write(data(), writeSheet, writeTable1); } finally { // 千万别忘记finish 会帮忙关闭流 if (excelWriter != null) { excelWriter.finish(); } } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void tableWrite() { String fileName = TestFileUtil.getPath() + "tableWrite" + System.currentTimeMillis() + ".xlsx"; // 这里直接写多个table的案例了,如果只有一个 也可以直一行代码搞定,参照其他案例 // 这里 需要指定写用哪个class去写 ExcelWriter excelWriter = null; try { excelWriter=EasyExcel.write(fileName, DemoData.class).build(); // 把sheet设置为不需要头 不然会输出sheet的头 这样看起来第一个table 就有2个头了 WriteSheet writeSheet = EasyExcel.writerSheet("模板").needHead(Boolean.FALSE).build(); // 这里必须指定需要头,table 会继承sheet的配置,sheet配置了不需要,table 默认也是不需要 WriteTable writeTable0 = EasyExcel.writerTable(0).needHead(Boolean.TRUE).build(); WriteTable writeTable1 = EasyExcel.writerTable(1).needHead(Boolean.TRUE).build(); // 第一次写入会创建头 excelWriter.write(data(), writeSheet, writeTable0); // 第二次写如也会创建头,然后在第一次的后面写入数据 excelWriter.write(data(), writeSheet, writeTable1); } finally { // 千万别忘记finish 会帮忙关闭流 if (excelWriter != null) { excelWriter.finish(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @GET @Path("/result_counter/{identifier}") @Produces("application/json") public EnumMap<ResultType, Integer> getCounterResults(@PathParam("identifier") String executionIdentifier) { try { return AlgorithmExecutionCache.getResultCounter(executionIdentifier).getResults(); } catch (Exception e) { throw new WebException("Could not find any progress to the given identifier", Response.Status.BAD_REQUEST); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @GET @Path("/result_counter/{identifier}") @Produces("application/json") public EnumMap<ResultType, Integer> getCounterResults(@PathParam("identifier") String executionIdentifier) { try { return this.resultCounts.get(executionIdentifier); } catch (Exception e) { throw new WebException("Could not find any progress to the given identifier", Response.Status.BAD_REQUEST); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected AlgorithmExecutor buildExecutor(String algorithmName) throws FileNotFoundException, UnsupportedEncodingException { FunctionalDependencyResultReceiver fdResultReceiver = new FunctionalDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); InclusionDependencyResultReceiver indResultReceiver = new InclusionDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); UniqueColumnCombinationResultReceiver uccResultReceiver = new UniqueColumnCombinationPrinter(getResultFileName(algorithmName), getResultDirectoryName()); FileGenerator fileGenerator = new TempFileGenerator(); return new AlgorithmExecutor(fdResultReceiver, indResultReceiver, uccResultReceiver, fileGenerator); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code protected AlgorithmExecutor buildExecutor(String algorithmName) throws FileNotFoundException, UnsupportedEncodingException { LinkedList<ResultPrinter> resultPrinters = new LinkedList<ResultPrinter>(); FunctionalDependencyPrinter fdResultReceiver = new FunctionalDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(fdResultReceiver); InclusionDependencyPrinter indResultReceiver = new InclusionDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(indResultReceiver); UniqueColumnCombinationPrinter uccResultReceiver = new UniqueColumnCombinationPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(uccResultReceiver); FileGenerator fileGenerator = new TempFileGenerator(); AlgorithmExecutor executor = new AlgorithmExecutor(fdResultReceiver, indResultReceiver, uccResultReceiver, fileGenerator); currentResultPrinters.put(algorithmName, resultPrinters); return executor; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void executeUniqueColumnCombinationsAlgorithmTest() { // Setup AlgorithmExecuter executer = new AlgorithmExecuter(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); List<ConfigurationValue> configs = new ArrayList<ConfigurationValue>(); configs.add(new ConfigurationValueString("pathToInputFile", "blub")); // Expected values ColumnCombination columnCombination = new ColumnCombination( new ColumnIdentifier("table1", "column1"), new ColumnIdentifier("table2", "column2")); // Execute executer.executeUniqueColumnCombinationsAlgorithm("example_algorithm-0.0.1-SNAPSHOT-jar-with-dependencies.jar", configs, new UniqueColumnCombinationPrinter(new PrintStream(outStream))); // Check result assertTrue(outStream.toString().contains(columnCombination.toString())); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void executeUniqueColumnCombinationsAlgorithmTest() { // Setup List<ConfigurationValue> configs = new ArrayList<ConfigurationValue>(); configs.add(new ConfigurationValueString("pathToInputFile", "blub")); UniqueColumnCombinationResultReceiver resultReceiver = mock(UniqueColumnCombinationFileWriter.class); // Execute executer.executeUniqueColumnCombinationsAlgorithm("example_algorithm-0.0.1-SNAPSHOT-jar-with-dependencies.jar", configs, resultReceiver); // Check result verify(resultReceiver).receiveResult(isA(ColumnCombination.class)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGenerateNewCsvFile() throws IOException { // Setup SimpleRelationalInput csv = generator.generateNewCsvFile(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCsvFile(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, IOException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void receiveResult(ColumnCombination columnCombination) { try { FileWriter writer = new FileWriter(this.file, true); writer.write(columnCombination.toString() + "\n"); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void receiveResult(ColumnCombination columnCombination) { appendToResultFile(columnCombination.toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected AlgorithmExecutor buildExecutor(String algorithmName) throws FileNotFoundException, UnsupportedEncodingException { FunctionalDependencyResultReceiver fdResultReceiver = new FunctionalDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); InclusionDependencyResultReceiver indResultReceiver = new InclusionDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); UniqueColumnCombinationResultReceiver uccResultReceiver = new UniqueColumnCombinationPrinter(getResultFileName(algorithmName), getResultDirectoryName()); FileGenerator fileGenerator = new TempFileGenerator(); return new AlgorithmExecutor(fdResultReceiver, indResultReceiver, uccResultReceiver, fileGenerator); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code protected AlgorithmExecutor buildExecutor(String algorithmName) throws FileNotFoundException, UnsupportedEncodingException { LinkedList<ResultPrinter> resultPrinters = new LinkedList<ResultPrinter>(); FunctionalDependencyPrinter fdResultReceiver = new FunctionalDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(fdResultReceiver); InclusionDependencyPrinter indResultReceiver = new InclusionDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(indResultReceiver); UniqueColumnCombinationPrinter uccResultReceiver = new UniqueColumnCombinationPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(uccResultReceiver); FileGenerator fileGenerator = new TempFileGenerator(); AlgorithmExecutor executor = new AlgorithmExecutor(fdResultReceiver, indResultReceiver, uccResultReceiver, fileGenerator); currentResultPrinters.put(algorithmName, resultPrinters); return executor; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGenerateNewCsvFile() throws IOException { // Setup SimpleRelationalInput csv = generator.generateNewCsvFile(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCsvFile(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, IOException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public T loadAlgorithm(String path) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException { String pathToFolder = ClassLoader.getSystemResource("algorithms").getPath(); File file = new File(URLDecoder.decode(pathToFolder + "/" + path, "utf-8")); JarFile jar = new JarFile(file); Manifest man = jar.getManifest(); Attributes attr = man.getMainAttributes(); String className = attr.getValue(bootstrapClassTagName); URL[] url = {file.toURI().toURL()}; ClassLoader loader = new URLClassLoader(url, algorithmSubclass.getClassLoader()); Class<? extends T> algorithmClass = Class.forName(className, true, loader).asSubclass(algorithmSubclass); return algorithmClass.getConstructor().newInstance(); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public T loadAlgorithm(String path) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException { String pathToFolder = ClassLoader.getSystemResource("algorithms").getPath(); File file = new File(URLDecoder.decode(pathToFolder + "/" + path, "utf-8")); JarFile jar = new JarFile(file); Manifest man = jar.getManifest(); Attributes attr = man.getMainAttributes(); String className = attr.getValue(bootstrapClassTagName); URL[] url = {file.toURI().toURL()}; ClassLoader loader = new URLClassLoader(url, algorithmSubclass.getClassLoader()); Class<? extends T> algorithmClass = Class.forName(className, true, loader).asSubclass(algorithmSubclass); jar.close(); return algorithmClass.getConstructor().newInstance(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAddAlgorithm() throws EntityStorageException { // Setup HibernateUtil.clear(); AlgorithmServiceImpl finderService = new AlgorithmServiceImpl(); // Execute functionality: add an IND algorithm Algorithm algorithm = new Algorithm("someFileName.jar"); algorithm.setInd(true); finderService.addAlgorithm(algorithm); // Check result assertTrue(finderService.listAllAlgorithms().contains(algorithm)); assertTrue( finderService.listAlgorithms(InclusionDependencyAlgorithm.class).contains(algorithm)); assertFalse(finderService.listAlgorithms(FunctionalDependencyAlgorithm.class).contains( algorithm)); // Cleanup HibernateUtil.clear(); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAddAlgorithm() throws EntityStorageException, AlgorithmLoadingException { // Setup HibernateUtil.clear(); AlgorithmServiceImpl finderService = new AlgorithmServiceImpl(); // Execute functionality: add an IND algorithm Algorithm algorithm = new Algorithm("example_ind_algorithm.jar"); finderService.addAlgorithm(algorithm); // Check result assertTrue(finderService.listAllAlgorithms().contains(algorithm)); assertTrue( finderService.listAlgorithms(InclusionDependencyAlgorithm.class).contains(algorithm)); assertFalse(finderService.listAlgorithms(FunctionalDependencyAlgorithm.class).contains( algorithm)); // Cleanup HibernateUtil.clear(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void executeAlgorithm(String algorithmName, List<InputParameter> parameters) throws AlgorithmConfigurationException, AlgorithmLoadingException, AlgorithmExecutionException { List<ConfigurationValue> configs = convertInputParameters(parameters); try { buildExecutor(algorithmName).executeAlgorithm(algorithmName, configs); } catch (FileNotFoundException e) { throw new AlgorithmExecutionException("Could not generate result file."); } catch (UnsupportedEncodingException e) { throw new AlgorithmExecutionException("Could not build temporary file generator."); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void executeAlgorithm(String algorithmName, List<InputParameter> parameters) throws AlgorithmConfigurationException, AlgorithmLoadingException, AlgorithmExecutionException { List<ConfigurationValue> configs = convertInputParameters(parameters); AlgorithmExecutor executor = null; try { executor = buildExecutor(algorithmName); } catch (FileNotFoundException e) { throw new AlgorithmExecutionException("Could not generate result file."); } catch (UnsupportedEncodingException e) { throw new AlgorithmExecutionException("Could not build temporary file generator."); } System.out.println("before execution"); executor.executeAlgorithm(algorithmName, configs); System.out.println("after execution & wait"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ConfigurationSettingCsvFile getValues() { if (this.listbox.getSelectedValue().equals("--")) { this.messageReceiver.addError("You must choose a CSV file!"); return null; } FileInput currentFileInput = this.fileInputs.get( this.listbox.getSelectedValue()); return getCurrentSetting(currentFileInput); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public ConfigurationSettingCsvFile getValues() throws InputValidationException { String selectedValue = this.listbox.getSelectedValue(); if (selectedValue.equals("--")) { throw new InputValidationException("You must choose a CSV file!"); } FileInput currentFileInput = this.fileInputs.get(selectedValue); return getCurrentSetting(currentFileInput); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, IOException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, InputIterationException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testUpdateOnSuccess() { // Set up TestHelper.resetDatabaseSync(); Execution execution = new Execution(null, 12); execution.setEnd(2345); BasePage parent = new BasePage(); ResultsPage page = new ResultsPage(parent); page.setMessageReceiver(new TabWrapper()); page.setExecutionParameter("identifier", "name"); page.startPolling(true); // Expected Values // Execute page.updateOnSuccess(null); // Check assertEquals(2, page.getWidgetCount()); assertTrue(page.getWidget(1) instanceof TabLayoutPanel); assertEquals(2, ((TabLayoutPanel) page.getWidget(1)).getWidgetCount()); // Cleanup TestHelper.resetDatabaseSync(); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code public void testUpdateOnSuccess() { // Set up TestHelper.resetDatabaseSync(); Algorithm algorithm = new Algorithm("example_ind_algorithm.jar"); Execution execution = new Execution(algorithm, 12); execution.setEnd(2345); BasePage parent = new BasePage(); ResultsPage page = new ResultsPage(parent); page.setMessageReceiver(new TabWrapper()); page.setExecutionParameter("identifier", "name"); page.startPolling(true); // Expected Values // Execute page.updateOnSuccess(execution); // Check assertEquals(2, page.getWidgetCount()); assertTrue(page.getWidget(1) instanceof TabLayoutPanel); assertEquals(2, ((TabLayoutPanel) page.getWidget(1)).getWidgetCount()); // Cleanup TestHelper.resetDatabaseSync(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<Result> fetchNewResults(String algorithmName){ List<Result> newResults = new LinkedList<Result>(); for (ResultPrinter printer : currentResultPrinters.get(algorithmName)) { // newResults.addAll(printer.getNewResults()); } newResults.add(new UniqueColumnCombination(new ColumnIdentifier("table", "col1"))); return newResults; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public List<Result> fetchNewResults(String algorithmName){ List<Result> newResults = new LinkedList<Result>(); //newResults.add(currentResultReceivers.get(algorithmName).getNewResults()); newResults.add(new UniqueColumnCombination(new ColumnIdentifier("table", "col1"))); return newResults; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAddAlgorithm() throws EntityStorageException { // Setup HibernateUtil.clear(); AlgorithmServiceImpl finderService = new AlgorithmServiceImpl(); // Execute functionality: add an IND algorithm Algorithm algorithm = new Algorithm("someFileName.jar"); algorithm.setInd(true); finderService.addAlgorithm(algorithm); // Check result assertTrue(finderService.listAllAlgorithms().contains(algorithm)); assertTrue( finderService.listAlgorithms(InclusionDependencyAlgorithm.class).contains(algorithm)); assertFalse(finderService.listAlgorithms(FunctionalDependencyAlgorithm.class).contains( algorithm)); // Cleanup HibernateUtil.clear(); } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAddAlgorithm() throws EntityStorageException, AlgorithmLoadingException { // Setup HibernateUtil.clear(); AlgorithmServiceImpl finderService = new AlgorithmServiceImpl(); // Execute functionality: add an IND algorithm Algorithm algorithm = new Algorithm("example_ind_algorithm.jar"); finderService.addAlgorithm(algorithm); // Check result assertTrue(finderService.listAllAlgorithms().contains(algorithm)); assertTrue( finderService.listAlgorithms(InclusionDependencyAlgorithm.class).contains(algorithm)); assertFalse(finderService.listAlgorithms(FunctionalDependencyAlgorithm.class).contains( algorithm)); // Cleanup HibernateUtil.clear(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<Class<?>> getAlgorithmInterfaces(File file) throws IOException, ClassNotFoundException { JarFile jar = new JarFile(file); Manifest man = jar.getManifest(); Attributes attr = man.getMainAttributes(); String className = attr.getValue(bootstrapClassTagName); URL[] url = {file.toURI().toURL()}; ClassLoader loader = new URLClassLoader(url, Algorithm.class.getClassLoader()); Class<?> algorithmClass = Class.forName(className, false, loader); return Arrays.asList(algorithmClass.getInterfaces()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public List<Class<?>> getAlgorithmInterfaces(File file) throws IOException, ClassNotFoundException { JarFile jar = new JarFile(file); Manifest man = jar.getManifest(); Attributes attr = man.getMainAttributes(); String className = attr.getValue(bootstrapClassTagName); URL[] url = {file.toURI().toURL()}; ClassLoader loader = new URLClassLoader(url, Algorithm.class.getClassLoader()); Class<?> algorithmClass = Class.forName(className, false, loader); jar.close(); return Arrays.asList(algorithmClass.getInterfaces()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, IOException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, InputIterationException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected AlgorithmExecutor buildExecutor(String executionIdentifier) throws FileNotFoundException, UnsupportedEncodingException { ResultPrinter resultPrinter = new ResultPrinter(executionIdentifier, "results"); ResultsCache resultsCache = new ResultsCache(); ResultsHub resultsHub = new ResultsHub(); resultsHub.addSubscriber(resultPrinter); resultsHub.addSubscriber(resultsCache); FileGenerator fileGenerator = new TempFileGenerator(); ProgressCache progressCache = new ProgressCache(); AlgorithmExecutor executor = new AlgorithmExecutor(resultsHub, progressCache, fileGenerator); AlgorithmExecutionCache.add(executionIdentifier, resultsCache, progressCache); return executor; } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code protected AlgorithmExecutor buildExecutor(String executionIdentifier) throws FileNotFoundException, UnsupportedEncodingException { ResultPrinter resultPrinter = new ResultPrinter(executionIdentifier); ResultsCache resultsCache = new ResultsCache(); ResultsHub resultsHub = new ResultsHub(); resultsHub.addSubscriber(resultPrinter); resultsHub.addSubscriber(resultsCache); FileGenerator fileGenerator = new TempFileGenerator(); ProgressCache progressCache = new ProgressCache(); AlgorithmExecutor executor = new AlgorithmExecutor(resultsHub, progressCache, fileGenerator); executor.setResultPathPrefix(resultPrinter.getOutputFilePathPrefix()); AlgorithmExecutionCache.add(executionIdentifier, resultsCache, progressCache); return executor; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testStoreTableInput() throws EntityStorageException, InputValidationException { // Setup TestHelper.resetDatabaseSync(); BasePage parent = new BasePage(); InputConfigurationPage page = new InputConfigurationPage(parent); page.setErrorReceiver(new TabWrapper()); DatabaseConnection dbConnection = new DatabaseConnection(); dbConnection.setId(1); dbConnection.setUrl("url"); dbConnection.setPassword("password"); dbConnection.setUsername("db"); TestHelper.storeDatabaseConnectionSync(dbConnection); page.tableInputField.setValues("1: url", "table"); page.tableInputFieldSelected = true; page.dbFieldSelected = false; page.fileInputFieldSelected = false; page.content.clear(); page.content.add(page.tableInputField); // Execute page.saveObject(); // Expected values TableInput expectedInput = page.tableInputField.getValue(); // Check result assertTrue(TestHelper.getAllTableInputs().contains(expectedInput)); // Cleanup TestHelper.resetDatabaseSync(); } #location 28 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testStoreTableInput() throws EntityStorageException, InputValidationException { // Setup TestHelper.resetDatabaseSync(); final boolean[] blocked = {true}; BasePage parent = new BasePage(); InputConfigurationPage page = new InputConfigurationPage(parent); page.setErrorReceiver(new TabWrapper()); DatabaseConnection dbConnection = new DatabaseConnection(); dbConnection.setUrl("url"); dbConnection.setPassword("password"); dbConnection.setUsername("db"); TestHelper.storeDatabaseConnectionSync(dbConnection); page.tableInputField.setValues("1: url", "table"); page.tableInputFieldSelected = true; page.dbFieldSelected = false; page.fileInputFieldSelected = false; page.content.clear(); page.content.add(page.tableInputField); // Execute page.saveObject(); // Expected values final TableInput expectedInput = page.tableInputField.getValue(); // Check result TestHelper.getAllTableInputs( new AsyncCallback<List<TableInput>>() { @Override public void onFailure(Throwable throwable) { fail(); } @Override public void onSuccess(List<TableInput> con) { blocked[0] = false; assertTrue(con.contains(expectedInput)); } }); Timer rpcCheck = new Timer() { @Override public void run() { if (blocked[0]) { this.schedule(100); } } }; rpcCheck.schedule(100); // Cleanup TestHelper.resetDatabaseSync(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNextSeparator() throws IOException { // Setup CsvFileOneLineFixture fixtureSeparator = new CsvFileOneLineFixture(';'); CsvFile csvFileSeparator = fixtureSeparator.getTestData(); // Check result assertEquals(fixtureSeparator.getExpectedStrings(), csvFileSeparator.next()); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testNextSeparator() throws InputIterationException { // Setup CsvFileOneLineFixture fixtureSeparator = new CsvFileOneLineFixture(';'); CsvFile csvFileSeparator = fixtureSeparator.getTestData(); // Check result assertEquals(fixtureSeparator.getExpectedStrings(), csvFileSeparator.next()); }
Below is the vulnerable code, please generate the patch based on the following information.