output
stringlengths
79
30.1k
instruction
stringclasses
1 value
input
stringlengths
216
28.9k
#fixed code private void incrementalCompile( Set<Object> drivers ) { for( Object driver: drivers ) { //noinspection unchecked Set<IFile> files = ((Collection<File>)ReflectUtil.method( driver, "getResourceFiles" ).invoke() ).stream().map( (File f) -> ManifoldHost.getFileSystem().getIFile( f ) ) .collect( Collectors.toSet() ); for( ITypeManifold tm : ManifoldHost.instance().getCurrentModule().getTypeManifolds() ) { for( IFile file: files ) { Set<String> types = Arrays.stream( tm.getTypesForFile( file ) ).collect( Collectors.toSet() ); if( types.size() > 0 ) { ReflectUtil.method( driver, "mapTypesToFile", Set.class, File.class ).invoke( types, file.toJavaFile() ); for( String fqn : types ) { // This call surfaces the type in the compiler. If compiling in "static" mode, this means // the type will be compiled to disk. IDynamicJdk.instance().getTypeElement( _tp.getContext(), (JCTree.JCCompilationUnit)_tp.getCompilationUnit(), fqn ); } } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void incrementalCompile( Set<Object> drivers ) { JavacElements elementUtils = JavacElements.instance( _tp.getContext() ); for( Object driver: drivers ) { //noinspection unchecked Set<IFile> files = ((Collection<File>)ReflectUtil.method( driver, "getResourceFiles" ).invoke() ).stream().map( (File f) -> ManifoldHost.getFileSystem().getIFile( f ) ) .collect( Collectors.toSet() ); for( ITypeManifold tm : ManifoldHost.instance().getCurrentModule().getTypeManifolds() ) { for( IFile file: files ) { Set<String> types = Arrays.stream( tm.getTypesForFile( file ) ).collect( Collectors.toSet() ); if( types.size() > 0 ) { ReflectUtil.method( driver, "mapTypesToFile", Set.class, File.class ).invoke( types, file.toJavaFile() ); for( String fqn : types ) { // This call surfaces the type in the compiler. If compiling in "static" mode, this means // the type will be compiled to disk. elementUtils.getTypeElement( fqn ); } } } } } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Collection<String> getAllTypeNames() { FqnCache<LocklessLazyVar<M>> fqnCache = _fqnToModel.get(); if( fqnCache.isEmpty() ) { return Collections.emptySet(); } return fqnCache.getFqns(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Collection<String> getAllTypeNames() { return _fqnToModel.get().getFqns(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public Tree getParent( Tree node ) { return _parents.getParent( node ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Tree getParent( Tree node ) { TreePath2 path = TreePath2.getPath( getCompilationUnit(), node ); if( path == null ) { // null is indiciative of Generation phase where trees are no longer attached to symobls so the comp unit is detached // use the root tree instead, which is mostly ok, mostly path = TreePath2.getPath( _tree, node ); } TreePath2 parentPath = path.getParentPath(); return parentPath == null ? null : parentPath.getLeaf(); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code public ItemList getDataItemList() throws RiotApiException { return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, (ItemListData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ItemList getDataItemList() throws RiotApiException { return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public RiotApiException getException() { return exception; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RiotApiException getException() { if (!isFailed()) { return null; } return exception; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected static CharSequence encodeUriQuery(CharSequence in) { //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things. StringBuilder outBuf = null; Formatter formatter = null; for(int i = 0; i < in.length(); i++) { char c = in.charAt(i); boolean escape = true; if (c < 128) { if (asciiQueryChars.get((int)c)) { escape = false; } } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii escape = false; } if (!escape) { if (outBuf != null) outBuf.append(c); } else { //escape if (outBuf == null) { outBuf = new StringBuilder(in.length() + 5*3); outBuf.append(in,0,i); try { formatter = new Formatter(outBuf); } finally { if (formatter != null) { formatter.flush(); formatter.close(); } } } //leading %, 0 padded, width 2, capital hex formatter.format("%%%02X",(int)c);//TODO } } return outBuf != null ? outBuf : in; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected static CharSequence encodeUriQuery(CharSequence in) { //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things. StringBuilder outBuf = null; Formatter formatter = null; for(int i = 0; i < in.length(); i++) { char c = in.charAt(i); boolean escape = true; if (c < 128) { if (asciiQueryChars.get((int)c)) { escape = false; } } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii escape = false; } if (!escape) { if (outBuf != null) outBuf.append(c); } else { //escape if (outBuf == null) { outBuf = new StringBuilder(in.length() + 5*3); outBuf.append(in,0,i); formatter = new Formatter(outBuf); } //leading %, 0 padded, width 2, capital hex formatter.format("%%%02X",(int)c);//TODO } } return outBuf != null ? outBuf : in; } #location 29 #vulnerability type RESOURCE_LEAK
#fixed code public static UrlBuilder fromString(final String url, final Charset inputEncoding) { if (url.isEmpty()) { return new UrlBuilder(); } final Matcher m = URI_PATTERN.matcher(url); String protocol = null, hostName = null, path = null, anchor = null; Integer port = null; final Map<String, List<String>> queryParameters; if (m.find()) { protocol = m.group(2); if (m.group(4) != null) { final Matcher n = AUTHORITY_PATTERN.matcher(m.group(4)); if (n.find()) { hostName = IDN.toUnicode(n.group(1)); if (n.group(3) != null) { port = Integer.parseInt(n.group(3)); } } } path = decodePath(m.group(5), inputEncoding); queryParameters = decodeQueryParameters(m.group(7), inputEncoding); anchor = m.group(9); } else { queryParameters = emptyMap(); } return of(inputEncoding, DEFAULT_ENCODING, protocol, hostName, port, path, queryParameters, anchor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static UrlBuilder fromString(final String url, final Charset inputEncoding) { if (url.isEmpty()) { return new UrlBuilder(); } final Matcher m = URI_PATTERN.matcher(url); String protocol = null, hostName = null, path = null, anchor = null; Integer port = null; Map<String, List<String>> queryParameters = null; if (m.find()) { protocol = m.group(2); if (m.group(4) != null) { final Matcher n = AUTHORITY_PATTERN.matcher(m.group(4)); if (n.find()) { hostName = IDN.toUnicode(n.group(1)); if (n.group(3) != null) { port = Integer.parseInt(n.group(3)); } } } path = decodePath(m.group(5), inputEncoding); queryParameters = decodeQueryParameters(m.group(7), inputEncoding); anchor = m.group(9); } return of(inputEncoding, DEFAULT_ENCODING, protocol, hostName, port, path, queryParameters, anchor); } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code public static ClassName get(Class<?> clazz) { checkNotNull(clazz, "clazz == null"); checkArgument(!clazz.isPrimitive(), "primitive types cannot be represented as a ClassName"); checkArgument(!void.class.equals(clazz), "'void' type cannot be represented as a ClassName"); checkArgument(!clazz.isArray(), "array types cannot be represented as a ClassName"); String anonymousSuffix = ""; while (clazz.isAnonymousClass()) { int lastDollar = clazz.getName().lastIndexOf('$'); anonymousSuffix = clazz.getName().substring(lastDollar) + anonymousSuffix; clazz = clazz.getEnclosingClass(); } String name = clazz.getSimpleName() + anonymousSuffix; if (clazz.getEnclosingClass() == null) { // Avoid unreliable Class.getPackage(). https://github.com/square/javapoet/issues/295 int lastDot = clazz.getName().lastIndexOf('.'); String packageName = (lastDot != -1) ? clazz.getName().substring(0, lastDot) : NO_PACKAGE; return new ClassName(packageName, null, name); } return ClassName.get(clazz.getEnclosingClass()).nestedClass(name); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ClassName get(Class<?> clazz) { checkNotNull(clazz, "clazz == null"); checkArgument(!clazz.isPrimitive(), "primitive types cannot be represented as a ClassName"); checkArgument(!void.class.equals(clazz), "'void' type cannot be represented as a ClassName"); checkArgument(!clazz.isArray(), "array types cannot be represented as a ClassName"); String anonymousSuffix = ""; while (clazz.isAnonymousClass()) { int lastDollar = clazz.getName().lastIndexOf('$'); anonymousSuffix = clazz.getName().substring(lastDollar) + anonymousSuffix; clazz = clazz.getEnclosingClass(); } String name = clazz.getSimpleName() + anonymousSuffix; if (clazz.getEnclosingClass() == null) { // Avoid unreliable Class.getPackage(). https://github.com/square/javapoet/issues/295 int lastDot = clazz.getName().lastIndexOf('.'); String packageName = (lastDot != -1) ? clazz.getName().substring(0, lastDot) : null; return new ClassName(packageName, null, name); } return ClassName.get(clazz.getEnclosingClass()).nestedClass(name); } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @SuppressWarnings("unchecked") private static Deserializer deserializer(File file, PoijiOptions options) { final PoijiStream poiParser = new PoijiStream(file); final PoiWorkbook workbook = PoiWorkbook.workbook(Files.getExtension(file.getName()), poiParser); return Deserializer.instance(workbook, options); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") private static Deserializer deserializer(File file, PoijiOptions options) throws FileNotFoundException { final PoijiStream poiParser = new PoijiStream(fileInputStream(file)); final PoiWorkbook workbook = PoiWorkbook.workbook(Files.getExtension(file.getName()), poiParser); return Deserializer.instance(workbook, options); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private ZipInputStream prepareZipInputStream() throws ZipException { try { splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); FileHeader fileHeader = getFirstFileHeader(getZipModel()); if (fileHeader != null) { splitInputStream.prepareExtractionForFileHeader(fileHeader); } return new ZipInputStream(splitInputStream, password); } catch (IOException e) { throw new ZipException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ZipInputStream prepareZipInputStream() throws ZipException { try { SplitInputStream splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); FileHeader fileHeader = getFirstFileHeader(getZipModel()); if (fileHeader != null) { splitInputStream.prepareExtractionForFileHeader(fileHeader); } return new ZipInputStream(splitInputStream, password); } catch (IOException e) { throw new ZipException(e); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code private ZipInputStream prepareZipInputStream() throws ZipException { try { splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); FileHeader fileHeader = getFirstFileHeader(getZipModel()); if (fileHeader != null) { splitInputStream.prepareExtractionForFileHeader(fileHeader); } return new ZipInputStream(splitInputStream, password); } catch (IOException e) { throw new ZipException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ZipInputStream prepareZipInputStream() throws ZipException { try { SplitInputStream splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); FileHeader fileHeader = getFirstFileHeader(getZipModel()); if (fileHeader != null) { splitInputStream.prepareExtractionForFileHeader(fileHeader); } return new ZipInputStream(splitInputStream, password); } catch (IOException e) { throw new ZipException(e); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void bidiBackpressure() throws InterruptedException { RxNumbersGrpc.RxNumbersStub stub = RxNumbersGrpc.newRxStub(channel); Flowable<NumberProto.Number> rxRequest = Flowable .fromIterable(IntStream.range(0, NUMBER_OF_STREAM_ELEMENTS)::iterator) .doOnNext(i -> System.out.println(i + " --> ")) .doOnNext(i -> updateNumberOfWaits(clientLastValueTime, clientNbOfWaits)) .map(BackpressureIntegrationTest::protoNum); TestSubscriber<NumberProto.Number> rxResponse = stub.twoWayPressure(rxRequest) .doOnNext(n -> System.out.println(n.getNumber(0) + " <--")) .doOnNext(n -> waitIfValuesAreEqual(n.getNumber(0), 3)) .test(); rxResponse.awaitTerminalEvent(5, TimeUnit.SECONDS); rxResponse.assertComplete().assertValueCount(NUMBER_OF_STREAM_ELEMENTS); assertThat(clientNbOfWaits.get()).isEqualTo(1); assertThat(serverNumberOfWaits.get()).isEqualTo(1); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void bidiBackpressure() throws InterruptedException { Object lock = new Object(); BackpressureDetector clientReqBPDetector = new BackpressureDetector(madMultipleCutoff); BackpressureDetector clientRespBPDetector = new BackpressureDetector(madMultipleCutoff); RxNumbersGrpc.RxNumbersStub stub = RxNumbersGrpc.newRxStub(channel); Flowable<NumberProto.Number> rxRequest = Flowable .fromIterable(new Sequence(180, clientReqBPDetector)) .doOnNext(i -> System.out.println(i + " -->")) .map(BackpressureIntegrationTest::protoNum); Flowable<NumberProto.Number> rxResponse = stub.twoWayPressure(rxRequest); rxResponse.subscribe( n -> { clientRespBPDetector.tick(); System.out.println(" " + n.getNumber(0) + " <--"); try { Thread.sleep(50); } catch (InterruptedException e) {} }, t -> { t.printStackTrace(); synchronized (lock) { lock.notify(); } }, () -> { System.out.println("Client done."); synchronized (lock) { lock.notify(); } }); synchronized (lock) { lock.wait(TimeUnit.SECONDS.toMillis(20)); } assertThat(clientReqBPDetector.backpressureDelayOcurred()).isTrue(); assertThat(serverRespBPDetector.backpressureDelayOcurred()).isTrue(); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { final Set<String> artifacts = new HashSet<>(); installNodeModules(artifacts); final File base = new File(cwd, "node_modules"); final File libs = new File(base, ".lib"); if (force || libs.exists()) { final double version = Double.parseDouble(System.getProperty("java.specification.version")); final boolean isGraalVM = System.getProperty("java.vm.name", "").toLowerCase().contains("graalvm") || // from graal 20.0.0 the vm name doesn't contain graalvm in the name // but it is now part of the vendor version System.getProperty("java.vendor.version", "").toLowerCase().contains("graalvm"); if (!isGraalVM) { // not on graal, install graaljs and dependencies warn("Installing GraalJS..."); // graaljs + dependencies installGraalJS(artifacts); if (version >= 11) { // verify if the current JDK contains the jdk.internal.vm.ci module try { String modules = exec(javaHomePrefix() + "java", "--list-modules"); if (modules.contains("jdk.internal.vm.ci")) { warn("Installing JVMCI Compiler..."); // jvmci compiler + dependencies installGraalJMVCICompiler(); } } catch (IOException | InterruptedException e) { err(e.getMessage()); } } else { warn("Current JDK only supports GraalJS in Interpreted mode!"); } } } // always create a launcher even if no dependencies are needed createLauncher(artifacts); // always install the es4x type definitions installTypeDefinitions(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { final Set<String> artifacts = new HashSet<>(); installNodeModules(artifacts); final File base = new File(cwd, "node_modules"); final File libs = new File(base, ".lib"); if (force || libs.exists()) { final double version = Double.parseDouble(System.getProperty("java.specification.version")); final String vm = System.getProperty("java.vm.name"); // from graal 20.0.0 the vm name doesn't contain graalvm in the name // but it is now part of the vendor version final String vendor = System.getProperty("java.vendor.version"); if (!vm.toLowerCase().contains("graalvm") && vendor != null && !vendor.toLowerCase().contains("graalvm")) { // not on graal, install graaljs and dependencies warn("Installing GraalJS..."); // graaljs + dependencies installGraalJS(artifacts); if (version >= 11) { // verify if the current JDK contains the jdk.internal.vm.ci module try { String modules = exec(javaHomePrefix() + "java", "--list-modules"); if (modules.contains("jdk.internal.vm.ci")) { warn("Installing JVMCI Compiler..."); // jvmci compiler + dependencies installGraalJMVCICompiler(); } } catch (IOException | InterruptedException e) { err(e.getMessage()); } } else { warn("Current JDK only supports GraalJS in Interpreted mode!"); } } } // always create a launcher even if no dependencies are needed createLauncher(artifacts); // always install the es4x type definitions installTypeDefinitions(); } #location 15 #vulnerability type NULL_DEREFERENCE
#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 @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 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); } 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 @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 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 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 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 @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 @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 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 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 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 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void startDb() { postgres = new MyPostgreSQLContainer() .withDatabaseName(TEST_SCHEMA_NAME) .withUsername("SA") .withPassword("pass") .withLogConsumer(new Consumer<OutputFrame>() { @Override public void accept(OutputFrame outputFrame) { logger.debug(outputFrame.getUtf8String()); } }); postgres.start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void startDb() { postgres = (PostgreSQLContainer) new PostgreSQLContainer() .withDatabaseName(TEST_SCHEMA_NAME) .withUsername("SA") .withPassword("pass") .withLogConsumer(new Consumer<OutputFrame>() { @Override public void accept(OutputFrame outputFrame) { logger.debug(outputFrame.getUtf8String()); } }); postgres.start(); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(dp.content()); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) { temp = ku; } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } try { Thread.sleep(this.interval); } catch (InterruptedException ex) { } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); pqueue.add(ku); } ku.input(dp.content()); } //选出第一个kcp更新状态 KcpOnUdp first = pqueue.poll(); if(first != null && first.getTimeout() < System.currentTimeMillis()) { first.update(); if(!first.isClosed()) { pqueue.add(first); } else { this.kcps.remove((InetSocketAddress) first.getKcp().getUser()); } } //每30s,更新一遍所有的kcp状态 if(System.currentTimeMillis()%(1000*30) == 0) { //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) {//删掉过时的kcp this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); pqueue.remove(ku); } } } //等待 try { synchronized(wakeup){ wakeup.wait(5*60*1000); } } catch (InterruptedException ex) { Logger.getLogger(KcpThread.class.getName()).log(Level.SEVERE, null, ex); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static Instances createBootstrapSample(Instances instances) { Random rand = Random.getInstance(); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < instances.size(); i++) { int idx = rand.nextInt(instances.size()); map.put(idx, map.getOrDefault(idx, 0) + 1); } Instances bag = new Instances(instances.getAttributes(), instances.getTargetAttribute(), map.size()); for (Integer idx : map.keySet()) { int weight = map.get(idx); Instance instance = instances.get(idx).clone(); instance.setWeight(weight); bag.add(instance); } return bag; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Instances createBootstrapSample(Instances instances) { Random rand = Random.getInstance(); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < instances.size(); i++) { int idx = rand.nextInt(instances.size()); if (!map.containsKey(idx)) { map.put(idx, 0); } map.put(idx, map.get(idx) + 1); } Instances bag = new Instances(instances.getAttributes(), instances.getTargetAttribute(), map.size()); for (Integer idx : map.keySet()) { int weight = map.get(idx); Instance instance = instances.get(idx).clone(); instance.setWeight(weight); bag.add(instance); } return bag; } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public void commit(Transaction transaction) throws RollbackException, TransactionException { if (LOG.isTraceEnabled()) { LOG.trace("commit " + transaction); } if (transaction.getStatus() != Status.RUNNING) { throw new IllegalArgumentException("Transaction has already been " + transaction.getStatus()); } // Check rollbackOnly status if (transaction.isRollbackOnly()) { rollback(transaction); throw new RollbackException(); } // Flush all pending writes if (!flushTables(transaction)) { cleanup(transaction); throw new RollbackException(); } SyncCommitCallback cb = new SyncCommitCallback(); TimerContext commitTimer = tsoclient.getMetrics().startTimer(Timers.COMMIT); try { tsoclient.commit(transaction.getStartTimestamp(), transaction.getRows(), cb); cb.await(); } catch (Exception e) { throw new TransactionException("Could not commit", e); } finally { commitTimer.stop(); } if (cb.getException() != null) { throw new TransactionException("Error committing", cb.getException()); } if (LOG.isTraceEnabled()) { LOG.trace("doneCommit " + transaction.getStartTimestamp() + " TS_c: " + cb.getCommitTimestamp() + " Success: " + (cb.getResult() == TSOClient.Result.OK)); } if (cb.getResult() == TSOClient.Result.ABORTED) { cleanup(transaction); throw new RollbackException(); } transaction.setStatus(Status.COMMITTED); transaction.setCommitTimestamp(cb.getCommitTimestamp()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void commit(Transaction transaction) throws RollbackException, TransactionException { if (LOG.isTraceEnabled()) { LOG.trace("commit " + transaction); } // Check rollbackOnly status if (transaction.isRollbackOnly()) { rollback(transaction); throw new RollbackException(); } // Flush all pending writes if (!flushTables(transaction)) { cleanup(transaction); throw new RollbackException(); } SyncCommitCallback cb = new SyncCommitCallback(); TimerContext commitTimer = tsoclient.getMetrics().startTimer(Timers.COMMIT); try { tsoclient.commit(transaction.getStartTimestamp(), transaction.getRows(), cb); cb.await(); } catch (Exception e) { throw new TransactionException("Could not commit", e); } finally { commitTimer.stop(); } if (cb.getException() != null) { throw new TransactionException("Error committing", cb.getException()); } if (LOG.isTraceEnabled()) { LOG.trace("doneCommit " + transaction.getStartTimestamp() + " TS_c: " + cb.getCommitTimestamp() + " Success: " + (cb.getResult() == TSOClient.Result.OK)); } if (cb.getResult() == TSOClient.Result.ABORTED) { cleanup(transaction); throw new RollbackException(); } transaction.setCommitTimestamp(cb.getCommitTimestamp()); } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void runTestWriteWriteConflict() throws Exception { TransactionManager tm = new TransactionManager(hbaseConf); TTable tt = new TTable(hbaseConf, TEST_TABLE); TransactionState t1 = tm.beginTransaction(); LOG.info("Transaction created " + t1); TransactionState t2 = tm.beginTransaction(); LOG.info("Transaction created" + t2); byte[] row = Bytes.toBytes("test-simple"); byte[] fam = Bytes.toBytes(TEST_FAMILY); byte[] col = Bytes.toBytes("testdata"); byte[] data1 = Bytes.toBytes("testWrite-1"); byte[] data2 = Bytes.toBytes("testWrite-2"); Put p = new Put(row); p.add(fam, col, data1); tt.put(t1, p); Put p2 = new Put(row); p2.add(fam, col, data2); tt.put(t2, p2); tm.tryCommit(t2); boolean aborted = false; try { tm.tryCommit(t1); assertTrue("Transaction commited successfully", false); } catch (CommitUnsuccessfulException e) { aborted = true; } assertTrue("Transaction didn't raise exception", aborted); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void runTestWriteWriteConflict() throws Exception { TransactionManager tm = new TransactionManager(hbaseConf); TransactionalTable tt = new TransactionalTable(hbaseConf, TEST_TABLE); TransactionState t1 = tm.beginTransaction(); LOG.info("Transaction created " + t1); TransactionState t2 = tm.beginTransaction(); LOG.info("Transaction created" + t2); byte[] row = Bytes.toBytes("test-simple"); byte[] fam = Bytes.toBytes(TEST_FAMILY); byte[] col = Bytes.toBytes("testdata"); byte[] data1 = Bytes.toBytes("testWrite-1"); byte[] data2 = Bytes.toBytes("testWrite-2"); Put p = new Put(row); p.add(fam, col, data1); tt.put(t1, p); Put p2 = new Put(row); p2.add(fam, col, data2); tt.put(t2, p2); tm.tryCommit(t2); boolean aborted = false; try { tm.tryCommit(t1); assertTrue("Transaction commited successfully", false); } catch (CommitUnsuccessfulException e) { aborted = true; } assertTrue("Transaction didn't raise exception", aborted); } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @Test(timeOut = 30_000) public void runTestInterleaveScanWhenATransactionAborts() throws Exception { TransactionManager tm = newTransactionManager(); TTable tt = new TTable(hbaseConf, TEST_TABLE); Transaction t1 = tm.begin(); LOG.info("Transaction created " + t1); byte[] fam = Bytes.toBytes(TEST_FAMILY); byte[] col = Bytes.toBytes("testdata"); byte[] data1 = Bytes.toBytes("testWrite-1"); byte[] data2 = Bytes.toBytes("testWrite-2"); byte[] startrow = Bytes.toBytes("test-scan" + 0); byte[] stoprow = Bytes.toBytes("test-scan" + 9); byte[] modrow = Bytes.toBytes("test-scan" + 3); for (int i = 0; i < 10; i++) { byte[] row = Bytes.toBytes("test-scan" + i); Put p = new Put(row); p.add(fam, col, data1); tt.put(t1, p); } tm.commit(t1); Transaction t2 = tm.begin(); Put p = new Put(modrow); p.add(fam, col, data2); tt.put(t2, p); int modifiedrows = 0; ResultScanner rs = tt.getScanner(t2, new Scan().setStartRow(startrow).setStopRow(stoprow).addColumn(fam, col)); Result r = rs.next(); while (r != null) { if (Bytes.equals(data2, r.getValue(fam, col))) { if (LOG.isTraceEnabled()) { LOG.trace("Modified :" + Bytes.toString(r.getRow())); } modifiedrows++; } r = rs.next(); } assertTrue(modifiedrows == 1, "Expected 1 row modified, but " + modifiedrows + " are."); tm.rollback(t2); Transaction tscan = tm.begin(); rs = tt.getScanner(tscan, new Scan().setStartRow(startrow).setStopRow(stoprow).addColumn(fam, col)); r = rs.next(); while (r != null) { if (LOG.isTraceEnabled()) { LOG.trace("Scan1 :" + Bytes.toString(r.getRow()) + " => " + Bytes.toString(r.getValue(fam, col))); } assertTrue(Bytes.equals(data1, r.getValue(fam, col)), "Unexpected value for SI scan " + tscan + ": " + Bytes.toString(r.getValue(fam, col))); r = rs.next(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeOut = 30_000) public void runTestInterleaveScanWhenATransactionAborts() throws Exception { TransactionManager tm = newTransactionManager(); TTable tt = new TTable(hbaseConf, TEST_TABLE); Transaction t1 = tm.begin(); LOG.info("Transaction created " + t1); byte[] fam = Bytes.toBytes(TEST_FAMILY); byte[] col = Bytes.toBytes("testdata"); byte[] data1 = Bytes.toBytes("testWrite-1"); byte[] data2 = Bytes.toBytes("testWrite-2"); byte[] startrow = Bytes.toBytes("test-scan" + 0); byte[] stoprow = Bytes.toBytes("test-scan" + 9); byte[] modrow = Bytes.toBytes("test-scan" + 3); for (int i = 0; i < 10; i++) { byte[] row = Bytes.toBytes("test-scan" + i); Put p = new Put(row); p.add(fam, col, data1); tt.put(t1, p); } tm.commit(t1); Transaction t2 = tm.begin(); Put p = new Put(modrow); p.add(fam, col, data2); tt.put(t2, p); int modifiedrows = 0; ResultScanner rs = tt.getScanner(t2, new Scan().setStartRow(startrow).setStopRow(stoprow).addColumn(fam, col)); Result r = rs.next(); while (r != null) { if (Bytes.equals(data2, r.getValue(fam, col))) { if (LOG.isTraceEnabled()) { LOG.trace("Modified :" + Bytes.toString(r.getRow())); } modifiedrows++; } r = rs.next(); } assertTrue(modifiedrows == 1, "Expected 1 row modified, but " + modifiedrows + " are."); tm.rollback(t2); Transaction tscan = tm.begin(); rs = tt.getScanner(tscan, new Scan().setStartRow(startrow).setStopRow(stoprow).addColumn(fam, col)); r = rs.next(); while (r != null) { if (LOG.isTraceEnabled()) { LOG.trace("Scan1 :" + Bytes.toString(r.getRow()) + " => " + Bytes.toString(r.getValue(fam, col))); } assertTrue(Bytes.equals(data1, r.getValue(fam, col)), "Unexpected value for SI scan " + tscan + ": " + Bytes.toString(r.getValue(fam, col))); r = rs.next(); } } #location 46 #vulnerability type RESOURCE_LEAK
#fixed code public byte[] getChannelConfigurationBytes() throws TransactionException { try { final Block configBlock = getConfigBlock(getRandomPeer()); Envelope envelopeRet = Envelope.parseFrom(configBlock.getData().getData(0)); Payload payload = Payload.parseFrom(envelopeRet.getPayload()); ConfigEnvelope configEnvelope = ConfigEnvelope.parseFrom(payload.getData()); return configEnvelope.getConfig().toByteArray(); } catch (Exception e) { throw new TransactionException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public byte[] getChannelConfigurationBytes() throws TransactionException { try { final Block configBlock = getConfigurationBlock(); Envelope envelopeRet = Envelope.parseFrom(configBlock.getData().getData(0)); Payload payload = Payload.parseFrom(envelopeRet.getPayload()); ConfigEnvelope configEnvelope = ConfigEnvelope.parseFrom(payload.getData()); return configEnvelope.getConfig().toByteArray(); } catch (Exception e) { throw new TransactionException(e); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code Orderer(String name, String url, Properties properties) throws InvalidArgumentException { if (StringUtil.isNullOrEmpty(name)) { throw new InvalidArgumentException("Invalid name for orderer"); } Exception e = checkGrpcUrl(url); if (e != null) { throw new InvalidArgumentException(e); } this.name = name; this.url = url; this.properties = properties == null ? null : (Properties) properties.clone(); //keep our own copy. }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code DeliverResponse[] sendDeliver(Common.Envelope transaction) throws TransactionException { if (shutdown) { throw new TransactionException(format("Orderer %s was shutdown.", name)); } OrdererClient localOrdererClient = ordererClient; logger.debug(format("Order.sendDeliver name: %s, url: %s", name, url)); if (localOrdererClient == null || !localOrdererClient.isChannelActive()) { localOrdererClient = new OrdererClient(this, new Endpoint(url, properties).getChannelBuilder()); ordererClient = localOrdererClient; } try { return localOrdererClient.sendDeliver(transaction); } catch (Throwable t) { ordererClient = null; throw t; } } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetInfo() throws Exception { if (testConfig.isRunningAgainstFabric10()) { HFCAInfo info = client.info(); assertNull(info.getVersion()); } if (!testConfig.isRunningAgainstFabric10()) { HFCAInfo info = client.info(); assertNotNull("client.info returned null.", info); String version = info.getVersion(); assertNotNull("client.info.getVersion returned null.", version); assertTrue(format("Version '%s' didn't match expected pattern", version), version.matches("^\\d+\\.\\d+\\.\\d+($|-.*)")); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetInfo() throws Exception { if (testConfig.isRunningAgainstFabric10()) { HFCAInfo info = client.info(); assertNull(info.getVersion()); } if (!testConfig.isRunningAgainstFabric10()) { HFCAInfo info = client.info(); assertTrue(info.getVersion().contains("1.1.0")); } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code boolean hasConnected() { return connected; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void setProperties(Properties properties) { this.properties = properties; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private static final Collection<MapArea> createAreasForSimpleMultipolygon(OsmRelation relation, TLongObjectMap<MapNode> nodeIdMap, OsmEntityProvider db) throws EntityNotFoundException { assert isSimpleMultipolygon(relation, db); OsmEntity tagSource = null; List<MapNode> outerNodes = null; List<List<MapNode>> holes = new ArrayList<List<MapNode>>(); for (OsmRelationMember member : membersAsList(relation)) { if (member.getType() == EntityType.Way) { OsmWay way = db.getWay(member.getId()); if ("inner".equals(member.getRole())) { List<MapNode> hole = new ArrayList<MapNode>(way.getNumberOfNodes()); for (long nodeId : nodesAsList(way).toArray()) { hole.add(nodeIdMap.get(nodeId)); } holes.add(hole); } else if ("outer".equals(member.getRole())) { tagSource = relation.getNumberOfTags() > 1 ? relation : way; outerNodes = new ArrayList<MapNode>(way.getNumberOfNodes()); for (long nodeId : nodesAsList(way).toArray()) { outerNodes.add(nodeIdMap.get(nodeId)); } } } } return singleton(new MapArea(tagSource.getId(), tagSource instanceof OsmRelation, OSMToMapDataConverter.tagsOfEntity(tagSource), outerNodes, holes)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static final Collection<MapArea> createAreasForSimpleMultipolygon(OsmRelation relation, TLongObjectMap<MapNode> nodeIdMap, OsmEntityProvider db) throws EntityNotFoundException { assert isSimpleMultipolygon(relation, db); OsmEntity tagSource = null; List<MapNode> outerNodes = null; List<List<MapNode>> holes = new ArrayList<List<MapNode>>(); for (OsmRelationMember member : membersAsList(relation)) { if (member.getType() == EntityType.Way) { OsmWay way = db.getWay(member.getId()); if ("inner".equals(member.getRole())) { List<MapNode> hole = new ArrayList<MapNode>(way.getNumberOfNodes()); for (long nodeId : nodesAsList(way).toArray()) { hole.add(nodeIdMap.get(nodeId)); } holes.add(hole); } else if ("outer".equals(member.getRole())) { tagSource = relation.getNumberOfTags() > 1 ? relation : way; outerNodes = new ArrayList<MapNode>(way.getNumberOfNodes()); for (long nodeId : nodesAsList(way).toArray()) { outerNodes.add(nodeIdMap.get(nodeId)); } } } } return singleton(new MapArea(tagSource, outerNodes, holes)); } #location 39 #vulnerability type NULL_DEREFERENCE
#fixed code public static final boolean isJOSMGenerated(File file) { try { BufferedReader reader = new BufferedReader(new FileReader(file)); for (int i=0; i<100; i++) { String line = reader.readLine(); if (line != null) { if (line.contains("generator='JOSM'")) { reader.close(); return true; } } } reader.close(); } catch (IOException e) { } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static final boolean isJOSMGenerated(File file) { try { BufferedReader reader = new BufferedReader(new FileReader(file)); for (int i=0; i<100; i++) { String line = reader.readLine(); if (line != null) { if (line.contains("generator='JOSM'")) { return true; } } } reader.close(); } catch (IOException e) { } return false; } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void finishSpan() { Span finished = new Span().setName("foo").setTimestamp(1000L); // set in start span finished.startTick = 500000L; // set in start span state.setCurrentLocalSpan(finished); PowerMockito.when(System.nanoTime()).thenReturn(1000000L); localTracer.finishSpan(); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(500L, finished.getDuration().longValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void finishSpan() { Span finished = new Span().setTimestamp(1000L); // set in start span finished.startTick = 500000L; // set in start span state.setCurrentLocalSpan(finished); PowerMockito.when(System.nanoTime()).thenReturn(1000000L); localTracer.finishSpan(); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(500L, finished.getDuration().longValue()); } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void reloadPage() { synchronized (this) { selectedSort = null; sortFieldLeft = null; super.reloadPage(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void reloadPage() { selectedSort = null; sortFieldLeft = null; super.reloadPage(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void getStartingWith(String queryString, Field field, String start, int limit, List<NamedItem> list) throws ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, SearchLibException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = urlDbClient.getNewSearchRequest(field + "Facet"); searchRequest.setQueryString(queryString); searchRequest.getFilterList().add(field + ":" + start + "*", Source.REQUEST); getFacetLimit(field, searchRequest, limit, list); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void getStartingWith(String queryString, Field field, String start, int limit, List<NamedItem> list) throws ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, SearchLibException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = client.getNewSearchRequest(field + "Facet"); searchRequest.setQueryString(queryString); searchRequest.getFilterList().add(field + ":" + start + "*", Source.REQUEST); getFacetLimit(field, searchRequest, limit, list); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String visitQuery_specification(VerdictSQLParser.Query_specificationContext ctx) { StringBuilder sql = new StringBuilder(2000); // this statement computes the mean value AnalyticSelectStatementRewriter meanRewriter = new AnalyticSelectStatementRewriter(vc, queryString); meanRewriter.setDepth(depth+1); meanRewriter.setIndentLevel(defaultIndent + 6); String mainSql = meanRewriter.visit(ctx); cumulativeReplacedTableSources.putAll(meanRewriter.getCumulativeSampleTables()); // this statement computes the standard deviation BootstrapSelectStatementRewriter varianceRewriter = new BootstrapSelectStatementRewriter(vc, queryString); varianceRewriter.setDepth(depth+1); varianceRewriter.setIndentLevel(defaultIndent + 6); String subSql = varianceRewriter.varianceComputationStatement(ctx); String leftAlias = genAlias(); String rightAlias = genAlias(); // we combine those two statements using join. List<Pair<String, String>> thisColumnName2Aliases = new ArrayList<Pair<String, String>>(); List<Pair<String, String>> leftColName2Aliases = meanRewriter.getColName2Aliases(); // List<Boolean> leftAggColIndicator = meanRewriter.getAggregateColumnIndicator(); List<Pair<String, String>> rightColName2Aliases = varianceRewriter.getColName2Aliases(); // List<Boolean> rightAggColIndicator = varianceRewriter.getAggregateColumnIndicator(); sql.append(String.format("%sSELECT", indentString)); int leftSelectElemIndex = 0; int totalSelectElemIndex = 0; for (Pair<String, String> colName2Alias : leftColName2Aliases) { leftSelectElemIndex++; if (leftSelectElemIndex == 1) sql.append(" "); else sql.append(", "); if (meanRewriter.isAggregateColumn(leftSelectElemIndex)) { // mean totalSelectElemIndex++; String alias = genAlias(); sql.append(String.format("%s.%s AS %s", leftAlias, colName2Alias.getRight(), alias)); thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), alias)); // error (standard deviation * 1.96 (for 95% confidence interval)) totalSelectElemIndex++; alias = genAlias(); String matchingAliasName = null; for (Pair<String, String> r : rightColName2Aliases) { if (colName2Alias.getLeft().equals(r.getLeft())) { matchingAliasName = r.getRight(); } } sql.append(String.format(", %s.%s AS %s", rightAlias, matchingAliasName, alias)); thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), alias)); meanColIndex2ErrColIndex.put(totalSelectElemIndex-1, totalSelectElemIndex); } else { totalSelectElemIndex++; sql.append(String.format("%s.%s AS %s", leftAlias, colName2Alias.getRight(), colName2Alias.getRight())); thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), colName2Alias.getRight())); } } colName2Aliases = thisColumnName2Aliases; sql.append(String.format("\n%sFROM (\n", indentString)); sql.append(mainSql); sql.append(String.format("\n%s ) AS %s", indentString, leftAlias)); sql.append(" LEFT JOIN (\n"); sql.append(subSql); sql.append(String.format("%s) AS %s", indentString, rightAlias)); sql.append(String.format(" ON %s.l_shipmode = %s.l_shipmode", leftAlias, rightAlias)); return sql.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String visitQuery_specification(VerdictSQLParser.Query_specificationContext ctx) { List<Pair<String, String>> subqueryColName2Aliases = null; BootstrapSelectStatementRewriter singleRewriter = null; StringBuilder unionedFrom = new StringBuilder(2000); int trialNum = vc.getConf().getInt("bootstrap_trial_num"); for (int i = 0; i < trialNum; i++) { singleRewriter = new BootstrapSelectStatementRewriter(vc, queryString); singleRewriter.setIndentLevel(2); singleRewriter.setDepth(1); String singleTrialQuery = singleRewriter.visitQuery_specificationForSingleTrial(ctx); if (i == 0) { subqueryColName2Aliases = singleRewriter.getColName2Aliases(); } if (i > 0) unionedFrom.append("\n UNION\n"); unionedFrom.append(singleTrialQuery); } StringBuilder sql = new StringBuilder(2000); sql.append("SELECT"); int selectElemIndex = 0; for (Pair<String, String> e : subqueryColName2Aliases) { selectElemIndex++; sql.append((selectElemIndex > 1)? ", " : " "); if (singleRewriter.isAggregateColumn(selectElemIndex)) { String alias = genAlias(); sql.append(String.format("AVG(%s) AS %s", e.getRight(), alias)); colName2Aliases.add(Pair.of(e.getLeft(), alias)); } else { if (e.getLeft().equals(e.getRight())) sql.append(e.getLeft()); else sql.append(String.format("%s AS %s", e.getLeft(), e.getRight())); colName2Aliases.add(Pair.of(e.getLeft(), e.getRight())); } } sql.append("\nFROM (\n"); sql.append(unionedFrom.toString()); sql.append("\n) AS t"); sql.append("\nGROUP BY"); for (int colIndex = 1; colIndex <= subqueryColName2Aliases.size(); colIndex++) { if (!singleRewriter.isAggregateColumn(colIndex)) { if (colIndex > 1) { sql.append(String.format(", %s", subqueryColName2Aliases.get(colIndex-1).getRight())); } else { sql.append(String.format(" %s", subqueryColName2Aliases.get(colIndex-1).getRight())); } } } return sql.toString(); } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet("'Can't connect to MySQL server on 'localhost'"); try { Process p; if (Platform.detect() == Platform.Windows) { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin.exe").toString(); successPatterns.add("mysqld.exe: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); } else { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); successPatterns.add("mysqld: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), //String.format("--socket=%s", sockFile(getExecutable().executable)), "shutdown"}); } retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(unsafeRuntimeConfig.getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseable(stdOut); closeCloseable(stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 59 #vulnerability type RESOURCE_LEAK
#fixed code public <T> MappingIterator<T> readValues(File src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues( _dataFormatReaders.findFormat(_inputStream(src)), false); } return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> MappingIterator<T> readValues(File src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues( _dataFormatReaders.findFormat(_inputStream(src)), false); } return _bindAndReadValues(considerFilter(_parserFactory.createParser(src))); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Override public String idFromValue(Object value) { return idFromClass(value.getClass()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String idFromValue(Object value) { Class<?> cls = _typeFactory.constructType(value.getClass()).getRawClass(); final String key = cls.getName(); String name; synchronized (_typeToId) { name = _typeToId.get(key); if (name == null) { // 24-Feb-2011, tatu: As per [JACKSON-498], may need to dynamically look up name // can either throw an exception, or use default name... if (_config.isAnnotationProcessingEnabled()) { BeanDescription beanDesc = _config.introspectClassAnnotations(cls); name = _config.getAnnotationIntrospector().findTypeName(beanDesc.getClassInfo()); } if (name == null) { // And if still not found, let's choose default? name = _defaultTypeId(cls); } _typeToId.put(key, name); } } return name; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void testAtomicInt() throws Exception { AtomicInteger value = MAPPER.readValue("13", AtomicInteger.class); assertEquals(13, value.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testAtomicInt() throws Exception { ObjectMapper mapper = new ObjectMapper(); AtomicInteger value = mapper.readValue("13", AtomicInteger.class); assertEquals(13, value.get()); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testVideosSitemap() throws UnknownFormatException, IOException { SiteMapParser parser = new SiteMapParser(); parser.enableExtension(Extension.VIDEO); String contentType = "text/xml"; byte[] content = SiteMapParserTest.getResourceAsBytes("src/test/resources/sitemaps/extension/sitemap-videos.xml"); URL url = new URL("http://www.example.com/sitemap-video.xml"); AbstractSiteMap asm = parser.parseSiteMap(contentType, content, url); assertEquals(false, asm.isIndex()); assertEquals(true, asm instanceof SiteMap); SiteMap sm = (SiteMap) asm; assertEquals(2, sm.getSiteMapUrls().size()); Iterator<SiteMapURL> siter = sm.getSiteMapUrls().iterator(); // first <loc> element: nearly all video attributes VideoAttributes expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123.jpg"), "Grilling steaks for summer", "Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123.flv"), new URL("http://www.example.com/videoplayer.swf?video=123")); expectedVideoAttributes.setDuration(600); ZonedDateTime dt = ZonedDateTime.parse("2009-11-05T19:20:30+08:00"); expectedVideoAttributes.setExpirationDate(dt); dt = ZonedDateTime.parse("2007-11-05T19:20:30+08:00"); expectedVideoAttributes.setPublicationDate(dt); expectedVideoAttributes.setRating(4.2f); expectedVideoAttributes.setViewCount(12345); expectedVideoAttributes.setFamilyFriendly(true); expectedVideoAttributes.setTags(new String[] { "sample_tag1", "sample_tag2" }); expectedVideoAttributes.setAllowedCountries(new String[] { "IE", "GB", "US", "CA" }); expectedVideoAttributes.setGalleryLoc(new URL("http://cooking.example.com")); expectedVideoAttributes.setGalleryTitle("Cooking Videos"); expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", 1.99f, VideoAttributes.VideoPriceType.own) }); expectedVideoAttributes.setRequiresSubscription(true); expectedVideoAttributes.setUploader("GrillyMcGrillerson"); expectedVideoAttributes.setUploaderInfo(new URL("http://www.example.com/users/grillymcgrillerson")); expectedVideoAttributes.setLive(false); VideoAttributes attr = (VideoAttributes) siter.next().getAttributesForExtension(Extension.VIDEO)[0]; assertNotNull(attr); assertEquals(expectedVideoAttributes, attr); // locale-specific number format in <video:price>, test #220 expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123-2.jpg"), "Grilling steaks for summer, episode 2", "Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123-2.flv"), null); expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", null, VideoAttributes.VideoPriceType.own) }); attr = (VideoAttributes) siter.next().getAttributesForExtension(Extension.VIDEO)[0]; assertNotNull(attr); assertEquals(expectedVideoAttributes, attr); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testVideosSitemap() throws UnknownFormatException, IOException { SiteMapParser parser = new SiteMapParser(); parser.enableExtension(Extension.VIDEO); String contentType = "text/xml"; byte[] content = SiteMapParserTest.getResourceAsBytes("src/test/resources/sitemaps/extension/sitemap-videos.xml"); URL url = new URL("http://www.example.com/sitemap-video.xml"); AbstractSiteMap asm = parser.parseSiteMap(contentType, content, url); assertEquals(false, asm.isIndex()); assertEquals(true, asm instanceof SiteMap); SiteMap sm = (SiteMap) asm; assertEquals(1, sm.getSiteMapUrls().size()); VideoAttributes expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123.jpg"), "Grilling steaks for summer", "Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123.flv"), new URL("http://www.example.com/videoplayer.swf?video=123")); expectedVideoAttributes.setDuration(600); ZonedDateTime dt = ZonedDateTime.parse("2009-11-05T19:20:30+08:00"); expectedVideoAttributes.setExpirationDate(dt); dt = ZonedDateTime.parse("2007-11-05T19:20:30+08:00"); expectedVideoAttributes.setPublicationDate(dt); expectedVideoAttributes.setRating(4.2f); expectedVideoAttributes.setViewCount(12345); expectedVideoAttributes.setFamilyFriendly(true); expectedVideoAttributes.setTags(new String[] { "sample_tag1", "sample_tag2" }); expectedVideoAttributes.setAllowedCountries(new String[] { "IE", "GB", "US", "CA" }); expectedVideoAttributes.setGalleryLoc(new URL("http://cooking.example.com")); expectedVideoAttributes.setGalleryTitle("Cooking Videos"); expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", 1.99f, VideoAttributes.VideoPriceType.own) }); expectedVideoAttributes.setRequiresSubscription(true); expectedVideoAttributes.setUploader("GrillyMcGrillerson"); expectedVideoAttributes.setUploaderInfo(new URL("http://www.example.com/users/grillymcgrillerson")); expectedVideoAttributes.setLive(false); for (SiteMapURL su : sm.getSiteMapUrls()) { assertNotNull(su.getAttributesForExtension(Extension.VIDEO)); VideoAttributes attr = (VideoAttributes) su.getAttributesForExtension(Extension.VIDEO)[0]; assertEquals(expectedVideoAttributes, attr); } } #location 37 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void moderator_should_approve_question_information() throws Exception { Information approvedInfo = new QuestionInformation("edited title", "edited desc", new LoggedUser(otherUser, null), new ArrayList<Tag>(), "comment"); moderator.approve(myQuestion, approvedInfo); assertEquals(approvedInfo, myQuestion.getInformation()); assertTrue(myQuestion.getInformation().isModerated()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void moderator_should_approve_question_information() throws Exception { Question question = question("question title", "question description", author); Information approvedInfo = new QuestionInformation("edited title", "edited desc", new LoggedUser(otherUser, null), new ArrayList<Tag>(), "comment"); moderator.approve(question, approvedInfo); assertEquals(approvedInfo, question.getInformation()); assertTrue(question.getInformation().isModerated()); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public SyndFeedInfo remove(final URL url) { SyndFeedInfo info = null; final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim(); FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(fileName); ois = new ObjectInputStream(fis); info = (SyndFeedInfo) ois.readObject(); final File file = new File(fileName); if (file.exists()) { file.delete(); } } catch (final FileNotFoundException fnfe) { // That's OK, we'l return null } catch (final ClassNotFoundException cnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", cnfe); } catch (final IOException fnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", fnfe); } finally { if (fis != null) { try { fis.close(); } catch (final IOException e) { } } if (ois != null) { try { ois.close(); } catch (final IOException e) { } } } return info; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public SyndFeedInfo remove(final URL url) { SyndFeedInfo info = null; final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim(); FileInputStream fis; try { fis = new FileInputStream(fileName); final ObjectInputStream ois = new ObjectInputStream(fis); info = (SyndFeedInfo) ois.readObject(); fis.close(); final File file = new File(fileName); if (file.exists()) { file.delete(); } } catch (final FileNotFoundException fnfe) { // That's OK, we'l return null } catch (final ClassNotFoundException cnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", cnfe); } catch (final IOException fnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", fnfe); } return info; } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } final XmlReader xmlReader = new XmlReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here becuase UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection } else { assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } xmlReader.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } final XmlReader xmlReader = new XmlReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here becuase UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection } else { assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code protected void testRawBomValid(final String encoding) throws Exception { final InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding); final XmlReader xmlReader = new XmlReader(is, false); if (!encoding.equals("UTF-16")) { assertEquals(xmlReader.getEncoding(), encoding); } else { assertEquals(xmlReader.getEncoding().substring(0, encoding.length()), encoding); } xmlReader.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testRawBomValid(final String encoding) throws Exception { final InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding); final XmlReader xmlReader = new XmlReader(is, false); if (!encoding.equals("UTF-16")) { assertEquals(xmlReader.getEncoding(), encoding); } else { assertEquals(xmlReader.getEncoding().substring(0, encoding.length()), encoding); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code static String load(File in, String charsetName) throws IOException { InputStream inStream = new FileInputStream(in); String data = readInputStream(inStream, charsetName); inStream.close(); return data; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static String load(File in, String charsetName) throws IOException { char[] buffer = new char[0x20000]; // ~ 130K StringBuilder data = new StringBuilder(0x20000); InputStream inStream = new FileInputStream(in); Reader inReader = new InputStreamReader(inStream, charsetName); int read; do { read = inReader.read(buffer, 0, buffer.length); if (read > 0) { data.append(buffer, 0, read); } } while (read >= 0); return data.toString(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code protected void addChildren(int index, Node... children) { Validate.notNull(children); if (children.length == 0) { return; } final List<Node> nodes = ensureChildNodes(); // fast path - if used as a wrap (index=0, children = child[0].parent.children - do inplace final Node firstParent = children[0].parent(); if (firstParent != null && firstParent.childNodeSize() == children.length) { boolean sameList = true; final List<Node> firstParentNodes = firstParent.childNodes(); // identity check contents to see if same int i = children.length; while (i-- > 0) { if (children[i] != firstParentNodes.get(i)) { sameList = false; break; } } firstParent.empty(); nodes.addAll(index, Arrays.asList(children)); i = children.length; while (i-- > 0) { children[i].parentNode = this; } reindexChildren(index); return; } Validate.noNullElements(children); for (Node child : children) { reparentChild(child); } nodes.addAll(index, Arrays.asList(children)); reindexChildren(index); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void addChildren(int index, Node... children) { Validate.noNullElements(children); final List<Node> nodes = ensureChildNodes(); for (Node child : children) { reparentChild(child); } nodes.addAll(index, Arrays.asList(children)); reindexChildren(index); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private static String ihVal(String key, Document doc) { final Element first = doc.select("th:contains(" + key + ") + td").first(); return first != null ? first.text() : null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static String ihVal(String key, Document doc) { return doc.select("th:contains(" + key + ") + td").first().text(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public void transactionObject(final String trytes) { if (StringUtils.isEmpty(trytes)) { log.warn("Warning: empty trytes in input for transactionObject"); return; } // validity check for (int i = 2279; i < 2295; i++) { if (trytes.charAt(i) != '9') { log.warn("Trytes {} does not seem a valid tryte", trytes); return; } } int[] transactionTrits = Converter.trits(trytes); int[] hash = new int[243]; ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURLP81); // generate the correct transaction hash curl.reset(); curl.absorb(transactionTrits, 0, transactionTrits.length); curl.squeeze(hash, 0, hash.length); this.setHash(Converter.trytes(hash)); this.setSignatureFragments(trytes.substring(0, 2187)); this.setAddress(trytes.substring(2187, 2268)); this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837))); this.setObsoleteTag(trytes.substring(2295, 2322)); this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993))); this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020))); this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047))); this.setBundle(trytes.substring(2349, 2430)); this.setTrunkTransaction(trytes.substring(2430, 2511)); this.setBranchTransaction(trytes.substring(2511, 2592)); this.setTag(trytes.substring(2592, 2619)); this.setAttachmentTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7857, 7884)) / 1000); this.setAttachmentTimestampLowerBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7884, 7911))); this.setAttachmentTimestampUpperBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7911, 7938))); this.setNonce(trytes.substring(2646, 2673)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void transactionObject(final String trytes) { if (StringUtils.isEmpty(trytes)) { log.warn("Warning: empty trytes in input for transactionObject"); return; } // validity check for (int i = 2279; i < 2295; i++) { if (trytes.charAt(i) != '9') { log.warn("Trytes {} does not seem a valid tryte", trytes); return; } } int[] transactionTrits = Converter.trits(trytes); int[] hash = new int[243]; ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURL); // generate the correct transaction hash curl.reset(); curl.absorb(transactionTrits, 0, transactionTrits.length); curl.squeeze(hash, 0, hash.length); this.setHash(Converter.trytes(hash)); this.setSignatureFragments(trytes.substring(0, 2187)); this.setAddress(trytes.substring(2187, 2268)); this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837))); this.setTag(trytes.substring(2295, 2322)); this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993))); this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020))); this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047))); this.setBundle(trytes.substring(2349, 2430)); this.setTrunkTransaction(trytes.substring(2430, 2511)); this.setBranchTransaction(trytes.substring(2511, 2592)); this.setNonce(trytes.substring(2592, 2673)); } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code @SuppressWarnings({"unchecked", "rawtypes"}) public void onReceive(ServiceContext serviceContext) throws Throwable { FlowMessage fm = serviceContext.getFlowMessage(); if (serviceContext.isSync() && !syncActors.containsKey(serviceContext.getId())) { syncActors.putIfAbsent(serviceContext.getId(), getSender()); } // TODO 没有必要设置默认值,下面执行异常就会抛出异常 Object result = null;// DefaultMessage.getMessage();// set default try { this.service = ServiceFactory.getService(serviceName); result = ((Service) service).process(fm.getMessage(), serviceContext); } catch (Throwable e) { Web web = serviceContext.getWeb(); if (web != null) { web.complete(); } throw new FlowerException("fail to invoke service " + serviceName + " : " + service + ", param : " + fm.getMessage(), e); } logger.info("同步处理 : {}, hasChild : {}", serviceContext.isSync(), hasChildActor()); if (serviceContext.isSync() && !hasChildActor()) { logger.info("返回响应 {}", result); ActorRef actor = syncActors.get(serviceContext.getId()); if(actor !=null) { actor.tell(result, getSelf()); syncActors.remove(serviceContext.getId()); } return; } Web web = serviceContext.getWeb(); if (service instanceof Complete) { // FlowContext.removeServiceContext(fm.getTransactionId()); } if (web != null) { if (service instanceof Flush) { web.flush(); } if (service instanceof HttpComplete || service instanceof Complete) { web.complete(); } } if (result == null)// for joint service return; if (hasChildActor()) { for (RefType refType : nextServiceActors) { ServiceContext context = serviceContext.newInstance(); context.getFlowMessage().setMessage(result); // if (refType.isJoint()) { // FlowMessage flowMessage1 = CloneUtil.clone(fm); // flowMessage1.setMessage(result); // context.setFlowMessage(flowMessage1); // } // condition fork for one-service to multi-service if (refType.getMessageType().isInstance(result)) { if (!(result instanceof Condition) || !(((Condition) result).getCondition() instanceof String) || stringInStrings(refType.getServiceName(), ((Condition) result).getCondition().toString())) { refType.getActorRef().tell(context, getSelf()); } } } } else { } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings({"unchecked", "rawtypes"}) public void onReceive(ServiceContext serviceContext) throws Throwable { FlowMessage fm = serviceContext.getFlowMessage(); if (serviceContext.isSync() && !syncActors.containsKey(serviceContext.getId())) { syncActors.putIfAbsent(serviceContext.getId(), getSender()); } // TODO 没有必要设置默认值,下面执行异常就会抛出异常 Object result = null;// DefaultMessage.getMessage();// set default try { this.service = ServiceFactory.getService(serviceName); result = ((Service) service).process(fm.getMessage(), serviceContext); } catch (Throwable e) { Web web = serviceContext.getWeb(); if (web != null) { web.complete(); } throw new FlowerException("fail to invoke service " + serviceName + " : " + service + ", param : " + fm.getMessage(), e); } if (serviceContext.isSync() && !hasChildActor()) { syncActors.get(serviceContext.getId()).tell(result, getSelf()); syncActors.remove(serviceContext.getId()); return; } Web web = serviceContext.getWeb(); if (service instanceof Complete) { // FlowContext.removeServiceContext(fm.getTransactionId()); } if (web != null) { if (service instanceof Flush) { web.flush(); } if (service instanceof HttpComplete || service instanceof Complete) { web.complete(); } } if (result == null)// for joint service return; if (hasChildActor()) { for (RefType refType : nextServiceActors) { ServiceContext context = serviceContext.newInstance(); context.getFlowMessage().setMessage(result); // if (refType.isJoint()) { // FlowMessage flowMessage1 = CloneUtil.clone(fm); // flowMessage1.setMessage(result); // context.setFlowMessage(flowMessage1); // } // condition fork for one-service to multi-service if (refType.getMessageType().isInstance(result)) { if (!(result instanceof Condition) || !(((Condition) result).getCondition() instanceof String) || stringInStrings(refType.getServiceName(), ((Condition) result).getCondition().toString())) { refType.getActorRef().tell(context, getSelf()); } } } } else { } } #location 45 #vulnerability type NULL_DEREFERENCE
#fixed code FunctionTypeBuilder(String fnName, AbstractCompiler compiler, Node errorRoot, String sourceName, Scope scope) { Preconditions.checkNotNull(errorRoot); this.fnName = fnName == null ? "" : fnName; this.codingConvention = compiler.getCodingConvention(); this.typeRegistry = compiler.getTypeRegistry(); this.errorRoot = errorRoot; this.sourceName = sourceName; this.compiler = compiler; this.scope = scope; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code FunctionTypeBuilder inferThisType(JSDocInfo info, @Nullable Node owner) { ObjectType maybeThisType = null; if (info != null && info.hasThisType()) { maybeThisType = ObjectType.cast( info.getThisType().evaluate(scope, typeRegistry)); } if (maybeThisType != null) { thisType = maybeThisType; thisType.setValidator(new ThisTypeValidator()); } else if (owner != null && (info == null || !info.hasType())) { // If the function is of the form: // x.prototype.y = function() {} // then we can assume "x" is the @this type. On the other hand, // if it's of the form: // /** @type {Function} */ x.prototype.y; // then we should not give it a @this type. String ownerTypeName = owner.getQualifiedName(); ObjectType ownerType = ObjectType.cast( typeRegistry.getForgivingType( scope, ownerTypeName, sourceName, owner.getLineno(), owner.getCharno())); if (ownerType != null) { thisType = ownerType; } } return this; } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code private void createPropertyScopeFor(Symbol s) { // In order to build a property scope for s, we will need to build // a property scope for all its implicit prototypes first. This means // that sometimes we will already have built its property scope // for a previous symbol. if (s.propertyScope != null) { return; } SymbolScope parentPropertyScope = null; ObjectType type = s.getType() == null ? null : s.getType().toObjectType(); if (type == null) { return; } ObjectType proto = type.getParentScope(); if (proto != null && proto != type && proto.getConstructor() != null) { Symbol parentSymbol = getSymbolForInstancesOf(proto.getConstructor()); if (parentSymbol != null) { createPropertyScopeFor(parentSymbol); parentPropertyScope = parentSymbol.getPropertyScope(); } } ObjectType instanceType = type; Iterable<String> propNames = type.getOwnPropertyNames(); if (instanceType.isFunctionPrototypeType()) { // Merge the properties of "Foo.prototype" and "new Foo()" together. instanceType = instanceType.getOwnerFunction().getInstanceType(); Set<String> set = Sets.newHashSet(propNames); Iterables.addAll(set, instanceType.getOwnPropertyNames()); propNames = set; } s.setPropertyScope(new SymbolScope(null, parentPropertyScope, type, s)); for (String propName : propNames) { StaticSlot<JSType> newProp = instanceType.getSlot(propName); if (newProp.getDeclaration() == null) { // Skip properties without declarations. We won't know how to index // them, because we index things by node. continue; } // We have symbol tables that do not do type analysis. They just try // to build a complete index of all objects in the program. So we might // already have symbols for things like "Foo.bar". If this happens, // throw out the old symbol and use the type-based symbol. Symbol oldProp = getScope(s).getSlot(s.getName() + "." + propName); if (oldProp != null) { removeSymbol(oldProp); } Symbol newSym = copySymbolTo(newProp, s.propertyScope); if (oldProp != null) { if (newSym.getJSDocInfo() == null) { newSym.setJSDocInfo(oldProp.getJSDocInfo()); } newSym.setPropertyScope(oldProp.propertyScope); for (Reference ref : oldProp.references.values()) { newSym.defineReferenceAt(ref.getNode()); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void createPropertyScopeFor(Symbol s) { // In order to build a property scope for s, we will need to build // a property scope for all its implicit prototypes first. This means // that sometimes we will already have built its property scope // for a previous symbol. if (s.propertyScope != null) { return; } SymbolScope parentPropertyScope = null; ObjectType type = s.getType().toObjectType(); ObjectType proto = type.getParentScope(); if (proto != null && proto != type && proto.getConstructor() != null) { Symbol parentSymbol = getSymbolForInstancesOf(proto.getConstructor()); if (parentSymbol != null) { createPropertyScopeFor(parentSymbol); parentPropertyScope = parentSymbol.getPropertyScope(); } } ObjectType instanceType = type; Iterable<String> propNames = type.getOwnPropertyNames(); if (instanceType.isFunctionPrototypeType()) { // Merge the properties of "Foo.prototype" and "new Foo()" together. instanceType = instanceType.getOwnerFunction().getInstanceType(); Set<String> set = Sets.newHashSet(propNames); Iterables.addAll(set, instanceType.getOwnPropertyNames()); propNames = set; } s.propertyScope = new SymbolScope(null, parentPropertyScope, type); for (String propName : propNames) { StaticSlot<JSType> newProp = instanceType.getSlot(propName); if (newProp.getDeclaration() == null) { // Skip properties without declarations. We won't know how to index // them, because we index things by node. continue; } // We have symbol tables that do not do type analysis. They just try // to build a complete index of all objects in the program. So we might // already have symbols for things like "Foo.bar". If this happens, // throw out the old symbol and use the type-based symbol. Symbol oldProp = getScope(s).getSlot(s.getName() + "." + propName); if (oldProp != null) { removeSymbol(oldProp); } Symbol newSym = copySymbolTo(newProp, s.propertyScope); if (oldProp != null) { if (newSym.getJSDocInfo() == null) { newSym.setJSDocInfo(oldProp.getJSDocInfo()); } newSym.propertyScope = oldProp.propertyScope; for (Reference ref : oldProp.references.values()) { newSym.defineReferenceAt(ref.getNode()); } } } } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code private FlowScope traverse(Node n, FlowScope scope) { switch (n.getType()) { case Token.ASSIGN: scope = traverseAssign(n, scope); break; case Token.NAME: scope = traverseName(n, scope); break; case Token.GETPROP: scope = traverseGetProp(n, scope); break; case Token.AND: scope = traverseAnd(n, scope).getJoinedFlowScope() .createChildFlowScope(); break; case Token.OR: scope = traverseOr(n, scope).getJoinedFlowScope() .createChildFlowScope(); break; case Token.HOOK: scope = traverseHook(n, scope); break; case Token.OBJECTLIT: scope = traverseObjectLiteral(n, scope); break; case Token.CALL: scope = traverseCall(n, scope); break; case Token.NEW: scope = traverseNew(n, scope); break; case Token.ASSIGN_ADD: case Token.ADD: scope = traverseAdd(n, scope); break; case Token.POS: case Token.NEG: scope = traverse(n.getFirstChild(), scope); // Find types. n.setJSType(getNativeType(NUMBER_TYPE)); break; case Token.ARRAYLIT: scope = traverseArrayLiteral(n, scope); break; case Token.THIS: n.setJSType(scope.getTypeOfThis()); break; case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.LSH: case Token.RSH: case Token.ASSIGN_URSH: case Token.URSH: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITAND: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITOR: case Token.ASSIGN_MUL: case Token.ASSIGN_SUB: case Token.DIV: case Token.MOD: case Token.BITAND: case Token.BITXOR: case Token.BITOR: case Token.MUL: case Token.SUB: case Token.DEC: case Token.INC: case Token.BITNOT: scope = traverseChildren(n, scope); n.setJSType(getNativeType(NUMBER_TYPE)); break; case Token.PARAM_LIST: scope = traverse(n.getFirstChild(), scope); n.setJSType(getJSType(n.getFirstChild())); break; case Token.COMMA: scope = traverseChildren(n, scope); n.setJSType(getJSType(n.getLastChild())); break; case Token.TYPEOF: scope = traverseChildren(n, scope); n.setJSType(getNativeType(STRING_TYPE)); break; case Token.DELPROP: case Token.LT: case Token.LE: case Token.GT: case Token.GE: case Token.NOT: case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: case Token.INSTANCEOF: case Token.IN: scope = traverseChildren(n, scope); n.setJSType(getNativeType(BOOLEAN_TYPE)); break; case Token.GETELEM: scope = traverseGetElem(n, scope); break; case Token.EXPR_RESULT: scope = traverseChildren(n, scope); if (n.getFirstChild().isGetProp()) { ensurePropertyDeclared(n.getFirstChild()); } break; case Token.SWITCH: scope = traverse(n.getFirstChild(), scope); break; case Token.RETURN: scope = traverseReturn(n, scope); break; case Token.VAR: case Token.THROW: scope = traverseChildren(n, scope); break; case Token.CATCH: scope = traverseCatch(n, scope); break; case Token.CAST: scope = traverseChildren(n, scope); JSDocInfo info = n.getJSDocInfo(); if (info != null && info.hasType()) { n.setJSType(info.getType().evaluate(syntacticScope, registry)); } break; } return scope; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private FlowScope traverse(Node n, FlowScope scope) { switch (n.getType()) { case Token.ASSIGN: scope = traverseAssign(n, scope); break; case Token.NAME: scope = traverseName(n, scope); break; case Token.GETPROP: scope = traverseGetProp(n, scope); break; case Token.AND: scope = traverseAnd(n, scope).getJoinedFlowScope() .createChildFlowScope(); break; case Token.OR: scope = traverseOr(n, scope).getJoinedFlowScope() .createChildFlowScope(); break; case Token.HOOK: scope = traverseHook(n, scope); break; case Token.OBJECTLIT: scope = traverseObjectLiteral(n, scope); break; case Token.CALL: scope = traverseCall(n, scope); break; case Token.NEW: scope = traverseNew(n, scope); break; case Token.ASSIGN_ADD: case Token.ADD: scope = traverseAdd(n, scope); break; case Token.POS: case Token.NEG: scope = traverse(n.getFirstChild(), scope); // Find types. n.setJSType(getNativeType(NUMBER_TYPE)); break; case Token.ARRAYLIT: scope = traverseArrayLiteral(n, scope); break; case Token.THIS: n.setJSType(scope.getTypeOfThis()); break; case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.LSH: case Token.RSH: case Token.ASSIGN_URSH: case Token.URSH: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITAND: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITOR: case Token.ASSIGN_MUL: case Token.ASSIGN_SUB: case Token.DIV: case Token.MOD: case Token.BITAND: case Token.BITXOR: case Token.BITOR: case Token.MUL: case Token.SUB: case Token.DEC: case Token.INC: case Token.BITNOT: scope = traverseChildren(n, scope); n.setJSType(getNativeType(NUMBER_TYPE)); break; case Token.PARAM_LIST: scope = traverse(n.getFirstChild(), scope); n.setJSType(getJSType(n.getFirstChild())); break; case Token.COMMA: scope = traverseChildren(n, scope); n.setJSType(getJSType(n.getLastChild())); break; case Token.TYPEOF: scope = traverseChildren(n, scope); n.setJSType(getNativeType(STRING_TYPE)); break; case Token.DELPROP: case Token.LT: case Token.LE: case Token.GT: case Token.GE: case Token.NOT: case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: case Token.INSTANCEOF: case Token.IN: scope = traverseChildren(n, scope); n.setJSType(getNativeType(BOOLEAN_TYPE)); break; case Token.GETELEM: scope = traverseGetElem(n, scope); break; case Token.EXPR_RESULT: scope = traverseChildren(n, scope); if (n.getFirstChild().isGetProp()) { ensurePropertyDeclared(n.getFirstChild()); } break; case Token.SWITCH: scope = traverse(n.getFirstChild(), scope); break; case Token.RETURN: scope = traverseReturn(n, scope); break; case Token.VAR: case Token.THROW: scope = traverseChildren(n, scope); break; case Token.CATCH: scope = traverseCatch(n, scope); break; case Token.CAST: scope = traverseChildren(n, scope); break; } // TODO(johnlenz): remove this after the CAST node change has shaken out. if (!n.isFunction()) { JSDocInfo info = n.getJSDocInfo(); if (info != null && info.hasType()) { JSType castType = info.getType().evaluate(syntacticScope, registry); // A stubbed type declaration on a qualified name should take // effect for all subsequent accesses of that name, // so treat it the same as an assign to that name. if (n.isQualifiedName() && n.getParent().isExprResult()) { updateScopeForTypeChange(scope, n, n.getJSType(), castType); } n.setJSType(castType); } } return scope; } #location 155 #vulnerability type NULL_DEREFERENCE
#fixed code private Node inlineReturnValue(Node callNode, Node fnNode) { Node block = fnNode.getLastChild(); Node callParentNode = callNode.getParent(); // NOTE: As the normalize pass guarantees globals aren't being // shadowed and an expression can't introduce new names, there is // no need to check for conflicts. // Create an argName -> expression map, checking for side effects. Map<String, Node> argMap = FunctionArgumentInjector.getFunctionCallParameterMap( fnNode, callNode, this.safeNameIdSupplier); Node newExpression; if (!block.hasChildren()) { Node srcLocation = block; newExpression = NodeUtil.newUndefinedNode(srcLocation); } else { Node returnNode = block.getFirstChild(); Preconditions.checkArgument(returnNode.getType() == Token.RETURN); // Clone the return node first. Node safeReturnNode = returnNode.cloneTree(); Node inlineResult = FunctionArgumentInjector.inject( null, safeReturnNode, null, argMap); Preconditions.checkArgument(safeReturnNode == inlineResult); newExpression = safeReturnNode.removeFirstChild(); } callParentNode.replaceChild(callNode, newExpression); return newExpression; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node inlineReturnValue(Node callNode, Node fnNode) { Node block = fnNode.getLastChild(); Node callParentNode = callNode.getParent(); // NOTE: As the normalize pass guarantees globals aren't being // shadowed and an expression can't introduce new names, there is // no need to check for conflicts. // Create an argName -> expression map, checking for side effects. Map<String, Node> argMap = FunctionArgumentInjector.getFunctionCallParameterMap( fnNode, callNode, this.safeNameIdSupplier); Node newExpression; if (!block.hasChildren()) { Node srcLocation = block; newExpression = NodeUtil.newUndefinedNode(srcLocation); } else { Node returnNode = block.getFirstChild(); Preconditions.checkArgument(returnNode.getType() == Token.RETURN); // Clone the return node first. Node safeReturnNode = returnNode.cloneTree(); Node inlineResult = FunctionArgumentInjector.inject( safeReturnNode, null, argMap); Preconditions.checkArgument(safeReturnNode == inlineResult); newExpression = safeReturnNode.removeFirstChild(); } callParentNode.replaceChild(callNode, newExpression); return newExpression; } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code public void setSqlSource(MappedStatement ms) { MapperTemplate mapperTemplate = getMapperTemplate(ms.getId()); try { if (mapperTemplate != null) { mapperTemplate.setSqlSource(ms); } } catch (Exception e) { throw new RuntimeException("调用方法异常:" + e.getMessage()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void setSqlSource(MappedStatement ms) { MapperTemplate mapperTemplate = getMapperTemplate(ms.getId()); try { mapperTemplate.setSqlSource(ms); } catch (Exception e) { throw new RuntimeException("调用方法异常:" + e.getMessage()); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean isIterableMapping() { return getSingleSourceParameter().getType().isIterableType() && getResultType().isIterableType(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isIterableMapping() { return getSingleSourceType().isIterableType() && resultType.isIterableType(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code private List<Method> retrieveMethods(TypeElement element, boolean implementationRequired) { List<Method> methods = new ArrayList<Method>(); MapperPrism mapperPrism = implementationRequired ? MapperPrism.getInstanceOn( element ) : null; for ( ExecutableElement executable : methodsIn( element.getEnclosedElements() ) ) { Method method = getMethod( element, executable, implementationRequired ); if ( method != null ) { methods.add( method ); } } //Add all methods of used mappers in order to reference them in the aggregated model if ( implementationRequired ) { for ( TypeMirror usedMapper : mapperPrism.uses() ) { methods.addAll( retrieveMethods( (TypeElement) ( (DeclaredType) usedMapper ).asElement(), false ) ); } } return methods; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<Method> retrieveMethods(TypeElement element, boolean implementationRequired) { List<Method> methods = new ArrayList<Method>(); MapperPrism mapperPrism = implementationRequired ? MapperPrism.getInstanceOn( element ) : null; //TODO Extract to separate method for ( ExecutableElement method : methodsIn( element.getEnclosedElements() ) ) { Parameter parameter = executables.retrieveParameter( method ); Type returnType = executables.retrieveReturnType( method ); boolean mappingErroneous = false; if ( implementationRequired ) { if ( parameter.getType().isIterableType() && !returnType.isIterableType() ) { printMessage( ReportingPolicy.ERROR, "Can't generate mapping method from iterable type to non-iterable type.", method ); mappingErroneous = true; } if ( !parameter.getType().isIterableType() && returnType.isIterableType() ) { printMessage( ReportingPolicy.ERROR, "Can't generate mapping method from non-iterable type to iterable type.", method ); mappingErroneous = true; } if ( parameter.getType().isPrimitive() ) { printMessage( ReportingPolicy.ERROR, "Can't generate mapping method with primitive parameter type.", method ); mappingErroneous = true; } if ( returnType.isPrimitive() ) { printMessage( ReportingPolicy.ERROR, "Can't generate mapping method with primitive return type.", method ); mappingErroneous = true; } if ( mappingErroneous ) { continue; } } //add method with property mappings if an implementation needs to be generated if ( implementationRequired ) { methods.add( Method.forMethodRequiringImplementation( method, parameter.getName(), parameter.getType(), returnType, getMappings( method ) ) ); } //otherwise add reference to existing mapper method else { methods.add( Method.forReferencedMethod( typeUtil.getType( typeUtils.getDeclaredType( element ) ), method, parameter.getName(), parameter.getType(), returnType ) ); } } //Add all methods of used mappers in order to reference them in the aggregated model if ( implementationRequired ) { for ( TypeMirror usedMapper : mapperPrism.uses() ) { methods.addAll( retrieveMethods( (TypeElement) ( (DeclaredType) usedMapper ).asElement(), false ) ); } } return methods; } #location 57 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean matches() { // check & collect generic types. List<? extends VariableElement> candidateParameters = candidateMethod.getExecutable().getParameters(); if ( candidateParameters.size() != 1 ) { typesMatch = false; } else { TypeMatcher parameterMatcher = new TypeMatcher(); typesMatch = parameterMatcher.visit( candidateParameters.iterator().next().asType(), parameter.getTypeMirror() ); } // check return type if ( typesMatch ) { TypeMirror candidateReturnType = candidateMethod.getExecutable().getReturnType(); TypeMatcher returnTypeMatcher = new TypeMatcher(); typesMatch = returnTypeMatcher.visit( candidateReturnType, returnType.getTypeMirror() ); } // check if all type parameters are indeed mapped if ( candidateMethod.getExecutable().getTypeParameters().size() != this.genericTypesMap.size() ) { typesMatch = false; } else { // check if all entries are in the bounds for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) { if (!isWithinBounds( entry.getValue(), getTypeParamFromCandidate( entry.getKey() ) ) ) { // checks if the found Type is in bounds of the TypeParameters bounds. typesMatch = false; } } } return typesMatch; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean matches() { // check & collect generic types. List<? extends VariableElement> candidateParameters = candidateMethod.getExecutable().getParameters(); if ( candidateParameters.size() == parameters.length ) { for ( int i = 0; i < parameters.length; i++ ) { TypeMatcher parameterMatcher = new TypeMatcher(); typesMatch = parameterMatcher.visit( candidateParameters.get( i ).asType(), parameters[i].getTypeMirror() ); if ( !typesMatch ) { break; } } } else { typesMatch = false; } // check return type if ( typesMatch ) { TypeMirror candidateReturnType = candidateMethod.getExecutable().getReturnType(); TypeMatcher returnTypeMatcher = new TypeMatcher(); typesMatch = returnTypeMatcher.visit( candidateReturnType, returnType.getTypeMirror() ); } // check if all type parameters are indeed mapped if ( candidateMethod.getExecutable().getTypeParameters().size() != this.genericTypesMap.size() ) { typesMatch = false; } else { // check if all entries are in the bounds for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) { if (!isWithinBounds( entry.getValue(), getTypeParamFromCandite( entry.getKey() ) ) ) { // checks if the found Type is in bounds of the TypeParameters bounds. typesMatch = false; } } } return typesMatch; } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) { int valueType = array.getType(index); switch (valueType) { case V8Value.INTEGER: return array.getInteger(index); case V8Value.DOUBLE: return array.getDouble(index); case V8Value.BOOLEAN: return array.getBoolean(index); case V8Value.STRING: return array.getString(index); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_ARRAY_BUFFER: V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index); try { return new ArrayBuffer(buffer.getBackingStore()); } finally { buffer.release(); } case V8Value.V8_TYPED_ARRAY: V8Array typedArray = array.getArray(index); try { return toTypedArray(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array arrayValue = array.getArray(index); try { return toList(arrayValue, cache); } finally { if (arrayValue instanceof V8Array) { arrayValue.release(); } } case V8Value.V8_OBJECT: V8Object objectValue = array.getObject(index); try { return toMap(objectValue, cache); } finally { if (objectValue instanceof V8Object) { objectValue.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for index: " + index); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) { int valueType = array.getType(index); switch (valueType) { case V8Value.INTEGER: return array.getInteger(index); case V8Value.DOUBLE: return array.getDouble(index); case V8Value.BOOLEAN: return array.getBoolean(index); case V8Value.STRING: return array.getString(index); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_ARRAY_BUFFER: V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index); try { return buffer.getBackingStore(); } finally { buffer.release(); } case V8Value.V8_TYPED_ARRAY: V8Array typedArray = array.getArray(index); try { return toTypedArray(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array arrayValue = array.getArray(index); try { return toList(arrayValue, cache); } finally { if (arrayValue instanceof V8Array) { arrayValue.release(); } } case V8Value.V8_OBJECT: V8Object objectValue = array.getObject(index); try { return toMap(objectValue, cache); } finally { if (objectValue instanceof V8Object) { objectValue.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for index: " + index); } } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code public void release(final boolean reportMemoryLeaks) { if (isReleased()) { return; } checkThread(); releaseResources(); shutdownExecutors(forceTerminateExecutors); if (executors != null) { executors.clear(); } synchronized (lock) { runtimeCounter--; } _releaseRuntime(v8RuntimePtr); v8RuntimePtr = 0L; released = true; if (reportMemoryLeaks && (objectReferences > 0)) { throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void release(final boolean reportMemoryLeaks) { if (isReleased()) { return; } checkThread(); if (debugEnabled) { disableDebugSupport(); } releaseResources(); shutdownExecutors(forceTerminateExecutors); if (executors != null) { executors.clear(); } synchronized (lock) { runtimeCounter--; } _releaseRuntime(v8RuntimePtr); v8RuntimePtr = 0L; released = true; if (reportMemoryLeaks && (objectReferences > 0)) { throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime"); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testTypedArrayGetValue_Float64Array() { V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(80);\n" + "var floatsArray = new Float64Array(buf);\n" + "floatsArray[0] = 16.2;\n" + "floatsArray;\n"); V8TypedArray result = ((TypedArray) V8ObjectUtils.getValue(floatsArray)).getV8TypedArray(); assertEquals(10, result.length()); assertEquals(16.2, (Double) result.get(0), 0.0001); floatsArray.close(); result.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testTypedArrayGetValue_Float64Array() { V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(80);\n" + "var floatsArray = new Float64Array(buf);\n" + "floatsArray[0] = 16.2;\n" + "floatsArray;\n"); V8TypedArray result = (V8TypedArray) V8ObjectUtils.getValue(floatsArray); assertEquals(10, result.length()); assertEquals(16.2, (Double) result.get(0), 0.0001); floatsArray.close(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testPartialResults() throws Exception { byte[] key1 = randomBytes(8); byte[] key2 = randomBytes(8); FlatRow response1 = FlatRow.newBuilder() .withRowKey(ByteString.copyFrom(key1)) .addCell( new Cell( "cf", ByteString.EMPTY, 10, ByteString.copyFromUtf8("hi!"), new ArrayList<String>())) .build(); RuntimeException exception = new RuntimeException("Something bad happened"); when(mockBulkRead.add(any(Query.class))) .thenReturn(ApiFutures.immediateFuture(response1)) .thenReturn(ApiFutures.<FlatRow>immediateFailedFuture(exception)); List<Get> gets = Arrays.asList(new Get(key1), new Get(key2)); Object[] results = new Object[2]; try { createExecutor().batch(gets, results); } catch (RetriesExhaustedWithDetailsException ignored) { } Assert.assertTrue("first result is a result", results[0] instanceof Result); Assert.assertTrue(Bytes.equals(((Result) results[0]).getRow(), key1)); Assert.assertEquals(exception, results[1]); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPartialResults() throws Exception { byte[] key1 = randomBytes(8); byte[] key2 = randomBytes(8); FlatRow response1 = FlatRow.newBuilder() .withRowKey(ByteString.copyFrom(key1)) .addCell( new Cell( "cf", ByteString.EMPTY, 10, ByteString.copyFromUtf8("hi!"), new ArrayList<String>())) .build(); RuntimeException exception = new RuntimeException("Something bad happened"); when(mockBulkRead.add(any(Query.class))) .thenReturn(ApiFutures.immediateFuture(response1)) .thenReturn(ApiFutures.<FlatRow>immediateFailedFuture(exception)); List<Get> gets = Arrays.asList(new Get(key1), new Get(key2)); Object[] results = new Object[2]; try { createExecutor(options).batch(gets, results); } catch (RetriesExhaustedWithDetailsException ignored) { } Assert.assertTrue("first result is a result", results[0] instanceof Result); Assert.assertTrue(Bytes.equals(((Result) results[0]).getRow(), key1)); Assert.assertEquals(exception, results[1]); } #location 26 #vulnerability type RESOURCE_LEAK
#fixed code public void awaitCompletion() throws InterruptedException { boolean performedWarning = false; lock.lock(); try { while (!isFlushed()) { flushedCondition.await(finishWaitMillis, TimeUnit.MILLISECONDS); long now = clock.nanoTime(); if (now >= noSuccessCheckDeadlineNanos) { // There are unusual cases where an RPC could be completed, but we don't clean up // the state and the locks. Try to clean up if there is a timeout. for (RetryHandler retryHandler : outstandingRetries.values()) { retryHandler.performRetryIfStale(); } logNoSuccessWarning(now); resetNoSuccessWarningDeadline(); performedWarning = true; } } if (performedWarning) { LOG.info("awaitCompletion() completed"); } } finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void awaitCompletion() throws InterruptedException { boolean performedWarning = false; lock.lock(); try { while (!isFlushed()) { flushedCondition.await(finishWaitMillis, TimeUnit.MILLISECONDS); long now = clock.nanoTime(); if (now >= noSuccessWarningDeadlineNanos) { logNoSuccessWarning(now); resetNoSuccessWarningDeadline(); performedWarning = true; } } if (performedWarning) { LOG.info("awaitCompletion() completed"); } } finally { lock.unlock(); } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override public void run() { try { // restart the clock. synchronized (callLock) { super.run(); // pre-fetch one more result, for performance reasons. adapter.request(1); if (rowObserver instanceof ClientResponseObserver) { ((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter); } lastResponseMs = clock.currentTimeMillis(); } } catch (Exception e) { setException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override public void run() { try { // restart the clock. this.rowMerger = new RowMerger(rowObserver); adapter = new CallToStreamObserverAdapter(); synchronized (callLock) { super.run(); // pre-fetch one more result, for performance reasons. adapter.request(1); if (rowObserver instanceof ClientResponseObserver) { ((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter); } lastResponseMs = clock.currentTimeMillis(); } } catch (Exception e) { setException(e); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private Boolean run() throws IOException { try { if (this.role.equals(XLearningConstants.WORKER)) { prepareInputFiles(); } if (this.conf.getBoolean(XLearningConfiguration.XLEARNING_CONTAINER_AUTO_CREATE_OUTPUT_DIR, XLearningConfiguration.DEFAULT_XLEARNING_CONTAINER_AUTO_CREATE_OUTPUT_DIR)) { createLocalOutputDir(); } } catch (InterruptedException e) { LOG.error("Container prepare inputs failed!", e); this.reportFailedAndExit(); } catch (ExecutionException e) { LOG.error("Container prepare inputs failed!", e); this.reportFailedAndExit(); } if ("TENSORFLOW".equals(xlearningAppType) && !single) { LOG.info("Reserved available port: " + reservedSocket.getLocalPort()); amClient.reportReservedPort(envs.get(ApplicationConstants.Environment.NM_HOST.toString()), reservedSocket.getLocalPort(), this.role, this.index); while (true) { //TODO may be need encode use Base64 while used in Env this.clusterDef = amClient.getClusterDef(); if (this.clusterDef != null) { LOG.info("Cluster def is: " + this.clusterDef); break; } Utilities.sleep(this.conf.getInt(XLearningConfiguration.XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL, XLearningConfiguration.DEFAULT_XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL)); } } if (xlearningAppType.equals("DISTLIGHTGBM")) { LOG.info("Reserved available port: " + reservedSocket.getLocalPort()); this.lightGBMLocalPort = reservedSocket.getLocalPort(); InetAddress address = null; try { address = InetAddress.getByName(envs.get(ApplicationConstants.Environment.NM_HOST.toString())); } catch (UnknownHostException e) { LOG.info("acquire host ip failed " + e); reportFailedAndExit(); } String ipPortStr = address.getHostAddress() + " " + reservedSocket.getLocalPort(); LOG.info("lightGBM ip port string is: " + ipPortStr); amClient.reportLightGbmIpPort(containerId, ipPortStr); String lightGBMIpPortStr; while (true) { //TODO may be need encode use Base64 while used in Env lightGBMIpPortStr = amClient.getLightGbmIpPortStr(); if (lightGBMIpPortStr != null) { LOG.info("lightGBM IP PORT list is: " + lightGBMIpPortStr); break; } Utilities.sleep(this.conf.getInt(XLearningConfiguration.XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL, XLearningConfiguration.DEFAULT_XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL)); } Type type = new TypeToken<ConcurrentHashMap<String, String>>() { }.getType(); ConcurrentHashMap<String, String> map = new Gson().fromJson(lightGBMIpPortStr, type); PrintWriter writer = new PrintWriter("lightGBMlist.txt", "UTF-8"); for (String str : map.keySet()) { writer.println(map.get(str)); } writer.close(); } List<String> envList = new ArrayList<>(20); envList.add("PATH=" + System.getenv("PATH")); envList.add("JAVA_HOME=" + System.getenv("JAVA_HOME")); envList.add("HADOOP_HOME=" + System.getenv("HADOOP_HOME")); envList.add("HADOOP_HDFS_HOME=" + System.getenv("HADOOP_HDFS_HOME")); envList.add("LD_LIBRARY_PATH=" + "./:" + System.getenv("LD_LIBRARY_PATH") + ":" + System.getenv("JAVA_HOME") + "/jre/lib/amd64/server:" + System.getenv("HADOOP_HOME") + "/lib/native"); envList.add("CLASSPATH=" + "./:" + System.getenv("CLASSPATH") + ":" + System.getProperty("java.class.path")); envList.add("PYTHONUNBUFFERED=1"); envList.add(XLearningConstants.Environment.XLEARNING_INPUT_FILE_LIST.toString() + "=" + this.inputFileList); if ("TENSORFLOW".equals(xlearningAppType)) { envList.add(XLearningConstants.Environment.XLEARNING_TF_INDEX.toString() + "=" + this.index); envList.add(XLearningConstants.Environment.XLEARNING_TF_ROLE.toString() + "=" + this.role); if (!single) { /** * set TF_CLUSTER_DEF in env * python script can load cluster def use "json.loads(os.environ["CLUSTER_DEF"])" */ envList.add(XLearningConstants.Environment.XLEARNING_TF_CLUSTER_DEF.toString() + "=" + this.clusterDef); } } else if (xlearningAppType.equals("MXNET")) { if (!singleMx) { String dmlcID; if (this.role.equals("worker")) { dmlcID = "DMLC_WORKER_ID"; } else { dmlcID = "DMLC_SERVER_ID"; } envList.add("DMLC_PS_ROOT_URI=" + System.getenv("DMLC_PS_ROOT_URI")); envList.add("DMLC_PS_ROOT_PORT=" + System.getenv("DMLC_PS_ROOT_PORT")); envList.add("DMLC_NUM_WORKER=" + System.getenv("DMLC_NUM_WORKER")); envList.add("DMLC_NUM_SERVER=" + System.getenv("DMLC_NUM_SERVER")); envList.add(dmlcID + "=" + this.index); envList.add("DMLC_ROLE=" + this.role); } } else if (xlearningAppType.equals("DISTXGBOOST")) { envList.add("DMLC_TRACKER_URI=" + System.getenv("DMLC_TRACKER_URI")); envList.add("DMLC_TRACKER_PORT=" + System.getenv("DMLC_TRACKER_PORT")); envList.add("DMLC_NUM_WORKER=" + System.getenv("DMLC_NUM_WORKER")); envList.add("DMLC_TASK_ID=" + this.index); envList.add("DMLC_ROLE=" + this.role); } else if (xlearningAppType.equals("DISTLIGHTGBM")) { envList.add("LIGHTGBM_NUM_MACHINE=" + System.getenv(XLearningConstants.Environment.XLEARNING_LIGHTGBM_WORKER_NUM.toString())); envList.add("LIGHTGBM_LOCAL_LISTEN_PORT=" + this.lightGBMLocalPort); } if (conf.get(XLearningConfiguration.XLEARNING_INPUT_STRATEGY, XLearningConfiguration.DEFAULT_XLEARNING_INPUT_STRATEGY).toUpperCase().equals("PLACEHOLDER")) { envList.add(XLearningConstants.Environment.XLEARNING_INPUT_FILE_LIST.toString() + "=" + this.inputFileList); if (envList.toString().length() > conf.getInt(XLearningConfiguration.XLEARNING_ENV_MAXLENGTH, XLearningConfiguration.DEFAULT_XLEARNING_ENV_MAXLENGTH)) { LOG.warn("Current container environments length " + envList.toString().length() + " exceed the configuration " + XLearningConfiguration.XLEARNING_ENV_MAXLENGTH + " " + conf.getInt(XLearningConfiguration.XLEARNING_ENV_MAXLENGTH, XLearningConfiguration.DEFAULT_XLEARNING_ENV_MAXLENGTH)); envList.remove(envList.size() - 1); LOG.warn("InputFile list had written to local file: inputFileList.txt !!"); PrintWriter writer = new PrintWriter("inputFileList.txt", "UTF-8"); writer.println(this.inputFileList); writer.close(); } } String[] env = envList.toArray(new String[envList.size()]); String command = envs.get(XLearningConstants.Environment.XLEARNING_EXEC_CMD.toString()); LOG.info("Executing command:" + command); Runtime rt = Runtime.getRuntime(); //close reserved socket as tf will bind this port later this.reservedSocket.close(); final Process xlearningProcess = rt.exec(command, env); Date now = new Date(); heartbeatThread.setContainersStartTime(now.toString()); if (conf.get(XLearningConfiguration.XLEARNING_INPUT_STRATEGY, XLearningConfiguration.DEFAULT_XLEARNING_INPUT_STRATEGY).toUpperCase().equals("STREAM")) { LOG.info("Starting thread to redirect stdin of xlearning process"); Thread stdinRedirectThread = new Thread(new Runnable() { @Override public void run() { try { OutputStreamWriter osw = new OutputStreamWriter(xlearningProcess.getOutputStream()); File gzFile = new File(conf.get(XLearningConfiguration.XLEARNING_INPUTFORMAT_CACHEFILE_NAME, XLearningConfiguration.DEFAULT_XLEARNING_INPUTFORMAT_CACHEFILE_NAME)); GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream(gzFile)); boolean isCache = conf.getBoolean(XLearningConfiguration.XLEARNING_INPUTFORMAT_CACHE, XLearningConfiguration.DEFAULT_XLEARNING_INPUTFORMAT_CACHE); List<InputSplit> inputs = Arrays.asList(amClient.getStreamInputSplit(containerId)); JobConf jobConf = new JobConf(conf); RecordReader reader; InputFormat inputFormat = ReflectionUtils.newInstance(conf.getClass(XLearningConfiguration.XLEARNING_INPUTF0RMAT_CLASS, XLearningConfiguration.DEFAULT_XLEARNING_INPUTF0RMAT_CLASS, InputFormat.class), jobConf); for (int j = 0; j < conf.getInt(XLearningConfiguration.XLEARNING_STREAM_EPOCH, XLearningConfiguration.DEFAULT_XLEARNING_STREAM_EPOCH); j++) { LOG.info("Epoch " + (j + 1) + " starting..."); for (int i = 0, len = inputs.size(); i < len; i++) { LOG.info("split " + (i + 1) + " is handling..."); reader = inputFormat.getRecordReader(inputs.get(i), jobConf, Reporter.NULL); Object key = reader.createKey(); Object value = reader.createValue(); Boolean finished = false; while (!finished) { try { finished = !reader.next(key, value); if (finished) { break; } osw.write(value.toString()); osw.write("\n"); if (j == 0 && isCache) { if (conf.getInt(XLearningConfiguration.XLEARNING_STREAM_EPOCH, XLearningConfiguration.DEFAULT_XLEARNING_STREAM_EPOCH) > 1) { gos.write(value.toString().getBytes()); gos.write("\n".getBytes()); if ((gzFile.length() / 1024 / 1024) > conf.getInt(XLearningConfiguration.XLEARNING_INPUTFORMAT_CACHESIZE_LIMIT, XLearningConfiguration.DEFAULT_XLEARNING_INPUTFORMAT_CACHESIZE_LIMIT)) { LOG.info("Inputformat cache file size is:" + gzFile.length() / 1024 / 1024 + "M " + "beyond the limit size:" + conf.getInt(XLearningConfiguration.XLEARNING_INPUTFORMAT_CACHESIZE_LIMIT, XLearningConfiguration.DEFAULT_XLEARNING_INPUTFORMAT_CACHESIZE_LIMIT) + "M."); gzFile.delete(); LOG.info("Local cache file deleted and will not use cache."); isCache = false; } } } } catch (EOFException e) { finished = true; e.printStackTrace(); } } reader.close(); LOG.info("split " + (i + 1) + " is finished."); } LOG.info("Epoch " + (j + 1) + " finished."); if (isCache) { break; } } osw.close(); gos.close(); } catch (Exception e) { LOG.warn("Exception in thread stdinRedirectThread"); e.printStackTrace(); } } }); stdinRedirectThread.start(); } List<OutputInfo> outputs = Arrays.asList(amClient.getOutputLocation()); if ((this.conf.get(XLearningConfiguration.XLEARNING_OUTPUT_STRATEGY, XLearningConfiguration.DEFAULT_XLEARNING_OUTPUT_STRATEGY).equals("STREAM")) && outputs.size() > 0) { LOG.info("Starting thread to redirect stream stdout of xlearning process"); final Thread stdoutRedirectThread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader reader; reader = new BufferedReader(new InputStreamReader(xlearningProcess.getInputStream())); List<OutputInfo> outputs = Arrays.asList(amClient.getOutputLocation()); JobConf jobConf = new JobConf(conf); jobConf.setOutputKeyClass(Text.class); jobConf.setOutputValueClass(Text.class); jobConf.setBoolean("mapred.output.compress", true); jobConf.set("mapred.output.compression.codec", "org.apache.hadoop.io.compress.GzipCodec"); jobConf.setOutputFormat(TextMultiOutputFormat.class); Path remotePath = new Path(outputs.get(0).getDfsLocation() + "/_temporary/" + containerId.toString()); FileSystem dfs = remotePath.getFileSystem(jobConf); jobConf.set(XLearningConstants.STREAM_OUTPUT_DIR, remotePath.makeQualified(dfs).toString()); OutputFormat outputFormat = ReflectionUtils.newInstance(conf.getClass(XLearningConfiguration.XLEARNING_OUTPUTFORMAT_CLASS, XLearningConfiguration.DEFAULT_XLEARNING_OUTPUTF0RMAT_CLASS, OutputFormat.class), jobConf); outputFormat.checkOutputSpecs(dfs, jobConf); JobID jobID = new JobID(new SimpleDateFormat("yyyyMMddHHmm").format(new Date()), 0); TaskAttemptID taId = new TaskAttemptID(new TaskID(jobID, true, 0), 0); jobConf.set("mapred.tip.id", taId.getTaskID().toString()); jobConf.set("mapred.task.id", taId.toString()); jobConf.set("mapred.job.id", jobID.toString()); amClient.reportMapedTaskID(containerId, taId.toString()); RecordWriter writer = outputFormat.getRecordWriter(dfs, jobConf, "part-r", Reporter.NULL); String xlearningStreamResultLine; while ((xlearningStreamResultLine = reader.readLine()) != null) { writer.write(null, xlearningStreamResultLine); } writer.close(Reporter.NULL); reader.close(); dfs.close(); } catch (Exception e) { LOG.warn("Exception in thread stdoutRedirectThread"); e.printStackTrace(); } } }); stdoutRedirectThread.start(); } else { LOG.info("Starting thread to redirect stdout of xlearning process"); Thread stdoutRedirectThread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader reader; reader = new BufferedReader(new InputStreamReader(xlearningProcess.getInputStream())); String xlearningStdoutLog; while ((xlearningStdoutLog = reader.readLine()) != null) { LOG.info(xlearningStdoutLog); } } catch (Exception e) { LOG.warn("Exception in thread stdoutRedirectThread"); e.printStackTrace(); } } }); stdoutRedirectThread.start(); } LOG.info("Starting thread to redirect stderr of xlearning process"); Thread stderrRedirectThread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader reader; reader = new BufferedReader(new InputStreamReader(xlearningProcess.getErrorStream())); String xlearningStderrLog; while ((xlearningStderrLog = reader.readLine()) != null) { if (xlearningStderrLog.contains("reporter progress")) { heartbeatThread.setProgressLog(xlearningStderrLog); } else { LOG.info(xlearningStderrLog); } } } catch (Exception e) { LOG.warn("Error in thread stderrRedirectThread"); e.printStackTrace(); } } }); stderrRedirectThread.start(); heartbeatThread.setContainerStatus(XLearningContainerStatus.RUNNING); //Start board process int boardIndex = this.conf.getInt(XLearningConfiguration.XLEARNING_TF_BOARD_WORKER_INDEX, XLearningConfiguration.DEFAULT_XLEARNING_TF_BOARD_WORKER_INDEX); Boolean boardEnable = this.conf.getBoolean(XLearningConfiguration.XLEARNING_TF_BOARD_ENABLE, XLearningConfiguration.DEFAULT_XLEARNING_TF_BOARD_ENABLE); if (boardEnable && this.role.equals(XLearningConstants.WORKER) && boardIndex == this.index) { Socket boardReservedSocket = new Socket(); try { boardReservedSocket.bind(new InetSocketAddress("127.0.0.1", 0)); } catch (IOException e) { LOG.error("Can not get available port"); reportFailedAndExit(); } String boardHost = envs.get(ApplicationConstants.Environment.NM_HOST.toString()); String boardLogDir = this.conf.get(XLearningConfiguration.XLEARNING_TF_BOARD_LOG_DIR, XLearningConfiguration.DEFAULT_XLEARNING_TF_BOARD_LOG_DIR); int boardPort = boardReservedSocket.getLocalPort(); String boardCommand; if ("TENSORFLOW".equals(xlearningAppType)) { int boardReloadInterval = this.conf.getInt(XLearningConfiguration.XLEARNING_TF_BOARD_RELOAD_INTERVAL, XLearningConfiguration.DEFAULT_XLEARNING_TF_BOARD_RELOAD_INTERVAL); boardCommand = this.conf.get(XLearningConfiguration.XLEARNING_TF_BOARD_PATH, XLearningConfiguration.DEFAULT_XLEARNING_TF_BOARD_PATH) + " --host=" + boardHost + " --port=" + boardPort + " --reload_interval=" + boardReloadInterval + " --logdir=" + boardLogDir; } else { int boardCacheTimeout = this.conf.getInt(XLearningConfiguration.XLEARNING_BOARD_CACHE_TIMEOUT, XLearningConfiguration.DEFAULT_XLEARNING_BOARD_CACHE_TIMEOUT); boardCommand = this.conf.get(XLearningConfiguration.XLEARNING_BOARD_PATH, XLearningConfiguration.DEFAULT_XLEARNING_BOARD_PATH) + " --host=" + boardHost + " --port=" + boardPort + " --logdir=" + boardLogDir + " --cache_timeout=" + boardCacheTimeout; String modelpb = this.conf.get(XLearningConfiguration.XLEARNING_BOARD_MODELPB, XLearningConfiguration.DEFAULT_XLEARNING_BOARD_MODELPB); if (!(modelpb.equals("") || modelpb == null)) { boardCommand = boardCommand + " --model_pb=" + modelpb; } } String boardUrl = "http://" + boardHost + ":" + boardPort; LOG.info("Executing board command:" + boardCommand); boardReservedSocket.close(); try { final Process boardProcess = rt.exec(boardCommand, env); LOG.info("Starting thread to redirect stdout of board process"); Thread boardStdoutRedirectThread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader reader; reader = new BufferedReader(new InputStreamReader(boardProcess.getInputStream())); String boardStdoutLog; while ((boardStdoutLog = reader.readLine()) != null) { LOG.debug(boardStdoutLog); } } catch (Exception e) { LOG.warn("Exception in thread boardStdoutRedirectThread"); e.printStackTrace(); } } }); boardStdoutRedirectThread.start(); LOG.info("Starting thread to redirect stderr of board process"); Thread boardStderrRedirectThread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader reader; reader = new BufferedReader(new InputStreamReader(boardProcess.getErrorStream())); String boardStderrLog; while ((boardStderrLog = reader.readLine()) != null) { LOG.debug(boardStderrLog); } } catch (Exception e) { LOG.warn("Error in thread boardStderrRedirectThread"); e.printStackTrace(); } } }); boardStderrRedirectThread.start(); amClient.reportTensorBoardURL(boardUrl); LOG.info("Container index is " + index + ", report board url:" + boardUrl); } catch (Exception e) { LOG.error("Board Process failed. For more detail: " + e); } } int updateAppStatusInterval = this.conf.getInt(XLearningConfiguration.XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL, XLearningConfiguration.DEFAULT_XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL); this.xlearningCmdProcessId = getPidOfProcess(xlearningProcess); LOG.info("xlearningCmdProcessId is:" + this.xlearningCmdProcessId); containerReporter = new ContainerReporter(amClient, conf, containerId, this.xlearningCmdProcessId); containerReporter.setDaemon(true); containerReporter.start(); int code = -1; while (code == -1 && !heartbeatThread.isXLearningTrainCompleted()) { Utilities.sleep(updateAppStatusInterval); try { code = xlearningProcess.exitValue(); } catch (IllegalThreadStateException e) { LOG.debug("XLearning Process is running"); } } if (this.role.equals(XLearningConstants.PS) && this.xlearningAppType.equals("TENSORFLOW")) { if (code == -1 || code == 0) { this.uploadOutputFiles(); } } if (this.role.equals(XLearningConstants.PS)) { if (code == -1) { xlearningProcess.destroy(); return true; } else if (code == 0) { return true; } return false; } if (this.role.equals("server")) { if (code == -1) { xlearningProcess.destroy(); return true; } else if (code == 0) { return true; } return false; } //As role is worker if (code == 0) { this.uploadOutputFiles(); } else { return false; } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Boolean run() throws IOException { try { if (this.role.equals(XLearningConstants.WORKER)) { prepareInputFiles(); } if (this.conf.getBoolean(XLearningConfiguration.XLEARNING_CONTAINER_AUTO_CREATE_OUTPUT_DIR, XLearningConfiguration.DEFAULT_XLEARNING_CONTAINER_AUTO_CREATE_OUTPUT_DIR)) { createLocalOutputDir(); } } catch (InterruptedException e) { LOG.error("Container prepare inputs failed!", e); this.reportFailedAndExit(); } catch (ExecutionException e) { LOG.error("Container prepare inputs failed!", e); this.reportFailedAndExit(); } if ("TENSORFLOW".equals(xlearningAppType) && !single) { LOG.info("Reserved available port: " + reservedSocket.getLocalPort()); amClient.reportReservedPort(envs.get(ApplicationConstants.Environment.NM_HOST.toString()), reservedSocket.getLocalPort(), this.role, this.index); while (true) { //TODO may be need encode use Base64 while used in Env this.clusterDef = amClient.getClusterDef(); if (this.clusterDef != null) { LOG.info("Cluster def is: " + this.clusterDef); break; } Utilities.sleep(this.conf.getInt(XLearningConfiguration.XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL, XLearningConfiguration.DEFAULT_XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL)); } } if (xlearningAppType.equals("DISTLIGHTGBM")) { LOG.info("Reserved available port: " + reservedSocket.getLocalPort()); this.lightGBMLocalPort = reservedSocket.getLocalPort(); InetAddress address = null; try { address = InetAddress.getByName(envs.get(ApplicationConstants.Environment.NM_HOST.toString())); } catch (UnknownHostException e) { LOG.info("acquire host ip failed " + e); reportFailedAndExit(); } String ipPortStr = address.getHostAddress() + " " + reservedSocket.getLocalPort(); LOG.info("lightGBM ip port string is: " + ipPortStr); amClient.reportLightGbmIpPort(containerId, ipPortStr); String lightGBMIpPortStr; while (true) { //TODO may be need encode use Base64 while used in Env lightGBMIpPortStr = amClient.getLightGbmIpPortStr(); if (lightGBMIpPortStr != null) { LOG.info("lightGBM IP PORT list is: " + lightGBMIpPortStr); break; } Utilities.sleep(this.conf.getInt(XLearningConfiguration.XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL, XLearningConfiguration.DEFAULT_XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL)); } Type type = new TypeToken<ConcurrentHashMap<String, String>>() { }.getType(); ConcurrentHashMap<String, String> map = new Gson().fromJson(lightGBMIpPortStr, type); PrintWriter writer = new PrintWriter("lightGBMlist.txt", "UTF-8"); for (String str : map.keySet()) { writer.println(map.get(str)); } writer.close(); } List<String> envList = new ArrayList<>(20); envList.add("PATH=" + System.getenv("PATH")); envList.add("JAVA_HOME=" + System.getenv("JAVA_HOME")); envList.add("HADOOP_HOME=" + System.getenv("HADOOP_HOME")); envList.add("HADOOP_HDFS_HOME=" + System.getenv("HADOOP_HDFS_HOME")); envList.add("LD_LIBRARY_PATH=" + "./:" + System.getenv("LD_LIBRARY_PATH") + ":" + System.getenv("JAVA_HOME") + "/jre/lib/amd64/server:" + System.getenv("HADOOP_HOME") + "/lib/native"); envList.add("CLASSPATH=" + "./:" + System.getenv("CLASSPATH") + ":" + System.getProperty("java.class.path")); envList.add("PYTHONUNBUFFERED=1"); envList.add(XLearningConstants.Environment.XLEARNING_INPUT_FILE_LIST.toString() + "=" + this.inputFileList); if ("TENSORFLOW".equals(xlearningAppType)) { envList.add(XLearningConstants.Environment.XLEARNING_TF_INDEX.toString() + "=" + this.index); envList.add(XLearningConstants.Environment.XLEARNING_TF_ROLE.toString() + "=" + this.role); if (!single) { /** * set TF_CLUSTER_DEF in env * python script can load cluster def use "json.loads(os.environ["CLUSTER_DEF"])" */ envList.add(XLearningConstants.Environment.XLEARNING_TF_CLUSTER_DEF.toString() + "=" + this.clusterDef); } } else if (xlearningAppType.equals("MXNET")) { if (!singleMx) { String dmlcID; if (this.role.equals("worker")) { dmlcID = "DMLC_WORKER_ID"; } else { dmlcID = "DMLC_SERVER_ID"; } envList.add("DMLC_PS_ROOT_URI=" + System.getenv("DMLC_PS_ROOT_URI")); envList.add("DMLC_PS_ROOT_PORT=" + System.getenv("DMLC_PS_ROOT_PORT")); envList.add("DMLC_NUM_WORKER=" + System.getenv("DMLC_NUM_WORKER")); envList.add("DMLC_NUM_SERVER=" + System.getenv("DMLC_NUM_SERVER")); envList.add(dmlcID + "=" + this.index); envList.add("DMLC_ROLE=" + this.role); } } else if (xlearningAppType.equals("DISTXGBOOST")) { envList.add("DMLC_TRACKER_URI=" + System.getenv("DMLC_TRACKER_URI")); envList.add("DMLC_TRACKER_PORT=" + System.getenv("DMLC_TRACKER_PORT")); envList.add("DMLC_NUM_WORKER=" + System.getenv("DMLC_NUM_WORKER")); envList.add("DMLC_TASK_ID=" + this.index); envList.add("DMLC_ROLE=" + this.role); } else if (xlearningAppType.equals("DISTLIGHTGBM")) { envList.add("LIGHTGBM_NUM_MACHINE=" + System.getenv(XLearningConstants.Environment.XLEARNING_LIGHTGBM_WORKER_NUM.toString())); envList.add("LIGHTGBM_LOCAL_LISTEN_PORT=" + this.lightGBMLocalPort); } if (conf.get(XLearningConfiguration.XLEARNING_INPUT_STRATEGY, XLearningConfiguration.DEFAULT_XLEARNING_INPUT_STRATEGY).toUpperCase().equals("PLACEHOLDER")) { envList.add(XLearningConstants.Environment.XLEARNING_INPUT_FILE_LIST.toString() + "=" + this.inputFileList); if (envList.toString().length() > conf.getInt(XLearningConfiguration.XLEARNING_ENV_MAXLENGTH, XLearningConfiguration.DEFAULT_XLEARNING_ENV_MAXLENGTH)) { LOG.warn("Current container environments length " + envList.toString().length() + " exceed the configuration " + XLearningConfiguration.XLEARNING_ENV_MAXLENGTH + " " + conf.getInt(XLearningConfiguration.XLEARNING_ENV_MAXLENGTH, XLearningConfiguration.DEFAULT_XLEARNING_ENV_MAXLENGTH)); envList.remove(envList.size() - 1); LOG.warn("InputFile list had written to local file: inputFileList.txt !!"); PrintWriter writer = new PrintWriter("inputFileList.txt", "UTF-8"); writer.println(this.inputFileList); writer.close(); } } String[] env = envList.toArray(new String[envList.size()]); String command = envs.get(XLearningConstants.Environment.XLEARNING_EXEC_CMD.toString()); LOG.info("Executing command:" + command); Runtime rt = Runtime.getRuntime(); //close reserved socket as tf will bind this port later this.reservedSocket.close(); final Process xlearningProcess = rt.exec(command, env); Date now = new Date(); heartbeatThread.setContainersStartTime(now.toString()); if (conf.get(XLearningConfiguration.XLEARNING_INPUT_STRATEGY, XLearningConfiguration.DEFAULT_XLEARNING_INPUT_STRATEGY).toUpperCase().equals("STREAM")) { LOG.info("Starting thread to redirect stdin of xlearning process"); Thread stdinRedirectThread = new Thread(new Runnable() { @Override public void run() { try { OutputStreamWriter osw = new OutputStreamWriter(xlearningProcess.getOutputStream()); File gzFile = new File(conf.get(XLearningConfiguration.XLEARNING_INPUTFORMAT_CACHEFILE_NAME, XLearningConfiguration.DEFAULT_XLEARNING_INPUTFORMAT_CACHEFILE_NAME)); GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream(gzFile)); boolean isCache = conf.getBoolean(XLearningConfiguration.XLEARNING_INPUTFORMAT_CACHE, XLearningConfiguration.DEFAULT_XLEARNING_INPUTFORMAT_CACHE); List<InputSplit> inputs = Arrays.asList(amClient.getStreamInputSplit(containerId)); JobConf jobConf = new JobConf(conf); RecordReader reader; InputFormat inputFormat = ReflectionUtils.newInstance(conf.getClass(XLearningConfiguration.XLEARNING_INPUTF0RMAT_CLASS, XLearningConfiguration.DEFAULT_XLEARNING_INPUTF0RMAT_CLASS, InputFormat.class), jobConf); for (int j = 0; j < conf.getInt(XLearningConfiguration.XLEARNING_STREAM_EPOCH, XLearningConfiguration.DEFAULT_XLEARNING_STREAM_EPOCH); j++) { LOG.info("Epoch " + (j + 1) + " starting..."); for (int i = 0, len = inputs.size(); i < len; i++) { LOG.info("split " + (i + 1) + " is handling..."); reader = inputFormat.getRecordReader(inputs.get(i), jobConf, Reporter.NULL); Object key = reader.createKey(); Object value = reader.createValue(); Boolean finished = false; while (!finished) { try { finished = !reader.next(key, value); if (finished) { break; } osw.write(value.toString()); osw.write("\n"); if (j == 0 && isCache) { if (conf.getInt(XLearningConfiguration.XLEARNING_STREAM_EPOCH, XLearningConfiguration.DEFAULT_XLEARNING_STREAM_EPOCH) > 1) { gos.write(value.toString().getBytes()); gos.write("\n".getBytes()); if ((gzFile.length() / 1024 / 1024) > conf.getInt(XLearningConfiguration.XLEARNING_INPUTFORMAT_CACHESIZE_LIMIT, XLearningConfiguration.DEFAULT_XLEARNING_INPUTFORMAT_CACHESIZE_LIMIT)) { LOG.info("Inputformat cache file size is:" + gzFile.length() / 1024 / 1024 + "M " + "beyond the limit size:" + conf.getInt(XLearningConfiguration.XLEARNING_INPUTFORMAT_CACHESIZE_LIMIT, XLearningConfiguration.DEFAULT_XLEARNING_INPUTFORMAT_CACHESIZE_LIMIT) + "M."); gzFile.delete(); LOG.info("Local cache file deleted and will not use cache."); isCache = false; } } } } catch (EOFException e) { finished = true; e.printStackTrace(); } } reader.close(); LOG.info("split " + (i + 1) + " is finished."); } LOG.info("Epoch " + (j + 1) + " finished."); if (isCache) { break; } } osw.close(); gos.close(); } catch (Exception e) { LOG.warn("Exception in thread stdinRedirectThread"); e.printStackTrace(); } } }); stdinRedirectThread.start(); } List<OutputInfo> outputs = Arrays.asList(amClient.getOutputLocation()); if ((this.conf.get(XLearningConfiguration.XLEARNING_OUTPUT_STRATEGY, XLearningConfiguration.DEFAULT_XLEARNING_OUTPUT_STRATEGY).equals("STREAM")) && outputs.size() > 0) { LOG.info("Starting thread to redirect stream stdout of xlearning process"); final Thread stdoutRedirectThread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader reader; reader = new BufferedReader(new InputStreamReader(xlearningProcess.getInputStream())); List<OutputInfo> outputs = Arrays.asList(amClient.getOutputLocation()); JobConf jobConf = new JobConf(conf); jobConf.setOutputKeyClass(Text.class); jobConf.setOutputValueClass(Text.class); jobConf.setBoolean("mapred.output.compress", true); jobConf.set("mapred.output.compression.codec", "org.apache.hadoop.io.compress.GzipCodec"); jobConf.setOutputFormat(TextMultiOutputFormat.class); Path remotePath = new Path(outputs.get(0).getDfsLocation() + "/_temporary/" + containerId.toString()); FileSystem dfs = remotePath.getFileSystem(jobConf); jobConf.set(XLearningConstants.STREAM_OUTPUT_DIR, remotePath.makeQualified(dfs).toString()); OutputFormat outputFormat = ReflectionUtils.newInstance(conf.getClass(XLearningConfiguration.XLEARNING_OUTPUTFORMAT_CLASS, XLearningConfiguration.DEFAULT_XLEARNING_OUTPUTF0RMAT_CLASS, OutputFormat.class), jobConf); outputFormat.checkOutputSpecs(dfs, jobConf); JobID jobID = new JobID(new SimpleDateFormat("yyyyMMddHHmm").format(new Date()), 0); TaskAttemptID taId = new TaskAttemptID(new TaskID(jobID, true, 0), 0); jobConf.set("mapred.tip.id", taId.getTaskID().toString()); jobConf.set("mapred.task.id", taId.toString()); jobConf.set("mapred.job.id", jobID.toString()); amClient.reportMapedTaskID(containerId, taId.toString()); RecordWriter writer = outputFormat.getRecordWriter(dfs, jobConf, "part-r", Reporter.NULL); String xlearningStreamResultLine; while ((xlearningStreamResultLine = reader.readLine()) != null) { writer.write(null, xlearningStreamResultLine); } writer.close(Reporter.NULL); reader.close(); dfs.close(); } catch (Exception e) { LOG.warn("Exception in thread stdoutRedirectThread"); e.printStackTrace(); } } }); stdoutRedirectThread.start(); } else { LOG.info("Starting thread to redirect stdout of xlearning process"); Thread stdoutRedirectThread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader reader; reader = new BufferedReader(new InputStreamReader(xlearningProcess.getInputStream())); String xlearningStdoutLog; while ((xlearningStdoutLog = reader.readLine()) != null) { LOG.info(xlearningStdoutLog); } } catch (Exception e) { LOG.warn("Exception in thread stdoutRedirectThread"); e.printStackTrace(); } } }); stdoutRedirectThread.start(); } LOG.info("Starting thread to redirect stderr of xlearning process"); Thread stderrRedirectThread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader reader; reader = new BufferedReader(new InputStreamReader(xlearningProcess.getErrorStream())); String xlearningStderrLog; while ((xlearningStderrLog = reader.readLine()) != null) { if (xlearningStderrLog.contains("reporter progress")) { heartbeatThread.setProgressLog(xlearningStderrLog); } else { LOG.info(xlearningStderrLog); } } } catch (Exception e) { LOG.warn("Error in thread stderrRedirectThread"); e.printStackTrace(); } } }); stderrRedirectThread.start(); heartbeatThread.setContainerStatus(XLearningContainerStatus.RUNNING); //Start board process int boardIndex = this.conf.getInt(XLearningConfiguration.XLEARNING_TF_BOARD_WORKER_INDEX, XLearningConfiguration.DEFAULT_XLEARNING_TF_BOARD_WORKER_INDEX); Boolean boardEnable = this.conf.getBoolean(XLearningConfiguration.XLEARNING_TF_BOARD_ENABLE, XLearningConfiguration.DEFAULT_XLEARNING_TF_BOARD_ENABLE); if (boardEnable && this.role.equals(XLearningConstants.WORKER) && boardIndex == this.index) { Socket boardReservedSocket = new Socket(); try { boardReservedSocket.bind(new InetSocketAddress("127.0.0.1", 0)); } catch (IOException e) { LOG.error("Can not get available port"); reportFailedAndExit(); } String boardHost = envs.get(ApplicationConstants.Environment.NM_HOST.toString()); String boardLogDir = this.conf.get(XLearningConfiguration.XLEARNING_TF_BOARD_LOG_DIR, XLearningConfiguration.DEFAULT_XLEARNING_TF_BOARD_LOG_DIR); int boardPort = boardReservedSocket.getLocalPort(); String boardCommand; if ("TENSORFLOW".equals(xlearningAppType)) { int boardReloadInterval = this.conf.getInt(XLearningConfiguration.XLEARNING_TF_BOARD_RELOAD_INTERVAL, XLearningConfiguration.DEFAULT_XLEARNING_TF_BOARD_RELOAD_INTERVAL); boardCommand = this.conf.get(XLearningConfiguration.XLEARNING_TF_BOARD_PATH, XLearningConfiguration.DEFAULT_XLEARNING_TF_BOARD_PATH) + " --host=" + boardHost + " --port=" + boardPort + " --reload_interval=" + boardReloadInterval + " --logdir=" + boardLogDir; } else { int boardCacheTimeout = this.conf.getInt(XLearningConfiguration.XLEARNING_BOARD_CACHE_TIMEOUT, XLearningConfiguration.DEFAULT_XLEARNING_BOARD_CACHE_TIMEOUT); boardCommand = this.conf.get(XLearningConfiguration.XLEARNING_BOARD_PATH, XLearningConfiguration.DEFAULT_XLEARNING_BOARD_PATH) + " --host=" + boardHost + " --port=" + boardPort + " --logdir=" + boardLogDir + " --cache_timeout=" + boardCacheTimeout; String modelpb = this.conf.get(XLearningConfiguration.XLEARNING_BOARD_MODELPB, XLearningConfiguration.DEFAULT_XLEARNING_BOARD_MODELPB); if (!(modelpb.equals("") || modelpb == null)) { boardCommand = boardCommand + " --model_pb=" + modelpb; } } String boardUrl = "http://" + boardHost + ":" + boardPort; LOG.info("Executing board command:" + boardCommand); boardReservedSocket.close(); try { final Process boardProcess = rt.exec(boardCommand, env); LOG.info("Starting thread to redirect stdout of board process"); Thread boardStdoutRedirectThread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader reader; reader = new BufferedReader(new InputStreamReader(boardProcess.getInputStream())); String boardStdoutLog; while ((boardStdoutLog = reader.readLine()) != null) { LOG.debug(boardStdoutLog); } } catch (Exception e) { LOG.warn("Exception in thread boardStdoutRedirectThread"); e.printStackTrace(); } } }); boardStdoutRedirectThread.start(); LOG.info("Starting thread to redirect stderr of board process"); Thread boardStderrRedirectThread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader reader; reader = new BufferedReader(new InputStreamReader(boardProcess.getErrorStream())); String boardStderrLog; while ((boardStderrLog = reader.readLine()) != null) { LOG.debug(boardStderrLog); } } catch (Exception e) { LOG.warn("Error in thread boardStderrRedirectThread"); e.printStackTrace(); } } }); boardStderrRedirectThread.start(); amClient.reportTensorBoardURL(boardUrl); LOG.info("Container index is " + index + ", report board url:" + boardUrl); } catch (Exception e) { LOG.error("Board Process failed. For more detail: " + e); } } int updateAppStatusInterval = this.conf.getInt(XLearningConfiguration.XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL, XLearningConfiguration.DEFAULT_XLEARNING_CONTAINER_UPDATE_APP_STATUS_INTERVAL); if (this.role.equals(XLearningConstants.WORKER)) { this.xlearningCmdProcessId = getPidOfProcess(xlearningProcess); LOG.info("xlearningCmdProcessId is:" + this.xlearningCmdProcessId); containerReporter = new ContainerReporter(amClient, conf, containerId, this.xlearningCmdProcessId); containerReporter.setDaemon(true); containerReporter.start(); } int code = -1; while (code == -1 && !heartbeatThread.isXLearningTrainCompleted()) { Utilities.sleep(updateAppStatusInterval); try { code = xlearningProcess.exitValue(); } catch (IllegalThreadStateException e) { LOG.debug("XLearning Process is running"); } } if (this.role.equals(XLearningConstants.PS) && this.xlearningAppType.equals("TENSORFLOW")) { if (code == -1 || code == 0) { this.uploadOutputFiles(); } } if (this.role.equals(XLearningConstants.PS)) { if (code == -1) { xlearningProcess.destroy(); return true; } else if (code == 0) { return true; } return false; } if (this.role.equals("server")) { if (code == -1) { xlearningProcess.destroy(); return true; } else if (code == 0) { return true; } return false; } //As role is worker if (code == 0) { this.uploadOutputFiles(); } else { return false; } return true; } #location 399 #vulnerability type RESOURCE_LEAK
#fixed code public void validate() { Map<String, Binding<?>> allBindings = linkEverything(); new ProblemDetector().detectProblems(allBindings.values()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void validate() { Map<String, Binding<?>> allBindings; synchronized (linker) { linkStaticInjections(); linkEntryPoints(); allBindings = linker.linkAll(); } new ProblemDetector().detectProblems(allBindings.values()); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static void main(String[] args) { SpringApplication.run(GoodsKillRpcServiceApplication.class); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { log.info(">>>>> goodsKill-rpc-service 正在启动 <<<<<"); AbstractApplicationContext context= new ClassPathXmlApplicationContext( "classpath*:META-INF/spring/spring-*.xml"); // 程序退出前优雅关闭JVM context.registerShutdownHook(); context.start(); log.info(">>>>> goodsKill-rpc-service 启动完成 <<<<<"); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test(expected = NullPointerException.class) public void testCreateNull() { new TemplateList(null,(String[]) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = NullPointerException.class) public void testCreateNull() { new PatternList((String[]) null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public void atExpr(Expr expr) throws CompileError { // array access, member access, // (unary) +, (unary) -, ++, --, !, ~ int token = expr.getOperator(); ASTree oprand = expr.oprand1(); if (token == '.') { String member = ((Symbol)expr.oprand2()).get(); if (member.equals("length")) atArrayLength(expr); else if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); } else if (token == MEMBER) { // field read String member = ((Symbol)expr.oprand2()).get(); if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); } else if (token == ARRAY) atArrayRead(oprand, expr.oprand2()); else if (token == PLUSPLUS || token == MINUSMINUS) atPlusPlus(token, oprand, expr); else if (token == '!') booleanExpr(expr); else if (token == CALL) // method call fatal(); else { oprand.accept(this); if (!isConstant(expr, token, oprand)) if (token == '-' || token == '~') if (CodeGen.isP_INT(exprType)) exprType = INT; // type may be BYTE, ... } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void atExpr(Expr expr) throws CompileError { // array access, member access, // (unary) +, (unary) -, ++, --, !, ~ int token = expr.getOperator(); ASTree oprand = expr.oprand1(); if (token == '.') { String member = ((Symbol)expr.oprand2()).get(); if (member.equals("length")) atArrayLength(expr); else if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); } else if (token == MEMBER) { // field read String member = ((Symbol)expr.oprand2()).get(); if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); } else if (token == ARRAY) atArrayRead(oprand, expr.oprand2()); else if (token == PLUSPLUS || token == MINUSMINUS) atPlusPlus(token, oprand, expr); else if (token == '!') booleanExpr(expr); else if (token == CALL) // method call fatal(); else { expr.oprand1().accept(this); if (token == '-' || token == '~') if (CodeGen.isP_INT(exprType)) exprType = INT; // type may be BYTE, ... } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public void atExpr(Expr expr) throws CompileError { // array access, member access, // (unary) +, (unary) -, ++, --, !, ~ int token = expr.getOperator(); ASTree oprand = expr.oprand1(); if (token == '.') { String member = ((Symbol)expr.oprand2()).get(); if (member.equals("length")) atArrayLength(expr); else if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); } else if (token == MEMBER) { // field read String member = ((Symbol)expr.oprand2()).get(); if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); } else if (token == ARRAY) atArrayRead(oprand, expr.oprand2()); else if (token == PLUSPLUS || token == MINUSMINUS) atPlusPlus(token, oprand, expr); else if (token == '!') booleanExpr(expr); else if (token == CALL) // method call fatal(); else { oprand.accept(this); if (!isConstant(expr, token, oprand)) if (token == '-' || token == '~') if (CodeGen.isP_INT(exprType)) exprType = INT; // type may be BYTE, ... } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void atExpr(Expr expr) throws CompileError { // array access, member access, // (unary) +, (unary) -, ++, --, !, ~ int token = expr.getOperator(); ASTree oprand = expr.oprand1(); if (token == '.') { String member = ((Symbol)expr.oprand2()).get(); if (member.equals("length")) atArrayLength(expr); else if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); } else if (token == MEMBER) { // field read String member = ((Symbol)expr.oprand2()).get(); if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); } else if (token == ARRAY) atArrayRead(oprand, expr.oprand2()); else if (token == PLUSPLUS || token == MINUSMINUS) atPlusPlus(token, oprand, expr); else if (token == '!') booleanExpr(expr); else if (token == CALL) // method call fatal(); else { expr.oprand1().accept(this); if (token == '-' || token == '~') if (CodeGen.isP_INT(exprType)) exprType = INT; // type may be BYTE, ... } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code private void atPlusPlus(int token, ASTree oprand, Expr expr) throws CompileError { boolean isPost = oprand == null; // ++i or i++? if (isPost) oprand = expr.oprand2(); if (oprand instanceof Variable) { Declarator d = ((Variable)oprand).getDeclarator(); exprType = d.getType(); arrayDim = d.getArrayDim(); } else { if (oprand instanceof Expr) { Expr e = (Expr)oprand; if (e.getOperator() == ARRAY) { atArrayRead(e.oprand1(), e.oprand2()); // arrayDim should be 0. int t = exprType; if (t == INT || t == BYTE || t == CHAR || t == SHORT) exprType = INT; return; } } atFieldPlusPlus(oprand); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void atPlusPlus(int token, ASTree oprand, Expr expr) throws CompileError { boolean isPost = oprand == null; // ++i or i++? if (isPost) oprand = expr.oprand2(); if (oprand instanceof Variable) { Declarator d = ((Variable)oprand).getDeclarator(); exprType = d.getType(); arrayDim = d.getArrayDim(); } else { if (oprand instanceof Expr) { Expr e = (Expr)oprand; if (e.getOperator() == ARRAY) { atArrayRead(expr.oprand1(), expr.oprand2()); // arrayDim should be 0. int t = exprType; if (t == INT || t == BYTE || t == CHAR || t == SHORT) exprType = INT; return; } } atFieldPlusPlus(oprand); } } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code public void renameClass(Map classnames) { LongVector v = items; int size = numOfItems; classes = new HashMap(classes.size() * 2); for (int i = 1; i < size; ++i) { ConstInfo ci = (ConstInfo)v.elementAt(i); ci.renameClass(this, classnames); ci.makeHashtable(this); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void renameClass(Map classnames) { LongVector v = items; int size = numOfItems; for (int i = 1; i < size; ++i) ((ConstInfo)v.elementAt(i)).renameClass(this, classnames); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected CommandLine processOptions(ObjectInspector[] argOIs) throws UDFArgumentException { CommandLine cl = super.processOptions(argOIs); if(cl == null) { this.eta0 = 0.1f; this.eps = 1.f; this.scaling = 100f; } else { this.eta0 = Primitives.parseFloat(cl.getOptionValue("eta0"), 0.1f); this.eps = Primitives.parseFloat(cl.getOptionValue("eps"), 1.f); this.scaling = Primitives.parseFloat(cl.getOptionValue("scale"), 100f); } return cl; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected CommandLine processOptions(ObjectInspector[] argOIs) throws UDFArgumentException { CommandLine cl = super.processOptions(argOIs); this.eta0 = Primitives.parseFloat(cl.getOptionValue("eta0"), 0.1f); this.eps = Primitives.parseFloat(cl.getOptionValue("eps"), 1.f); this.scaling = Primitives.parseFloat(cl.getOptionValue("scale"), 100f); return cl; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testEvaluate() throws IOException { CosineSimilarityUDF cosine = new CosineSimilarityUDF(); { List<String> ftvec1 = Arrays.asList("bbb:1.4", "aaa:0.9", "ccc"); Assert.assertEquals(1.f, cosine.evaluate(ftvec1, ftvec1).get(), 0.0); } Assert.assertEquals(0.f, cosine.evaluate(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e")).get(), 0.0); Assert.assertEquals(0.f, cosine.evaluate(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e")).get(), 0.0); Assert.assertEquals(1.f, cosine.evaluate(Arrays.asList("a", "b"), Arrays.asList("a", "b")).get(), 0.0); Assert.assertEquals(0.5f, cosine.evaluate(Arrays.asList("a", "b"), Arrays.asList("a", "c")).get(), 0.0); Assert.assertEquals(-1.f, cosine.evaluate(Arrays.asList("a:1.0"), Arrays.asList("a:-1.0")).get(), 0.0); Assert.assertTrue(cosine.evaluate(Arrays.asList("apple", "orange"), Arrays.asList("banana", "apple")).get() > 0.f); Assert.assertTrue(cosine.evaluate(Arrays.asList("apple", "orange"), Arrays.asList("banana", "apple")).get() > 0.f); Assert.assertTrue((cosine.evaluate(Arrays.asList("apple", "orange"), Arrays.asList("banana", "orange", "apple"))).get() > (cosine.evaluate(Arrays.asList("apple", "orange"), Arrays.asList("banana", "orange"))).get()); Assert.assertEquals(1.0f, cosine.evaluate(Arrays.asList("This is a sentence with seven tokens".split(" ")), Arrays.<String> asList("This is a sentence with seven tokens".split(" "))).get(), 0.0); Assert.assertEquals(1.0f, cosine.evaluate(Arrays.asList("This is a sentence with seven tokens".split(" ")), Arrays.<String> asList("This is a sentence with seven tokens".split(" "))).get(), 0.0); { List<String> tokens1 = Arrays.asList("1:1,2:1,3:1,4:1,5:0,6:1,7:1,8:1,9:0,10:1,11:1".split(",")); List<String> tokens2 = Arrays.asList("1:1,2:1,3:0,4:1,5:1,6:1,7:1,8:0,9:1,10:1,11:1".split(",")); Assert.assertEquals(0.77777f, cosine.evaluate(tokens1, tokens2).get(), 0.00001f); } { List<String> tokens1 = Arrays.asList("1 2 3 4 6 7 8 10 11".split("\\s+")); List<String> tokens2 = Arrays.asList("1 2 4 5 6 7 9 10 11".split("\\s+")); double dotp = 1 + 1 + 0 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1; double norm = Math.sqrt(tokens1.size()) * Math.sqrt(tokens2.size()); Assert.assertEquals(dotp / norm, cosine.evaluate(tokens1, tokens2).get(), 0.00001f); Assert.assertEquals(dotp / norm, cosine.evaluate(tokens1, tokens2).get(), 0.00001f); Assert.assertEquals(dotp / norm, cosine.evaluate(Arrays.asList("1", "2", "3", "4", "6", "7", "8", "10", "11"), Arrays.asList("1", "2", "4", "5", "6", "7", "9", "10", "11")).get(), 0.00001f); } Assert.assertEquals(0.f, cosine.evaluate(Arrays.asList("1", "2", "3"), Arrays.asList("4", "5")).get(), 0.0); Assert.assertEquals(1.f, cosine.evaluate(Arrays.asList("1", "2"), Arrays.asList("1", "2")).get(), 0.0); cosine.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEvaluate() { CosineSimilarityUDF cosine = new CosineSimilarityUDF(); { List<String> ftvec1 = Arrays.asList("bbb:1.4", "aaa:0.9", "ccc"); Assert.assertEquals(1.f, cosine.evaluate(ftvec1, ftvec1).get(), 0.0); } Assert.assertEquals(0.f, cosine.evaluate(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e")).get(), 0.0); Assert.assertEquals(0.f, cosine.evaluate(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e")).get(), 0.0); Assert.assertEquals(1.f, cosine.evaluate(Arrays.asList("a", "b"), Arrays.asList("a", "b")).get(), 0.0); Assert.assertEquals(0.5f, cosine.evaluate(Arrays.asList("a", "b"), Arrays.asList("a", "c")).get(), 0.0); Assert.assertEquals(-1.f, cosine.evaluate(Arrays.asList("a:1.0"), Arrays.asList("a:-1.0")).get(), 0.0); Assert.assertTrue(cosine.evaluate(Arrays.asList("apple", "orange"), Arrays.asList("banana", "apple")).get() > 0.f); Assert.assertTrue(cosine.evaluate(Arrays.asList("apple", "orange"), Arrays.asList("banana", "apple")).get() > 0.f); Assert.assertTrue((cosine.evaluate(Arrays.asList("apple", "orange"), Arrays.asList("banana", "orange", "apple"))).get() > (cosine.evaluate(Arrays.asList("apple", "orange"), Arrays.asList("banana", "orange"))).get()); Assert.assertEquals(1.0f, cosine.evaluate(Arrays.asList("This is a sentence with seven tokens".split(" ")), Arrays.<String> asList("This is a sentence with seven tokens".split(" "))).get(), 0.0); Assert.assertEquals(1.0f, cosine.evaluate(Arrays.asList("This is a sentence with seven tokens".split(" ")), Arrays.<String> asList("This is a sentence with seven tokens".split(" "))).get(), 0.0); { List<String> tokens1 = Arrays.asList("1:1,2:1,3:1,4:1,5:0,6:1,7:1,8:1,9:0,10:1,11:1".split(",")); List<String> tokens2 = Arrays.asList("1:1,2:1,3:0,4:1,5:1,6:1,7:1,8:0,9:1,10:1,11:1".split(",")); Assert.assertEquals(0.77777f, cosine.evaluate(tokens1, tokens2).get(), 0.00001f); } { List<String> tokens1 = Arrays.asList("1 2 3 4 6 7 8 10 11".split("\\s+")); List<String> tokens2 = Arrays.asList("1 2 4 5 6 7 9 10 11".split("\\s+")); double dotp = 1 + 1 + 0 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1; double norm = Math.sqrt(tokens1.size()) * Math.sqrt(tokens2.size()); Assert.assertEquals(dotp / norm, cosine.evaluate(tokens1, tokens2).get(), 0.00001f); Assert.assertEquals(dotp / norm, cosine.evaluate(tokens1, tokens2).get(), 0.00001f); Assert.assertEquals(dotp / norm, cosine.evaluate(Arrays.asList("1", "2", "3", "4", "6", "7", "8", "10", "11"), Arrays.asList("1", "2", "4", "5", "6", "7", "9", "10", "11")).get(), 0.00001f); } Assert.assertEquals(0.f, cosine.evaluate(Arrays.asList("1", "2", "3"), Arrays.asList("4", "5")).get(), 0.0); Assert.assertEquals(1.f, cosine.evaluate(Arrays.asList("1", "2"), Arrays.asList("1", "2")).get(), 0.0); } #location 45 #vulnerability type RESOURCE_LEAK
#fixed code public static Node deserializeNode(final byte[] serializedObj, final int length, final boolean compressed) throws HiveException { final Node root = new Node(); try { if (compressed) { ObjectUtils.readCompressedObject(serializedObj, 0, length, root); } else { ObjectUtils.readObject(serializedObj, length, root); } } catch (IOException ioe) { throw new HiveException("IOException cause while deserializing DecisionTree object", ioe); } catch (Exception e) { throw new HiveException("Exception cause while deserializing DecisionTree object", e); } return root; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Node deserializeNode(final byte[] serializedObj, final int length, final boolean compressed) throws HiveException { FastByteArrayInputStream bis = new FastByteArrayInputStream(serializedObj, length); InputStream wrapped = compressed ? new InflaterInputStream(bis) : bis; final Node root; ObjectInputStream ois = null; try { ois = new ObjectInputStream(wrapped); root = new Node(); root.readExternal(ois); } catch (IOException ioe) { throw new HiveException("IOException cause while deserializing DecisionTree object", ioe); } catch (Exception e) { throw new HiveException("Exception cause while deserializing DecisionTree object", e); } finally { IOUtils.closeQuietly(ois); } return root; } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public static Node deserializeNode(final byte[] serializedObj, final int length, final boolean compressed) throws HiveException { final Node root = new Node(); try { if (compressed) { ObjectUtils.readCompressedObject(serializedObj, 0, length, root); } else { ObjectUtils.readObject(serializedObj, length, root); } } catch (IOException ioe) { throw new HiveException("IOException cause while deserializing DecisionTree object", ioe); } catch (Exception e) { throw new HiveException("Exception cause while deserializing DecisionTree object", e); } return root; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Node deserializeNode(final byte[] serializedObj, final int length, final boolean compressed) throws HiveException { FastByteArrayInputStream bis = new FastByteArrayInputStream(serializedObj, length); InputStream wrapped = compressed ? new InflaterInputStream(bis) : bis; final Node root; ObjectInputStream ois = null; try { ois = new ObjectInputStream(wrapped); root = new Node(); root.readExternal(ois); } catch (IOException ioe) { throw new HiveException("IOException cause while deserializing DecisionTree object", ioe); } catch (Exception e) { throw new HiveException("Exception cause while deserializing DecisionTree object", e); } finally { IOUtils.closeQuietly(ois); } return root; } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void test1() { List<String> ftvec1 = Arrays.asList("1:1.0", "2:2.0", "3:3.0"); List<String> ftvec2 = Arrays.asList("1:2.0", "2:4.0", "3:6.0"); double d = EuclidDistanceUDF.euclidDistance(ftvec1, ftvec2); Assert.assertEquals(Math.sqrt(1.0 + 4.0 + 9.0), d, 0.f); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test1() { EuclidDistanceUDF udf = new EuclidDistanceUDF(); List<String> ftvec1 = Arrays.asList("1:1.0", "2:2.0", "3:3.0"); List<String> ftvec2 = Arrays.asList("1:2.0", "2:4.0", "3:6.0"); FloatWritable d = udf.evaluate(ftvec1, ftvec2); Assert.assertEquals((float) Math.sqrt(1.0 + 4.0 + 9.0), d.get(), 0.f); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code private static void loadValues(OpenHashMap<Object, Object> map, File file, PrimitiveObjectInspector keyOI, PrimitiveObjectInspector valueOI) throws IOException, SerDeException { if(!file.exists()) { return; } if(!file.getName().endsWith(".crc")) { if(file.isDirectory()) { for(File f : file.listFiles()) { loadValues(map, f, keyOI, valueOI); } } else { LazySimpleSerDe serde = HiveUtils.getKeyValueLineSerde(keyOI, valueOI); StructObjectInspector lineOI = (StructObjectInspector) serde.getObjectInspector(); StructField keyRef = lineOI.getStructFieldRef("key"); StructField valueRef = lineOI.getStructFieldRef("value"); PrimitiveObjectInspector keyRefOI = (PrimitiveObjectInspector) keyRef.getFieldObjectInspector(); PrimitiveObjectInspector valueRefOI = (PrimitiveObjectInspector) valueRef.getFieldObjectInspector(); BufferedReader reader = null; try { reader = HadoopUtils.getBufferedReader(file); String line; while((line = reader.readLine()) != null) { Text lineText = new Text(line); Object lineObj = serde.deserialize(lineText); List<Object> fields = lineOI.getStructFieldsDataAsList(lineObj); Object f0 = fields.get(0); Object f1 = fields.get(1); Object k = keyRefOI.getPrimitiveJavaObject(f0); Object v = valueRefOI.getPrimitiveWritableObject(valueRefOI.copyObject(f1)); map.put(k, v); } } finally { IOUtils.closeQuietly(reader); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void loadValues(OpenHashMap<Object, Object> map, File file, PrimitiveObjectInspector keyOI, PrimitiveObjectInspector valueOI) throws IOException, SerDeException { if(!file.exists()) { return; } if(!file.getName().endsWith(".crc")) { if(file.isDirectory()) { for(File f : file.listFiles()) { loadValues(map, f, keyOI, valueOI); } } else { LazySimpleSerDe serde = HiveUtils.getKeyValueLineSerde(keyOI, valueOI); StructObjectInspector lineOI = (StructObjectInspector) serde.getObjectInspector(); StructField keyRef = lineOI.getStructFieldRef("key"); StructField valueRef = lineOI.getStructFieldRef("value"); PrimitiveObjectInspector keyRefOI = (PrimitiveObjectInspector) keyRef.getFieldObjectInspector(); PrimitiveObjectInspector valueRefOI = (PrimitiveObjectInspector) valueRef.getFieldObjectInspector(); final BufferedReader reader = HadoopUtils.getBufferedReader(file); try { String line; while((line = reader.readLine()) != null) { Text lineText = new Text(line); Object lineObj = serde.deserialize(lineText); List<Object> fields = lineOI.getStructFieldsDataAsList(lineObj); Object f0 = fields.get(0); Object f1 = fields.get(1); Object k = keyRefOI.getPrimitiveJavaObject(f0); Object v = valueRefOI.getPrimitiveWritableObject(valueRefOI.copyObject(f1)); map.put(k, v); } } finally { reader.close(); } } } } #location 33 #vulnerability type RESOURCE_LEAK
#fixed code @Nonnull public byte[] predictSerCodegen(boolean compress) throws HiveException { try { if (compress) { return ObjectUtils.toCompressedBytes(_root); } else { return ObjectUtils.toBytes(_root); } } catch (IOException ioe) { throw new HiveException("IOException cause while serializing DecisionTree object", ioe); } catch (Exception e) { throw new HiveException("Exception cause while serializing DecisionTree object", e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Nonnull public byte[] predictSerCodegen(boolean compress) throws HiveException { FastMultiByteArrayOutputStream bos = new FastMultiByteArrayOutputStream(); OutputStream wrapped = compress ? new DeflaterOutputStream(bos) : bos; ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(wrapped); _root.writeExternal(oos); oos.flush(); } catch (IOException ioe) { throw new HiveException("IOException cause while serializing DecisionTree object", ioe); } catch (Exception e) { throw new HiveException("Exception cause while serializing DecisionTree object", e); } finally { IOUtils.closeQuietly(oos); } return bos.toByteArray_clear(); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code public Class<? extends Deserializer> getDeserializerClass(final String jarName, final String classpath) throws LoaderException { try { final String absolutePath = getPathForJar(jarName).toString(); final URL jarUrl = new URL("file://" + absolutePath); final ClassLoader pluginClassLoader = new PluginClassLoader(jarUrl); return getDeserializerClass(pluginClassLoader, classpath); } catch (MalformedURLException exception) { throw new LoaderException("Unable to load jar " + jarName, exception); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Class<? extends Deserializer> getDeserializerClass(final String jarName, final String classpath) throws LoaderException { try { final String absolutePath = getPathForJar(jarName).toString(); final URL jarUrl = new URL("file://" + absolutePath); final ClassLoader pluginClassLoader = new PluginClassLoader(jarUrl); final Class loadedClass = pluginClassLoader.loadClass(classpath); if (!Deserializer.class.isAssignableFrom(loadedClass)) { throw new WrongImplementationException("Class does not implement " + Deserializer.class.getName(), null); } return loadedClass; } catch (MalformedURLException exception) { throw new LoaderException("Unable to load jar " + jarName, exception); } catch (ClassNotFoundException exception) { throw new UnableToFindClassException("Unable to find class " + classpath + " in jar " + jarName, exception); } } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code public void drawTitle(String title, PDFont font, int fontSize, TextType textType) throws IOException { PDPageContentStream articleTitle = createPdPageContentStream(); articleTitle.beginText(); articleTitle.setFont(font, fontSize); articleTitle.moveTextPositionByAmount(getMargin(), yStart); articleTitle.setNonStrokingColor(Color.black); articleTitle.drawString(title); articleTitle.endText(); if (textType != null) { switch (textType) { case HIGHLIGHT: throw new NotImplementedException(); case SQUIGGLY: throw new NotImplementedException(); case STRIKEOUT: throw new NotImplementedException(); case UNDERLINE: float y = (float) (yStart - 1.5); float titleWidth = font.getStringWidth(title) / 1000 * fontSize; articleTitle.drawLine(getMargin(), y, getMargin() + titleWidth, y); break; default: break; } } articleTitle.close(); yStart = (float) (yStart - (fontSize / 1.5)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void drawTitle(String title, PDFont font, int fontSize, TextType textType) throws IOException { PDPageContentStream articleTitle = new PDPageContentStream(this.document, this.currentPage, true, true); articleTitle.beginText(); articleTitle.setFont(font, fontSize); articleTitle.moveTextPositionByAmount(getMargin(), yStart); articleTitle.setNonStrokingColor(Color.black); articleTitle.drawString(title); articleTitle.endText(); if (textType != null) { switch (textType) { case HIGHLIGHT: throw new NotImplementedException(); case SQUIGGLY: throw new NotImplementedException(); case STRIKEOUT: throw new NotImplementedException(); case UNDERLINE: float y = (float) (yStart - 1.5); float titleWidth = font.getStringWidth(title) / 1000 * fontSize; articleTitle.drawLine(getMargin(), y, getMargin() + titleWidth, y); break; default: break; } } articleTitle.close(); yStart = (float) (yStart - (fontSize / 1.5)); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void Sample1 () throws IOException, COSVisitorException { //Set margins float margin = 10; List<String[]> facts = getFacts(); //Initialize Document PDDocument doc = new PDDocument(); PDPage page = addNewPage(doc); float yStartNewPage = page.findMediaBox().getHeight() - (2 * margin); //Initialize table float tableWidth = page.findMediaBox().getWidth() - (2 * margin); boolean drawContent = false; float yStart = yStartNewPage; float bottomMargin = 70; BaseTable table = new BaseTable(yStart,yStartNewPage, bottomMargin, tableWidth, margin, doc, page, true, drawContent); //Create Header row Row headerRow = table.createRow(15f); Cell cell = headerRow.createCell(100, "Awesome Facts About Belgium"); cell.setFont(PDType1Font.HELVETICA_BOLD); cell.setFillColor(Color.BLACK); cell.setTextColor(Color.WHITE); table.setHeader(headerRow); //Create 2 column row Row row = table.createRow(15f); cell = row.createCell(30,"Source:"); cell.setFont(PDType1Font.HELVETICA); cell = row.createCell(70, "http://www.factsofbelgium.com/"); cell.setFont(PDType1Font.HELVETICA_OBLIQUE); //Create Fact header row Row factHeaderrow = table.createRow(15f); cell = factHeaderrow.createCell((100 / 3) * 2, "Fact"); cell.setFont(PDType1Font.HELVETICA); cell.setFontSize(6); cell.setFillColor(Color.LIGHT_GRAY); cell = factHeaderrow.createCell((100 / 3), "Tags"); cell.setFillColor(Color.LIGHT_GRAY); cell.setFont(PDType1Font.HELVETICA_OBLIQUE); cell.setFontSize(6); //Add multiple rows with random facts about Belgium for (String[] fact : facts) { row = table.createRow(10f); cell = row.createCell((100 / 3) * 2, fact[0]); cell.setFont(PDType1Font.HELVETICA); cell.setFontSize(6); for (int i = 1; i < fact.length; i++) { cell = row.createCell((100 / 9), fact[i]); cell.setFont(PDType1Font.HELVETICA_OBLIQUE); cell.setFontSize(6); //Set colors if (fact[i].contains("beer")) cell.setFillColor(Color.yellow); if (fact[i].contains("champion")) cell.setTextColor(Color.GREEN); } } table.draw(); //Close Stream and save pdf File file = new File("target/BoxableSample1.pdf"); Files.createParentDirs(file); doc.save(file); doc.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void Sample1 () throws IOException, COSVisitorException { //Set margins float margin = 10; List<String[]> facts = getFacts(); //Initialize Document PDDocument doc = new PDDocument(); PDPage page = addNewPage(doc); float top = page.findMediaBox().getHeight() - (2 * margin); //Initialize table float tableWidth = page.findMediaBox().getWidth() - (2 * margin); boolean drawContent = false; Table table = new Table(top,tableWidth, margin, doc, page, true, drawContent); //Create Header row Row headerRow = table.createRow(15f); Cell cell = headerRow.createCell(100, "Awesome Facts About Belgium"); cell.setFont(PDType1Font.HELVETICA_BOLD); cell.setFillColor(Color.BLACK); cell.setTextColor(Color.WHITE); table.setHeader(headerRow); //Create 2 column row Row row = table.createRow(15f); cell = row.createCell(30,"Source:"); cell.setFont(PDType1Font.HELVETICA); cell = row.createCell(70, "http://www.factsofbelgium.com/"); cell.setFont(PDType1Font.HELVETICA_OBLIQUE); //Create Fact header row Row factHeaderrow = table.createRow(15f); cell = factHeaderrow.createCell((100 / 3) * 2, "Fact"); cell.setFont(PDType1Font.HELVETICA); cell.setFontSize(6); cell.setFillColor(Color.LIGHT_GRAY); cell = factHeaderrow.createCell((100 / 3), "Tags"); cell.setFillColor(Color.LIGHT_GRAY); cell.setFont(PDType1Font.HELVETICA_OBLIQUE); cell.setFontSize(6); //Add multiple rows with random facts about Belgium for (String[] fact : facts) { row = table.createRow(10f); cell = row.createCell((100 / 3) * 2, fact[0]); cell.setFont(PDType1Font.HELVETICA); cell.setFontSize(6); for (int i = 1; i < fact.length; i++) { cell = row.createCell((100 / 9), fact[i]); cell.setFont(PDType1Font.HELVETICA_OBLIQUE); cell.setFontSize(6); //Set colors if (fact[i].contains("beer")) cell.setFillColor(Color.yellow); if (fact[i].contains("champion")) cell.setTextColor(Color.GREEN); } } table.draw(); //Close Stream and save pdf File file = new File("target/BoxableSample1.pdf"); Files.createParentDirs(file); doc.save(file); doc.close(); } #location 67 #vulnerability type RESOURCE_LEAK
#fixed code public void drawTitle(String title, PDFont font, int fontSize, TextType textType) throws IOException { PDPageContentStream articleTitle = createPdPageContentStream(); articleTitle.beginText(); articleTitle.setFont(font, fontSize); articleTitle.moveTextPositionByAmount(getMargin(), yStart); articleTitle.setNonStrokingColor(Color.black); articleTitle.drawString(title); articleTitle.endText(); if (textType != null) { switch (textType) { case HIGHLIGHT: throw new NotImplementedException(); case SQUIGGLY: throw new NotImplementedException(); case STRIKEOUT: throw new NotImplementedException(); case UNDERLINE: float y = (float) (yStart - 1.5); float titleWidth = font.getStringWidth(title) / 1000 * fontSize; articleTitle.drawLine(getMargin(), y, getMargin() + titleWidth, y); break; default: break; } } articleTitle.close(); yStart = (float) (yStart - (fontSize / 1.5)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void drawTitle(String title, PDFont font, int fontSize, TextType textType) throws IOException { PDPageContentStream articleTitle = new PDPageContentStream(this.document, this.currentPage, true, true); articleTitle.beginText(); articleTitle.setFont(font, fontSize); articleTitle.moveTextPositionByAmount(getMargin(), yStart); articleTitle.setNonStrokingColor(Color.black); articleTitle.drawString(title); articleTitle.endText(); if (textType != null) { switch (textType) { case HIGHLIGHT: throw new NotImplementedException(); case SQUIGGLY: throw new NotImplementedException(); case STRIKEOUT: throw new NotImplementedException(); case UNDERLINE: float y = (float) (yStart - 1.5); float titleWidth = font.getStringWidth(title) / 1000 * fontSize; articleTitle.drawLine(getMargin(), y, getMargin() + titleWidth, y); break; default: break; } } articleTitle.close(); yStart = (float) (yStart - (fontSize / 1.5)); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void open(Map stormConf, TopologyContext context, SpoutOutputCollector collector) { partitionField = ConfUtils.getString(stormConf, ESStatusRoutingFieldParamName); bucketSortField = ConfUtils.getString(stormConf, ESStatusBucketSortFieldParamName, bucketSortField); totalSortField = ConfUtils.getString(stormConf, ESStatusGlobalSortFieldParamName); maxURLsPerBucket = ConfUtils.getInt(stormConf, ESStatusMaxURLsParamName, 1); maxBucketNum = ConfUtils.getInt(stormConf, ESStatusMaxBucketParamName, 10); minDelayBetweenQueries = ConfUtils.getLong(stormConf, ESStatusMinDelayParamName, 2000); super.open(stormConf, context, collector); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void open(Map stormConf, TopologyContext context, SpoutOutputCollector collector) { indexName = ConfUtils.getString(stormConf, ESStatusIndexNameParamName, "status"); docType = ConfUtils.getString(stormConf, ESStatusDocTypeParamName, "status"); partitionField = ConfUtils.getString(stormConf, ESStatusRoutingFieldParamName); bucketSortField = ConfUtils.getString(stormConf, ESStatusBucketSortFieldParamName, bucketSortField); totalSortField = ConfUtils.getString(stormConf, ESStatusGlobalSortFieldParamName); maxURLsPerBucket = ConfUtils.getInt(stormConf, ESStatusMaxURLsParamName, 1); maxBucketNum = ConfUtils.getInt(stormConf, ESStatusMaxBucketParamName, 10); minDelayBetweenQueries = ConfUtils.getLong(stormConf, ESStatusMinDelayParamName, 2000); // one ES client per JVM synchronized (AggregationSpout.class) { try { if (client == null) { client = ElasticSearchConnection.getClient(stormConf, ESBoltType); } } catch (Exception e1) { LOG.error("Can't connect to ElasticSearch", e1); throw new RuntimeException(e1); } } // if more than one instance is used we expect their number to be the // same as the number of shards int totalTasks = context .getComponentTasks(context.getThisComponentId()).size(); if (totalTasks > 1) { logIdprefix = "[" + context.getThisComponentId() + " #" + context.getThisTaskIndex() + "] "; // determine the number of shards so that we can restrict the // search ClusterSearchShardsRequest request = new ClusterSearchShardsRequest( indexName); ClusterSearchShardsResponse shardresponse = client.admin() .cluster().searchShards(request).actionGet(); ClusterSearchShardsGroup[] shardgroups = shardresponse.getGroups(); if (totalTasks != shardgroups.length) { throw new RuntimeException( "Number of ES spout instances should be the same as number of shards (" + shardgroups.length + ") but is " + totalTasks); } shardID = shardgroups[context.getThisTaskIndex()].getShardId(); LOG.info("{} assigned shard ID {}", logIdprefix, shardID); } _collector = collector; this.eventCounter = context.registerMetric("counters", new MultiCountMetric(), 10); context.registerMetric("buffer_size", new IMetric() { @Override public Object getValueAndReset() { return buffer.size(); } }, 10); } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void execute(Tuple input) { // triggered by the arrival of a tuple // be it a tick or normal one flushQueues(); if (isTickTuple(input)) { _collector.ack(input); return; } CountMetric metric = metricGauge.scope("activethreads"); metric.getValueAndReset(); metric.incrBy(this.activeThreads.get()); metric = metricGauge.scope("in queues"); metric.getValueAndReset(); metric.incrBy(this.fetchQueues.inQueues.get()); metric = metricGauge.scope("queues"); metric.getValueAndReset(); metric.incrBy(this.fetchQueues.queues.size()); LOG.info("[Fetcher #" + taskIndex + "] Threads : " + this.activeThreads.get() + "\tqueues : " + this.fetchQueues.queues.size() + "\tin_queues : " + this.fetchQueues.inQueues.get()); String url = input.getStringByField("url"); // check whether this tuple has a url field if (url == null) { LOG.info("[Fetcher #" + taskIndex + "] Missing url field for tuple " + input); // ignore silently _collector.ack(input); return; } fetchQueues.addFetchItem(input); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void execute(Tuple input) { // main thread in charge of acking and failing // see // https://github.com/nathanmarz/storm/wiki/Troubleshooting#nullpointerexception-from-deep-inside-storm int acked = 0; int failed = 0; int emitted = 0; // emit with or without anchors // before acking synchronized (emitQueue) { for (Object[] toemit : this.emitQueue) { String streamID = (String) toemit[0]; Tuple anchor = (Tuple) toemit[1]; Values vals = (Values) toemit[2]; if (anchor == null) _collector.emit(streamID, vals); else _collector.emit(streamID, Arrays.asList(anchor), vals); } emitted = emitQueue.size(); emitQueue.clear(); } // have a tick tuple to make sure we don't get starved synchronized (ackQueue) { for (Tuple toack : this.ackQueue) { _collector.ack(toack); } acked = ackQueue.size(); ackQueue.clear(); } synchronized (failQueue) { for (Tuple toack : this.failQueue) { _collector.fail(toack); } failed = failQueue.size(); failQueue.clear(); } if (acked + failed + emitted > 0) LOG.info("[Fetcher #" + taskIndex + "] Acked : " + acked + "\tFailed : " + failed + "\tEmitted : " + emitted); if (isTickTuple(input)) { _collector.ack(input); return; } CountMetric metric = metricGauge.scope("activethreads"); metric.getValueAndReset(); metric.incrBy(this.activeThreads.get()); metric = metricGauge.scope("in queues"); metric.getValueAndReset(); metric.incrBy(this.fetchQueues.inQueues.get()); metric = metricGauge.scope("queues"); metric.getValueAndReset(); metric.incrBy(this.fetchQueues.queues.size()); LOG.info("[Fetcher #" + taskIndex + "] Threads : " + this.activeThreads.get() + "\tqueues : " + this.fetchQueues.queues.size() + "\tin_queues : " + this.fetchQueues.inQueues.get()); String url = input.getStringByField("url"); // check whether this tuple has a url field if (url == null) { LOG.info("[Fetcher #" + taskIndex + "] Missing url field for tuple " + input); // ignore silently _collector.ack(input); return; } fetchQueues.addFetchItem(input); } #location 50 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void onResponse(SearchResponse response) { long timeTaken = System.currentTimeMillis() - timeStartESQuery; SearchHit[] hits = response.getHits().getHits(); int numBuckets = hits.length; // reset the value for next fetch date if the previous one is too old if (resetFetchDateAfterNSecs != -1) { Calendar diffCal = Calendar.getInstance(); diffCal.setTime(lastDate); diffCal.add(Calendar.SECOND, resetFetchDateAfterNSecs); // compare to now if (diffCal.before(Calendar.getInstance())) { LOG.info( "{} lastDate set to null based on resetFetchDateAfterNSecs {}", logIdprefix, resetFetchDateAfterNSecs); lastDate = null; lastStartOffset = 0; } } int alreadyprocessed = 0; int numDocs = 0; synchronized (buffer) { for (SearchHit hit : hits) { Map<String, SearchHits> innerHits = hit.getInnerHits(); // wanted just one per bucket : no inner hits if (innerHits == null) { numDocs++; if (!addHitToBuffer(hit)) { alreadyprocessed++; } continue; } // more than one per bucket SearchHits inMyBucket = innerHits.get("urls_per_bucket"); for (SearchHit subHit : inMyBucket.getHits()) { numDocs++; if (!addHitToBuffer(subHit)) { alreadyprocessed++; } } } // Shuffle the URLs so that we don't get blocks of URLs from the // same host or domain if (numBuckets != numDocs) { Collections.shuffle((List) buffer); } } esQueryTimes.addMeasurement(timeTaken); // could be derived from the count of query times above eventCounter.scope("ES_queries").incrBy(1); eventCounter.scope("ES_docs").incrBy(numDocs); eventCounter.scope("already_being_processed").incrBy(alreadyprocessed); LOG.info( "{} ES query returned {} hits from {} buckets in {} msec with {} already being processed", logIdprefix, numDocs, numBuckets, timeTaken, alreadyprocessed); // no more results? if (numBuckets == 0) { lastDate = null; lastStartOffset = 0; } // still got some results but paging won't help else if (numBuckets < maxBucketNum) { lastStartOffset = 0; } else { lastStartOffset += numBuckets; } // remove lock isInESQuery.set(false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onResponse(SearchResponse response) { long timeTaken = System.currentTimeMillis() - timeStartESQuery; SearchHit[] hits = response.getHits().getHits(); int numBuckets = hits.length; // no more results? if (numBuckets == 0) { lastDate = null; lastStartOffset = 0; } // still got some results but paging won't help else if (numBuckets < maxBucketNum) { lastStartOffset = 0; } else { lastStartOffset += numBuckets; } // reset the value for next fetch date if the previous one is too old if (resetFetchDateAfterNSecs != -1) { Calendar diffCal = Calendar.getInstance(); diffCal.setTime(lastDate); diffCal.add(Calendar.SECOND, resetFetchDateAfterNSecs); // compare to now if (diffCal.before(Calendar.getInstance())) { LOG.info( "{} lastDate set to null based on resetFetchDateAfterNSecs {}", logIdprefix, resetFetchDateAfterNSecs); lastDate = null; lastStartOffset = 0; } } int alreadyprocessed = 0; int numDocs = 0; synchronized (buffer) { for (SearchHit hit : hits) { Map<String, SearchHits> innerHits = hit.getInnerHits(); // wanted just one per bucket : no inner hits if (innerHits == null) { numDocs++; if (!addHitToBuffer(hit)) { alreadyprocessed++; } continue; } // more than one per bucket SearchHits inMyBucket = innerHits.get("urls_per_bucket"); for (SearchHit subHit : inMyBucket.getHits()) { numDocs++; if (!addHitToBuffer(subHit)) { alreadyprocessed++; } } } // Shuffle the URLs so that we don't get blocks of URLs from the // same host or domain if (numBuckets != numDocs) { Collections.shuffle((List) buffer); } } esQueryTimes.addMeasurement(timeTaken); // could be derived from the count of query times above eventCounter.scope("ES_queries").incrBy(1); eventCounter.scope("ES_docs").incrBy(numDocs); eventCounter.scope("already_being_processed").incrBy(alreadyprocessed); LOG.info( "{} ES query returned {} hits from {} buckets in {} msec with {} already being processed", logIdprefix, numDocs, numBuckets, timeTaken, alreadyprocessed); // remove lock isInESQuery.set(false); } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void open(Map stormConf, TopologyContext context, SpoutOutputCollector collector) { partitionField = ConfUtils.getString(stormConf, ESStatusRoutingFieldParamName); bucketSortField = ConfUtils.getString(stormConf, ESStatusBucketSortFieldParamName, bucketSortField); totalSortField = ConfUtils.getString(stormConf, ESStatusGlobalSortFieldParamName); maxURLsPerBucket = ConfUtils.getInt(stormConf, ESStatusMaxURLsParamName, 1); maxBucketNum = ConfUtils.getInt(stormConf, ESStatusMaxBucketParamName, 10); minDelayBetweenQueries = ConfUtils.getLong(stormConf, ESStatusMinDelayParamName, 2000); super.open(stormConf, context, collector); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void open(Map stormConf, TopologyContext context, SpoutOutputCollector collector) { indexName = ConfUtils.getString(stormConf, ESStatusIndexNameParamName, "status"); docType = ConfUtils.getString(stormConf, ESStatusDocTypeParamName, "status"); partitionField = ConfUtils.getString(stormConf, ESStatusRoutingFieldParamName); bucketSortField = ConfUtils.getString(stormConf, ESStatusBucketSortFieldParamName, bucketSortField); totalSortField = ConfUtils.getString(stormConf, ESStatusGlobalSortFieldParamName); maxURLsPerBucket = ConfUtils.getInt(stormConf, ESStatusMaxURLsParamName, 1); maxBucketNum = ConfUtils.getInt(stormConf, ESStatusMaxBucketParamName, 10); minDelayBetweenQueries = ConfUtils.getLong(stormConf, ESStatusMinDelayParamName, 2000); // one ES client per JVM synchronized (AggregationSpout.class) { try { if (client == null) { client = ElasticSearchConnection.getClient(stormConf, ESBoltType); } } catch (Exception e1) { LOG.error("Can't connect to ElasticSearch", e1); throw new RuntimeException(e1); } } // if more than one instance is used we expect their number to be the // same as the number of shards int totalTasks = context .getComponentTasks(context.getThisComponentId()).size(); if (totalTasks > 1) { logIdprefix = "[" + context.getThisComponentId() + " #" + context.getThisTaskIndex() + "] "; // determine the number of shards so that we can restrict the // search ClusterSearchShardsRequest request = new ClusterSearchShardsRequest( indexName); ClusterSearchShardsResponse shardresponse = client.admin() .cluster().searchShards(request).actionGet(); ClusterSearchShardsGroup[] shardgroups = shardresponse.getGroups(); if (totalTasks != shardgroups.length) { throw new RuntimeException( "Number of ES spout instances should be the same as number of shards (" + shardgroups.length + ") but is " + totalTasks); } shardID = shardgroups[context.getThisTaskIndex()].getShardId(); LOG.info("{} assigned shard ID {}", logIdprefix, shardID); } _collector = collector; this.eventCounter = context.registerMetric("counters", new MultiCountMetric(), 10); context.registerMetric("buffer_size", new IMetric() { @Override public Object getValueAndReset() { return buffer.size(); } }, 10); } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void parseXml_uri() { Result<Attachment> result = parseXCalProperty("<uri>http://example.com/image.png</uri>", marshaller); Attachment prop = result.getValue(); assertEquals("http://example.com/image.png", prop.getUri()); assertNull(prop.getData()); assertWarnings(0, result.getWarnings()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void parseXml_uri() { ICalParameters params = new ICalParameters(); Element element = xcalPropertyElement(marshaller, "<uri>http://example.com/image.png</uri>"); Result<Attachment> result = marshaller.parseXml(element, params); Attachment prop = result.getValue(); assertEquals("http://example.com/image.png", prop.getUri()); assertNull(prop.getData()); assertWarnings(0, result.getWarnings()); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void escape_newlines() throws Exception { ICalendar ical = new ICalendar(); VEvent event = new VEvent(); event.setSummary("summary\nof event"); ical.addEvent(event); StringWriter sw = new StringWriter(); ICalWriter writer = new ICalWriter(sw); writer.write(ical); writer.close(); //@formatter:off String expected = "BEGIN:VCALENDAR\r\n" + "VERSION:2\\.0\r\n" + "PRODID:.*?\r\n" + "BEGIN:VEVENT\r\n" + "UID:.*?\r\n" + "DTSTAMP:.*?\r\n" + "SUMMARY:summary\\\\nof event\r\n" + "END:VEVENT\r\n" + "END:VCALENDAR\r\n"; //@formatter:on String actual = sw.toString(); assertRegex(expected, actual); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void escape_newlines() throws Exception { ICalendar ical = new ICalendar(); VEvent event = new VEvent(); event.setSummary("summary\nof event"); ical.addEvent(event); StringWriter sw = new StringWriter(); ICalWriter writer = new ICalWriter(sw); writer.write(ical); writer.close(); //@formatter:off String expected = "BEGIN:VCALENDAR\r\n" + "VERSION:2\\.0\r\n" + "PRODID:.*?\r\n" + "BEGIN:VEVENT\r\n" + "UID:.*?\r\n" + "DTSTAMP:.*?\r\n" + "SUMMARY:summary\\\\nof event\r\n" + "END:VEVENT\r\n" + "END:VCALENDAR\r\n"; //@formatter:on String actual = sw.toString(); assertRegex(expected, actual); assertWarnings(0, writer.getWarnings()); } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void writeXml_data() { Attachment prop = new Attachment("image/png", "data".getBytes()); assertWriteXml("<binary>" + Base64.encodeBase64String("data".getBytes()) + "</binary>", prop, marshaller); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void writeXml_data() { Attachment prop = new Attachment("image/png", "data".getBytes()); Document actual = xcalProperty(marshaller); marshaller.writeXml(prop, XmlUtils.getRootElement(actual)); Document expected = xcalProperty(marshaller, "<binary>" + Base64.encodeBase64String("data".getBytes()) + "</binary>"); assertXMLEqual(expected, actual); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public void createInvertedIndex() { if (currentIndex == null) { currentIndex = Index.createIndex(path,prefix); if (currentIndex == null) { logger.error("No index at ("+path+","+prefix+") to build an inverted index for "); return; } } long beginTimestamp = System.currentTimeMillis(); if (currentIndex.getCollectionStatistics().getNumberOfUniqueTerms() == 0) { logger.error("Index has no terms. Inverted index creation aborted."); return; } if (currentIndex.getCollectionStatistics().getNumberOfDocuments() == 0) { logger.error("Index has no documents. Inverted index creation aborted."); return; } logger.info("Started building the block inverted index..."); invertedIndexBuilder = new BlockInvertedIndexBuilder(currentIndex, "inverted", compressionInvertedConfig); invertedIndexBuilder.createInvertedIndex(); this.finishedInvertedIndexBuild(); try{ currentIndex.flush(); } catch (IOException ioe) { logger.error("Cannot flush index: ", ioe); } long endTimestamp = System.currentTimeMillis(); logger.info("Finished building the block inverted index..."); long seconds = (endTimestamp - beginTimestamp) / 1000; logger.info("Time elapsed for inverted file: " + seconds); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void createInvertedIndex() { if (currentIndex == null) { currentIndex = Index.createIndex(path,prefix); if (currentIndex == null) { logger.error("No index at ("+path+","+prefix+") to build an inverted index for "); } } long beginTimestamp = System.currentTimeMillis(); if (currentIndex.getCollectionStatistics().getNumberOfUniqueTerms() == 0) { logger.error("Index has no terms. Inverted index creation aborted."); return; } if (currentIndex.getCollectionStatistics().getNumberOfDocuments() == 0) { logger.error("Index has no documents. Inverted index creation aborted."); return; } logger.info("Started building the block inverted index..."); invertedIndexBuilder = new BlockInvertedIndexBuilder(currentIndex, "inverted", compressionInvertedConfig); invertedIndexBuilder.createInvertedIndex(); this.finishedInvertedIndexBuild(); try{ currentIndex.flush(); } catch (IOException ioe) { logger.error("Cannot flush index: ", ioe); } long endTimestamp = System.currentTimeMillis(); logger.info("Finished building the block inverted index..."); long seconds = (endTimestamp - beginTimestamp) / 1000; logger.info("Time elapsed for inverted file: " + seconds); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test void shouldAutoEnableCaching() { ApplicationContextRunner contextRunner = baseApplicationRunner(); contextRunner.run(context -> { assertThat(context.getBeansOfType(CacheManager.class)).hasSize(1); assertThat(((CacheManager) context.getBean("loadBalancerCacheManager")) .getCacheNames()).hasSize(1); assertThat(context.getBean("loadBalancerCacheManager")) .isInstanceOf(CaffeineCacheManager.class); assertThat(((CacheManager) context.getBean("loadBalancerCacheManager")) .getCacheNames()).contains("CachingServiceInstanceListSupplierCache"); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void shouldAutoEnableCaching() { AnnotationConfigApplicationContext context = setup(""); assertThat(context.getBeansOfType(CacheManager.class)).isNotEmpty(); assertThat(context.getBeansOfType(CacheManager.class).get("cacheManager")) .isNotInstanceOf(NoOpCacheManager.class); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code protected void checkListStatesUpdated() { boolean allListsEnded = true; boolean atLeastOneListSucceeded = false; if (getState().isEstablished()) { return; } List<IceMediaStream> streams = getStreams(); for (IceMediaStream stream : streams) { CheckListState checkListState = stream.getCheckList().getState(); if (checkListState == CheckListState.RUNNING) { allListsEnded = false; break; } else if (checkListState == CheckListState.COMPLETED) { logger.info("CheckList of stream " + stream.getName() + " is COMPLETED"); atLeastOneListSucceeded = true; } } if (!allListsEnded) { return; } if (!atLeastOneListSucceeded) { //all lists ended but none succeeded. No love today ;( if (logger.isLoggable(Level.INFO)) { if (connCheckClient.isAlive() || connCheckServer.isAlive()) { logger.info("Suspicious ICE connectivity failure. Checks" + " failed but the remote end was able to reach us."); } logger.info("ICE state is FAILED"); } terminate(IceProcessingState.FAILED); return; } //Once the state of each check list is Completed: //The agent sets the state of ICE processing overall to Completed. if (getState() != IceProcessingState.RUNNING) { //Oh, seems like we already did this. return; } // The race condition in which another thread enters COMPLETED right // under our nose here has been observed (and not in a single instance) // So check that we did indeed just trigger the change. if (!setState(IceProcessingState.COMPLETED)) { return; } // keep ICE running (answer STUN Binding requests, send STUN Binding // indications or requests) scheduleStunKeepAlive(); scheduleTermination(); //print logs for the types of addresses we chose. logCandTypes(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void checkListStatesUpdated() { boolean allListsEnded = true; boolean atLeastOneListSucceeded = false; if (getState().isEstablished()) { return; } List<IceMediaStream> streams = getStreams(); for (IceMediaStream stream : streams) { CheckListState checkListState = stream.getCheckList().getState(); if (checkListState == CheckListState.RUNNING) { allListsEnded = false; break; } else if (checkListState == CheckListState.COMPLETED) { logger.info("CheckList of stream " + stream.getName() + " is COMPLETED"); atLeastOneListSucceeded = true; } } if (!allListsEnded) { return; } if (!atLeastOneListSucceeded) { //all lists ended but none succeeded. No love today ;( if (logger.isLoggable(Level.INFO)) { if (connCheckClient.isAlive() || connCheckServer.isAlive()) { logger.info("Suspicious ICE connectivity failure. Checks" + " failed but the remote end was able to reach us."); } logger.info("ICE state is FAILED"); } terminate(IceProcessingState.FAILED); return; } //Once the state of each check list is Completed: //The agent sets the state of ICE processing overall to Completed. if (getState() != IceProcessingState.RUNNING) { //Oh, seems like we already did this. return; } // The race condition in which another thread enters COMPLETED right // under our nose here has been observed (and not in a single instance) // So check that we did indeed just trigger the change. if (!setState(IceProcessingState.COMPLETED)) { return; } // keep ICE running (answer STUN Binding requests, send STUN Binding // indications or requests) if (stunKeepAliveThread == null && !StackProperties.getBoolean( StackProperties.NO_KEEP_ALIVES, false)) { // schedule STUN checks for selected candidates scheduleStunKeepAlive(); } scheduleTermination(); //print logs for the types of addresses we chose. logCandTypes(); } #location 79 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); // cancel termination timer in case agent is freed // before termination timer is triggered synchronized (terminationFutureSyncRoot) { if (terminationFuture != null) { terminationFuture.cancel(true); terminationFuture = null; } } //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void free() { logger.fine("Free ICE agent"); shutdown = true; //stop sending keep alives (STUN Binding Indications). if (stunKeepAliveThread != null) stunKeepAliveThread.interrupt(); //stop responding to STUN Binding Requests. connCheckServer.stop(); /* * Set the IceProcessingState#TERMINATED state on this Agent unless it * is in a termination state already. */ IceProcessingState state = getState(); if (!IceProcessingState.FAILED.equals(state) && !IceProcessingState.TERMINATED.equals(state)) { terminate(IceProcessingState.TERMINATED); } // Free its IceMediaStreams, Components and Candidates. boolean interrupted = false; logger.fine("remove streams"); for (IceMediaStream stream : getStreams()) { try { removeStream(stream); logger.fine("remove stream " + stream.getName()); } catch (Throwable t) { logger.fine( "remove stream " + stream.getName() + " failed: " + t); if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (interrupted) Thread.currentThread().interrupt(); getStunStack().shutDown(); logger.fine("ICE agent freed"); } #location 34 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void setIV(byte[] iv, boolean isEncrypt) { if (_ivLength == 0) { return; } CipherParameters cipherParameters = null; if (isEncrypt) { cipherParameters = getCipherParameters(iv); try { encCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } encCipher.init(isEncrypt, cipherParameters); } else { _decryptIV = Arrays.copyOfRange(iv,0,_ivLength); cipherParameters = getCipherParameters(iv); try { decCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } decCipher.init(isEncrypt, cipherParameters); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void setIV(byte[] iv, boolean isEncrypt) { if (_ivLength == 0) { return; } CipherParameters cipherParameters = null; if (isEncrypt) { cipherParameters = getCipherParameters(iv); try { encCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } encCipher.init(isEncrypt, cipherParameters); } else { _decryptIV = new byte[_ivLength]; System.arraycopy(iv, 0, _decryptIV, 0, _ivLength); cipherParameters = getCipherParameters(iv); try { decCipher = getCipher(isEncrypt); } catch (InvalidAlgorithmParameterException e) { logger.info(e.toString()); } decCipher.init(isEncrypt, cipherParameters); } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testSkipNone() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); byte[] actualBytes = new byte[6]; assertEquals(0, b64stream.skip(0)); b64stream.read(actualBytes, 0, actualBytes.length); assertArrayEquals(actualBytes, new byte[] { 0, 0, 0, (byte) 255, (byte) 255, (byte) 255 }); // End of stream reached assertEquals(-1, b64stream.read()); b64stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSkipNone() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); byte[] actualBytes = new byte[6]; assertEquals(0, b64stream.skip(0)); b64stream.read(actualBytes, 0, actualBytes.length); assertArrayEquals(actualBytes, new byte[] { 0, 0, 0, (byte) 255, (byte) 255, (byte) 255 }); // End of stream reached assertEquals(-1, b64stream.read()); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testAvailable() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); assertEquals(1, b32stream.available()); assertEquals(3, b32stream.skip(10)); // End of stream reached assertEquals(0, b32stream.available()); assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); assertEquals(0, b32stream.available()); b32stream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAvailable() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); Base32InputStream b32stream = new Base32InputStream(ins); assertEquals(1, b32stream.available()); assertEquals(3, b32stream.skip(10)); // End of stream reached assertEquals(0, b32stream.available()); assertEquals(-1, b32stream.read()); assertEquals(-1, b32stream.read()); assertEquals(0, b32stream.available()); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public void bind() { bind(false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void bind() { if (bound) throw new IllegalStateException("Already bound to " + assignedThread); bound = true; assignedThread = Thread.currentThread(); AffinitySupport.setAffinity(1L << id); if (LOGGER.isLoggable(Level.INFO)) LOGGER.info("Assigning cpu " + id + " to " + assignedThread); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Object execute(Object ctx, Map tokens) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions. */ switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked // return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens); if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, MVEL.compileExpression(s)); return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { ExpressionParser oParser = new ExpressionParser(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = (ForeachContext) currNode.getRegister(); if (foreachContext.getItererators() == null) { try { String[] lists = getForEachSegment(currNode).split(","); Iterator[] iters = new Iterator[lists.length]; for (int i = 0; i < lists.length; i++) { Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse(); if (listObject instanceof Object[]) { listObject = Arrays.asList((Object[]) listObject); } iters[i] = ((Collection) listObject).iterator(); } foreachContext.setIterators(iters); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split(","); // must trim vars for (int i = 0; i < alias.length; i++) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for (int i = 0; i < iters.length; i++) { tokens.put(alias[i], iters[i].next()); } if (foreachContext.getCount() != 0) { sbuf.append(foreachContext.getSeperator()); } foreachContext.setCount(foreachContext.getCount() + 1); } else { for (int i = 0; i < iters.length; i++) { tokens.remove(alias[i]); } foreachContext.setIterators(null); foreachContext.setCount(0); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length == 2) { return register; } else { return sbuf.toString(); } } case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[node].getRegister(); String template = EX_TEMPLATE_REGISTRY.get(includeRef.getName()); IncludeRefParam[] params = includeRef.getParams(); Map vars = new HashMap(params.length * 2); for (int i = 0; i < params.length; i++) { vars.put(params[i].getIdentifier(), MVEL.eval(params[i].getValue(), ctx, tokens)); } sbuf.append(Interpreter.parse(template, ctx, vars)); } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}", e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object execute(Object ctx, Map tokens) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { switch (nodes[0].getToken()) { case PROPERTY_EX: //noinspection unchecked // return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens); if (!cacheAggressively) { char[] seg = new char[expression.length - 3]; arraycopy(expression, 2, seg, 0, seg.length); return MVEL.eval(seg, ctx, tokens); } else { String s = new String(expression, 2, expression.length - 3); if (!EX_PRECOMP_CACHE.containsKey(s)) { synchronized (EX_PRECOMP_CACHE) { EX_PRECOMP_CACHE.put(s, MVEL.compileExpression(s)); return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } else { return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens); } } case LITERAL: return new String(expression); case INCLUDE_BY_REF: { IncludeRef includeRef = (IncludeRef) nodes[0].getRegister(); String template = EX_TEMPLATE_REGISTRY.get( includeRef.getName() ); IncludeRefParam[] params = includeRef.getParams(); Map vars = new HashMap( params.length ); for ( int i = 0; i < params.length; i++ ) { vars.put( params[i].getIdentifier(), parse(params[i].getValue(), ctx, tokens)); } return Interpreter.parse( template, ctx, vars ); } } return new String(expression); } Object register = null; StringAppender sbuf = new StringAppender(10); Node currNode = null; try { ExpressionParser oParser = new ExpressionParser(ctx, tokens); initStack(); pushAndForward(); while ((currNode = pop()) != null) { node = currNode.getNode(); switch (currNode.getToken()) { case LITERAL: { sbuf.append(register = new String(expression, currNode.getStartPos(), currNode.getEndPos() - currNode.getStartPos())); break; } case PROPERTY_EX: { sbuf.append( valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse()) ); break; } case IF: case ELSEIF: { try { if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) { exitContext(); } } catch (ClassCastException e) { throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode))); } break; } case FOREACH: { ForeachContext foreachContext = ( ForeachContext ) currNode.getRegister(); if ( foreachContext.getItererators() == null ) { try { String[] lists = getForEachSegment(currNode).split( "," ); Iterator[] iters = new Iterator[lists.length]; for( int i = 0; i < lists.length; i++ ) { Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse(); if ( listObject instanceof Object[]) { listObject = Arrays.asList( (Object[]) listObject ); } iters[i] = ((Collection)listObject).iterator() ; } foreachContext.setIterators( iters ); } catch (ClassCastException e) { throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode))); } catch (NullPointerException e) { throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode))); } } Iterator[] iters = foreachContext.getItererators(); String[] alias = currNode.getAlias().split( "," ); // must trim vars for ( int i = 0; i < alias.length; i++ ) { alias[i] = alias[i].trim(); } if (iters[0].hasNext()) { push(); //noinspection unchecked for ( int i = 0; i < iters.length; i++ ) { tokens.put(alias[i], iters[i].next()); } if ( foreachContext.getCount() != 0 ) { sbuf.append( foreachContext.getSeperator() ); } foreachContext.setCount( foreachContext.getCount( ) + 1 ); } else { for ( int i = 0; i < iters.length; i++ ) { tokens.remove(alias[i]); } foreachContext.setIterators( null ); foreachContext.setCount( 0 ); exitContext(); } break; } case ELSE: case END: if (stack.isEmpty()) forwardAndPush(); continue; case GOTO: pushNode(currNode.getEndNode()); continue; case TERMINUS: { if (nodes.length == 2) { return register; } else { return sbuf.toString(); } } } forwardAndPush(); } throw new CompileException("expression did not end properly: expected TERMINUS node"); } catch (CompileException e) { throw e; } catch (Exception e) { if (currNode != null) { throw new CompileException("problem encountered at node [" + currNode.getNode() + "] " + currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}", e); } throw new CompileException("unhandled fatal exception (node:" + node + ")", e); } } #location 39 #vulnerability type THREAD_SAFETY_VIOLATION