output
stringlengths
79
30.1k
instruction
stringclasses
1 value
input
stringlengths
216
28.9k
#fixed code public ClassLoader compile() { // 获得classPath final List<File> classPath = getClassPath(); final URL[] urLs = URLUtil.getURLs(classPath.toArray(new File[0])); final URLClassLoader ucl = URLClassLoader.newInstance(urLs, this.parentClassLoader); if (sourceCodeMap.isEmpty() && sourceFileList.isEmpty()) { // 没有需要编译的源码 return ucl; } // 没有需要编译的源码文件返回加载zip或jar包的类加载器 // 创建编译器 final JavaFileManager javaFileManager = new JavaClassFileManager(ucl, CompilerUtil.getFileManager()); // classpath final List<String> options = new ArrayList<>(); if (false == classPath.isEmpty()) { final List<String> cp = classPath.stream().map(File::getAbsolutePath).collect(Collectors.toList()); options.add("-cp"); options.addAll(cp); } // 编译文件 final DiagnosticCollector<? super JavaFileObject> diagnosticCollector = new DiagnosticCollector<>(); final List<JavaFileObject> javaFileObjectList = getJavaFileObject(); final CompilationTask task = CompilerUtil.getTask(javaFileManager, diagnosticCollector, options, javaFileObjectList); try{ if (task.call()) { // 加载编译后的类 return javaFileManager.getClassLoader(StandardLocation.CLASS_OUTPUT); } } finally { IoUtil.close(javaFileManager); } //编译失败,收集错误信息 throw new CompilerException(DiagnosticUtil.getMessages(diagnosticCollector)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ClassLoader compile() { // 获得classPath final List<File> classPath = getClassPath(); final URL[] urLs = URLUtil.getURLs(classPath.toArray(new File[0])); final URLClassLoader ucl = URLClassLoader.newInstance(urLs, this.parentClassLoader); if (sourceCodeMap.isEmpty() && sourceFileList.isEmpty()) { // 没有需要编译的源码 return ucl; } // 没有需要编译的源码文件返回加载zip或jar包的类加载器 // 创建编译器 final JavaFileManager javaFileManager = new JavaClassFileManager(ucl, CompilerUtil.getFileManager()); // classpath final List<String> options = new ArrayList<>(); if (false == classPath.isEmpty()) { final List<String> cp = classPath.stream().map(File::getAbsolutePath).collect(Collectors.toList()); options.add("-cp"); options.addAll(cp); } // 编译文件 final DiagnosticCollector<? super JavaFileObject> diagnosticCollector = new DiagnosticCollector<>(); final List<JavaFileObject> javaFileObjectList = getJavaFileObject(); final CompilationTask task = CompilerUtil.getTask(javaFileManager, diagnosticCollector, options, javaFileObjectList); if (task.call()) { // 加载编译后的类 return javaFileManager.getClassLoader(StandardLocation.CLASS_OUTPUT); } else { // 编译失败,收集错误信息 throw new CompilerException(DiagnosticUtil.getMessages(diagnosticCollector)); } } #location 33 #vulnerability type RESOURCE_LEAK
#fixed code DccManager(PircBotX bot) { _bot = bot; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean processRequest(String nick, String login, String hostname, String request) { StringTokenizer tokenizer = new StringTokenizer(request); tokenizer.nextToken(); String type = tokenizer.nextToken(); String filename = tokenizer.nextToken(); if (type.equals("SEND")) { long address = Long.parseLong(tokenizer.nextToken()); int port = Integer.parseInt(tokenizer.nextToken()); long size = -1; try { size = Long.parseLong(tokenizer.nextToken()); } catch (Exception e) { // Stick with the old value. } DccFileTransfer transfer = new DccFileTransfer(_bot, this, nick, login, hostname, type, filename, address, port, size); _bot.onIncomingFileTransfer(transfer); } else if (type.equals("RESUME")) { int port = Integer.parseInt(tokenizer.nextToken()); long progress = Long.parseLong(tokenizer.nextToken()); DccFileTransfer transfer = null; synchronized (_awaitingResume) { for (int i = 0; i < _awaitingResume.size(); i++) { transfer = (DccFileTransfer) _awaitingResume.elementAt(i); if (transfer.getNick().equals(nick) && transfer.getPort() == port) { _awaitingResume.removeElementAt(i); break; } } } if (transfer != null) { transfer.setProgress(progress); _bot.sendCTCPCommand(nick, "DCC ACCEPT file.ext " + port + " " + progress); } } else if (type.equals("ACCEPT")) { int port = Integer.parseInt(tokenizer.nextToken()); long progress = Long.parseLong(tokenizer.nextToken()); DccFileTransfer transfer = null; synchronized (_awaitingResume) { for (int i = 0; i < _awaitingResume.size(); i++) { transfer = (DccFileTransfer) _awaitingResume.elementAt(i); if (transfer.getNick().equals(nick) && transfer.getPort() == port) { _awaitingResume.removeElementAt(i); break; } } } if (transfer != null) transfer.doReceive(transfer.getFile(), true); } else if (type.equals("CHAT")) { long address = Long.parseLong(tokenizer.nextToken()); int port = Integer.parseInt(tokenizer.nextToken()); final DccChat chat = new DccChat(_bot, nick, login, hostname, address, port); new Thread() { public void run() { _bot.onIncomingChatRequest(chat); } }.start(); } else return false; return true; } #location 36 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleLine(String line) throws Throwable { try { log(line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. onServerPing(line.substring(5)); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else { // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; target = token; } } else { // We don't know what this line means. onUnknown(line); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request onVersion(sourceNick, sourceLogin, sourceHostname, target); else if (request.startsWith("ACTION ")) // ACTION request onAction(sourceNick, sourceLogin, sourceHostname, target, request.substring(7)); else if (request.startsWith("PING ")) // PING request onPing(sourceNick, sourceLogin, sourceHostname, target, request.substring(5)); else if (request.equals("TIME")) // TIME request onTime(sourceNick, sourceLogin, sourceHostname, target); else if (request.equals("FINGER")) // FINGER request onFinger(sourceNick, sourceLogin, sourceHostname, target); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(sourceNick, sourceLogin, sourceHostname, request); if (!success) // The DccManager didn't know what to do with the line. onUnknown(line); } else // An unknown CTCP message - ignore it. onUnknown(line); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. onMessage(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("PRIVMSG")) // This is a private message to us. onPrivateMessage(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("JOIN")) { // Someone is joining a channel. String channel = target; Channel chan = getChannel(channel); if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup sendRawLine("WHO " + channel); sendRawLine("MODE " + channel); } User usr = getUser(sourceNick); //Only setup if nessesary if (usr.getHostmask() == null) { usr.setLogin(sourceLogin); usr.setHostmask(sourceHostname); } chan.addUser(usr); onJoin(channel, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("PART")) { // Someone is parting from a channel. if (sourceNick.equals(getNick())) removeChannel(target); else //Just remove the user from memory getChannel(target).removeUser(sourceNick); onPart(target, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; renameUser(sourceNick, newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); onNickChange(sourceNick, sourceLogin, sourceHostname, newNick); } else if (command.equals("NOTICE")) // Someone is sending a notice. onNotice(sourceNick, sourceLogin, sourceHostname, target, line.substring(line.indexOf(" :") + 2)); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) removeAllChannels(); else removeUser(sourceNick); onQuit(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. String recipient = tokenizer.nextToken(); if (recipient.equals(getNick())) removeChannel(target); removeUser(recipient); onKick(target, sourceNick, sourceLogin, sourceHostname, recipient, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) { // Someone is changing the topic. String topic = line.substring(line.indexOf(" :") + 2); long currentTime = System.currentTimeMillis(); Channel chan = getChannel(target); chan.setTopic(topic); chan.setTopicSetter(sourceNick); chan.setTopicTimestamp(currentTime); onTopic(target, topic, sourceNick, currentTime, true); } else if (command.equals("INVITE")) // Somebody is inviting somebody else into a channel. onInvite(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. onUnknown(line); } catch (Throwable t) { // Stick the whole stack trace into a String so we can output it nicely. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); synchronized (this) { log("### Your implementation of PircBotXis faulty and you have"); log("### allowed an uncaught Exception or Error to propagate in your"); log("### code. It may be possible for PircBotXto continue operating"); log("### normally. Here is the stack trace that was produced: -"); log("### "); for (String curLine : sw.toString().split("\r\n")) log("### " + curLine); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleLine(String line) throws Throwable { try { log(line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. onServerPing(line.substring(5)); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else { // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; target = token; } } else { // We don't know what this line means. onUnknown(line); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request onVersion(sourceNick, sourceLogin, sourceHostname, target); else if (request.startsWith("ACTION ")) // ACTION request onAction(sourceNick, sourceLogin, sourceHostname, target, request.substring(7)); else if (request.startsWith("PING ")) // PING request onPing(sourceNick, sourceLogin, sourceHostname, target, request.substring(5)); else if (request.equals("TIME")) // TIME request onTime(sourceNick, sourceLogin, sourceHostname, target); else if (request.equals("FINGER")) // FINGER request onFinger(sourceNick, sourceLogin, sourceHostname, target); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(sourceNick, sourceLogin, sourceHostname, request); if (!success) // The DccManager didn't know what to do with the line. onUnknown(line); } else // An unknown CTCP message - ignore it. onUnknown(line); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. onMessage(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("PRIVMSG")) // This is a private message to us. onPrivateMessage(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else if (command.equals("JOIN")) { // Someone is joining a channel. String channel = target; if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup _channels.put(channel, new Channel(channel)); sendRawLine("WHO " + channel); sendRawLine("MODE " + channel); } User usr = _channels.get(channel).getUser(sourceNick); usr.setLogin(sourceLogin); usr.setHostmask(sourceHostname); onJoin(channel, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("PART")) { // Someone is parting from a channel. removeUser(target, sourceNick); if (sourceNick.equals(getNick())) removeChannel(target); onPart(target, sourceNick, sourceLogin, sourceHostname); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; renameUser(sourceNick, newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); onNickChange(sourceNick, sourceLogin, sourceHostname, newNick); } else if (command.equals("NOTICE")) // Someone is sending a notice. onNotice(sourceNick, sourceLogin, sourceHostname, target, line.substring(line.indexOf(" :") + 2)); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) removeAllChannels(); else removeUser(sourceNick); onQuit(sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. String recipient = tokenizer.nextToken(); if (recipient.equals(getNick())) removeChannel(target); removeUser(target, recipient); onKick(target, sourceNick, sourceLogin, sourceHostname, recipient, line.substring(line.indexOf(" :") + 2)); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) // Someone is changing the topic. onTopic(target, line.substring(line.indexOf(" :") + 2), sourceNick, System.currentTimeMillis(), true); else if (command.equals("INVITE")) // Somebody is inviting somebody else into a channel. onInvite(target, sourceNick, sourceLogin, sourceHostname, line.substring(line.indexOf(" :") + 2)); else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. onUnknown(line); } catch (Throwable t) { // Stick the whole stack trace into a String so we can output it nicely. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); synchronized (this) { log("### Your implementation of PircBotXis faulty and you have"); log("### allowed an uncaught Exception or Error to propagate in your"); log("### code. It may be possible for PircBotXto continue operating"); log("### normally. Here is the stack trace that was produced: -"); log("### "); for (String curLine : sw.toString().split("\r\n")) log("### " + curLine); } } } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testStart_WFData() throws Exception { Map<Object, Object> map = new HashMap<Object, Object>(); map.put("process.label", "test"); swr.bindWorkflowProcesses(new WFDataWorkflowProcess(), map); Map<String, Map<String, Object>> metadata = new HashMap<String, Map<String, Object>>(); swr.start(resourceResolver, "/content/test", new String[] {"test"}, metadata); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testStart_WFData() throws Exception { Map<Object, Object> map = new HashMap<Object, Object>(); map.put("process.label", "test"); swr.bindWorkflowProcesses(new WFDataWorkflowProcess(), map); Map<String, Map<String, Object>> metadata = new HashMap<String, Map<String, Object>>(); swr.start(null, "/content/test", new String[] {"test"}, metadata); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public final void clearCache() { this.cache.clear(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public final void clearCache() { synchronized (this.cache) { this.cache.clear(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testCreateRuntime_Injection() { BQRuntime runtime = testFactory.app("-x").autoLoadModules().createRuntime(); assertArrayEquals(new String[]{"-x"}, runtime.getArgs()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCreateRuntime_Injection() { BQTestRuntime runtime = testFactory.app("-x").autoLoadModules().createRuntime(); assertArrayEquals(new String[]{"-x"}, runtime.getRuntime().getArgs()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected MetricData getRollupByGranularity( String tenantId, String metricName, long from, long to, Granularity g) { final Timer.Context ctx = metricsFetchTimer.time(); final Locator locator = Locator.createLocatorFromPathComponents(tenantId, metricName); final MetricData metricData = AstyanaxReader.getInstance().getDatapointsForRange( locator, new Range(g.snapMillis(from), to), g); boolean isRollable = metricData.getType().equals(MetricData.Type.NUMBER.toString()) || metricData.getType().equals(MetricData.Type.HISTOGRAM.toString()); // if Granularity is FULL, we are missing raw data - can't generate that if (ROLLUP_REPAIR && isRollable && g != Granularity.FULL && metricData != null) { final Timer.Context rollupsCalcCtx = rollupsCalcOnReadTimer.time(); if (metricData.getData().isEmpty()) { // data completely missing for range. complete repair. rollupsRepairEntireRange.mark(); List<Points.Point> repairedPoints = repairRollupsOnRead(locator, g, from, to); for (Points.Point repairedPoint : repairedPoints) { metricData.getData().add(repairedPoint); } if (repairedPoints.isEmpty()) { rollupsRepairEntireRangeEmpty.mark(); } } else { long actualStart = minTime(metricData.getData()); long actualEnd = maxTime(metricData.getData()); // If the returned start is greater than 'from', we are missing a portion of data. if (actualStart > from) { rollupsRepairedLeft.mark(); List<Points.Point> repairedLeft = repairRollupsOnRead(locator, g, from, actualStart); for (Points.Point repairedPoint : repairedLeft) { metricData.getData().add(repairedPoint); } if (repairedLeft.isEmpty()) { rollupsRepairedLeftEmpty.mark(); } } // If the returned end timestamp is less than 'to', we are missing a portion of data. if (actualEnd + g.milliseconds() <= to) { rollupsRepairedRight.mark(); List<Points.Point> repairedRight = repairRollupsOnRead(locator, g, actualEnd + g.milliseconds(), to); for (Points.Point repairedPoint : repairedRight) { metricData.getData().add(repairedPoint); } if (repairedRight.isEmpty()) { rollupsRepairedRightEmpty.mark(); } } } rollupsCalcCtx.stop(); } ctx.stop(); if (g == Granularity.FULL) { numFullPointsReturned.update(metricData.getData().getPoints().size()); } else { numRollupPointsReturned.update(metricData.getData().getPoints().size()); } return metricData; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected MetricData getRollupByGranularity( String tenantId, String metricName, long from, long to, Granularity g) { final Timer.Context ctx = metricsFetchTimer.time(); final Locator locator = Locator.createLocatorFromPathComponents(tenantId, metricName); final MetricData metricData = AstyanaxReader.getInstance().getDatapointsForRange( locator, new Range(g.snapMillis(from), to), g); // if Granularity is FULL, we are missing raw data - can't generate that if (ROLLUP_REPAIR && g != Granularity.FULL && metricData != null) { final Timer.Context rollupsCalcCtx = rollupsCalcOnReadTimer.time(); if (metricData.getData().isEmpty()) { // data completely missing for range. complete repair. rollupsRepairEntireRange.mark(); List<Points.Point> repairedPoints = repairRollupsOnRead(locator, g, from, to); for (Points.Point repairedPoint : repairedPoints) { metricData.getData().add(repairedPoint); } if (repairedPoints.isEmpty()) { rollupsRepairEntireRangeEmpty.mark(); } } else { long actualStart = minTime(metricData.getData()); long actualEnd = maxTime(metricData.getData()); // If the returned start is greater than 'from', we are missing a portion of data. if (actualStart > from) { rollupsRepairedLeft.mark(); List<Points.Point> repairedLeft = repairRollupsOnRead(locator, g, from, actualStart); for (Points.Point repairedPoint : repairedLeft) { metricData.getData().add(repairedPoint); } if (repairedLeft.isEmpty()) { rollupsRepairedLeftEmpty.mark(); } } // If the returned end timestamp is less than 'to', we are missing a portion of data. if (actualEnd + g.milliseconds() <= to) { rollupsRepairedRight.mark(); List<Points.Point> repairedRight = repairRollupsOnRead(locator, g, actualEnd + g.milliseconds(), to); for (Points.Point repairedPoint : repairedRight) { metricData.getData().add(repairedPoint); } if (repairedRight.isEmpty()) { rollupsRepairedRightEmpty.mark(); } } } rollupsCalcCtx.stop(); } ctx.stop(); if (g == Granularity.FULL) { numFullPointsReturned.update(metricData.getData().getPoints().size()); } else { numRollupPointsReturned.update(metricData.getData().getPoints().size()); } return metricData; } #location 66 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) { if (args.length != 5){ System.err.println("Usage: java " + AFLRedundancyDriver.class + " TEST_CLASS TEST_METHOD TEST_INPUT_FILE AFL_TO_JAVA_PIPE JAVA_TO_AFL_PIPE"); System.exit(1); } String testClassName = args[0]; String testMethodName = args[1]; String testInputFile = args[2]; String a2jPipe = args[3]; String j2aPipe = args[4]; try { // Load the guidance Guidance guidance = new AFLPerformanceGuidance(testInputFile, a2jPipe, j2aPipe); // Run the Junit test GuidedFuzzing.run(testClassName, testMethodName, guidance, System.out); } catch (Exception e) { e.printStackTrace(); System.exit(2); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { if (args.length != 5){ System.err.println("Usage: java " + AFLRedundancyDriver.class + " TEST_CLASS TEST_METHOD TEST_INPUT_FILE AFL_TO_JAVA_PIPE JAVA_TO_AFL_PIPE"); System.exit(1); } String testClassName = args[0]; String testMethodName = args[1]; String testInputFile = args[2]; String a2jPipe = args[3]; String j2aPipe = args[4]; try { // Load the guidance Guidance guidance = new AFLPerformanceGuidance(testInputFile, a2jPipe, j2aPipe); // Run the Junit test GuidedFuzzing.run(testClassName, testMethodName, guidance, System.out); } catch (ClassNotFoundException e) { System.err.println(String.format("Cannot load class %s", testClassName)); e.printStackTrace(); System.exit(2); } catch (IOException e) { e.printStackTrace(); System.exit(3); } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { final HttpRequest req = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); } nettyInputStream.clear(); // clearing the content - possible leftover from previous request processing. final ContainerRequest requestContext = createContainerRequest(ctx, req); requestContext.setWriter(new NettyResponseWriter(ctx, req, container)); long contentLength = req.headers().contains(HttpHeaderNames.CONTENT_LENGTH) ? HttpUtil.getContentLength(req) : -1L; if (contentLength >= MAX_REQUEST_ENTITY_BYTES) { requestContext.abortWith(javax.ws.rs.core.Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build()); } else { /** * Jackson JSON decoder tries to read a minimum of 2 bytes (4 * for BOM). So, during an empty or 1-byte input, we'd want to * avoid reading the entity to safely handle this edge case by * eventually throwing a malformed JSON exception. */ String contentType = req.headers().get(HttpHeaderNames.CONTENT_TYPE); boolean isJson = contentType != null ? contentType.toLowerCase().contains(MediaType.APPLICATION_JSON) : false; //process entity streams only if there is an entity issued in the request (i.e., content-length >=0). //Otherwise, it's safe to discard during next processing if ((!isJson && contentLength != -1) || HttpUtil.isTransferEncodingChunked(req) || (isJson && contentLength >= 2)) { requestContext.setEntityStream(nettyInputStream); } } // copying headers from netty request to jersey container request context. for (String name : req.headers().names()) { requestContext.headers(name, req.headers().getAll(name)); } // must be like this, since there is a blocking read from Jersey container.getExecutorService().execute(new Runnable() { @Override public void run() { container.getApplicationHandler().handle(requestContext); } }); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { nettyInputStream.publish(content); } if (msg instanceof LastHttpContent) { nettyInputStream.complete(null); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { final HttpRequest req = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); } isList.clear(); // clearing the content - possible leftover from previous request processing. final ContainerRequest requestContext = createContainerRequest(ctx, req); requestContext.setWriter(new NettyResponseWriter(ctx, req, container)); long contentLength = req.headers().contains(HttpHeaderNames.CONTENT_LENGTH) ? HttpUtil.getContentLength(req) : -1L; if (contentLength >= MAX_REQUEST_ENTITY_BYTES) { requestContext.abortWith(javax.ws.rs.core.Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build()); } else { /** * Jackson JSON decoder tries to read a minimum of 2 bytes (4 * for BOM). So, during an empty or 1-byte input, we'd want to * avoid reading the entity to safely handle this edge case by * eventually throwing a malformed JSON exception. */ String contentType = req.headers().get(HttpHeaderNames.CONTENT_TYPE); boolean isJson = contentType != null ? contentType.toLowerCase().contains(MediaType.APPLICATION_JSON) : false; //process entity streams only if there is an entity issued in the request (i.e., content-length >=0). //Otherwise, it's safe to discard during next processing if ((!isJson && contentLength != -1) || HttpUtil.isTransferEncodingChunked(req) || (isJson && contentLength >= 2)) { requestContext.setEntityStream(new NettyInputStream(isList)); } } // copying headers from netty request to jersey container request context. for (String name : req.headers().names()) { requestContext.headers(name, req.headers().getAll(name)); } // must be like this, since there is a blocking read from Jersey container.getExecutorService().execute(new Runnable() { @Override public void run() { container.getApplicationHandler().handle(requestContext); } }); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { isList.add(content); } if (msg instanceof LastHttpContent) { isList.add(Unpooled.EMPTY_BUFFER); } } } #location 34 #vulnerability type RESOURCE_LEAK
#fixed code public Object intercept(Invocation invocation) throws Throwable { if (autoRuntimeDialect) { SqlUtil sqlUtil = getSqlUtil(invocation); return sqlUtil.processPage(invocation); } else { if (autoDialect) { initSqlUtil(invocation); } return sqlUtil.processPage(invocation); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object intercept(Invocation invocation) throws Throwable { SqlUtil sqlUtil; if (autoRuntimeDialect) { sqlUtil = getSqlUtil(invocation); } else { if (autoDialect) { initSqlUtil(invocation); } sqlUtil = this.sqlUtil; } return sqlUtil.processPage(invocation); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private Long getRequestStartTime() { final RequestContext ctx = RequestContext.getCurrentContext(); final HttpServletRequest request = ctx.getRequest(); return (Long) request.getAttribute(REQUEST_START_TIME); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Long getRequestStartTime() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); return (Long) requestAttributes.getAttribute(REQUEST_START_TIME, SCOPE_REQUEST); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code DictionaryBuilder() { buffer = ByteBuffer.allocate(BUFFER_SIZE); buffer.order(ByteOrder.LITTLE_ENDIAN); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void buildLexicon(String filename, FileInputStream lexiconInput) throws IOException { int lineno = -1; try (InputStreamReader isr = new InputStreamReader(lexiconInput); LineNumberReader reader = new LineNumberReader(isr)) { for (String line = reader.readLine(); line != null; line = reader.readLine()) { lineno = reader.getLineNumber(); WordEntry entry = parseLine(line); if (entry.headword != null) { addToTrie(entry.headword, wordInfos.size()); } params.add(entry.parameters); wordInfos.add(entry.wordInfo); } } catch (Exception e) { if (lineno > 0) { System.err.println("Error: " + e.getMessage() + " at line " + lineno + " in " + filename); } throw e; } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Override public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) { oqueue.add( (WebSocketImpl) conn );// because the ostream will close the channel selector.wakeup(); try { if( removeConnection( conn ) ) { onClose( conn, code, reason, remote ); } } finally { try { releaseBuffers( conn ); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) { oqueue.add( (WebSocketImpl) conn );// because the ostream will close the channel selector.wakeup(); try { synchronized ( connections ) { if( this.connections.remove( conn ) ) { onClose( conn, code, reason, remote ); } } } finally { try { releaseBuffers( conn ); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public int getConnectionLostTimeout() { synchronized (syncConnectionLost) { return connectionLostTimeout; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int getConnectionLostTimeout() { return connectionLostTimeout; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { if( thread == null ) thread = Thread.currentThread(); interruptableRun(); assert ( !channel.isOpen() ); try { if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null selector.close(); } catch ( IOException e ) { onError( e ); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { if( thread == null ) thread = Thread.currentThread(); interruptableRun(); try { if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { channel.close(); } catch ( IOException e ) { onError( e ); } channel = null; thread = null; } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected final void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onWebsocketError( null, e ); return; } catch ( IOException e ) {// onWebsocketError( conn, e ); return; } catch ( SecurityException e ) { onWebsocketError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onWebsocketError( conn, e ); return; } conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() ); ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF ); try/*IO*/{ while ( !conn.isClosed() ) { if( Thread.interrupted() ) { conn.close( CloseFrame.NORMAL ); } SelectionKey key = null; SocketChannelIOHelper.batch( conn, channel ); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) { conn.decode( buff ); } if( !key.isValid() ) { continue; } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error } } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNORMAL_CLOSE ); } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.eot( e ); } try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { channel.close(); } catch ( IOException e ) { onError( e ); } channel = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected final void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onWebsocketError( null, e ); return; } catch ( IOException e ) {// onWebsocketError( conn, e ); return; } catch ( SecurityException e ) { onWebsocketError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onWebsocketError( conn, e ); return; } conn = (WebSocketImpl) wf.createWebSocket( this, draft, client ); ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF ); try/*IO*/{ while ( !conn.isClosed() ) { if( Thread.interrupted() ) { conn.close( CloseFrame.NORMAL ); } SelectionKey key = null; conn.flush(); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( key.isReadable() && conn.read( buff ) ) { conn.decode( buff ); } if( !key.isValid() ) { continue; } if( key.isWritable() ) { conn.flush(); } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error conn.flush(); } } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNORMAL_CLOSE ); return; } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false ); return; } try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { client.close(); } catch ( IOException e ) { onError( e ); } client = null; } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testFindFontFor() { assertNotNull(findFontFor("ทดสอบ")); // thai assertNotNull(findFontFor("αυτό είναι ένα τεστ")); // greek assertNotNull(findFontFor("വീട്")); // malayalam assertNotNull(findFontFor("मानक")); // hindi assertNotNull(findFontFor("జ")); // telugu assertNotNull(findFontFor("উ")); // bengali assertNotNull(findFontFor("עברית")); // hebrew assertNotNull(findFontFor("简化字")); // simplified chinese assertNotNull(findFontFor("한국어/조선말")); // korean assertNotNull(findFontFor("日本語")); // japanese assertNotNull(findFontFor("latin ąćęłńóśźż")); // latin }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFindFontFor() { assertEquals("NotoSansThai", findFontFor(new PDDocument(), "ทดสอบ").getName()); assertEquals("NotoSans", findFontFor(new PDDocument(), "αυτό είναι ένα τεστ").getName()); assertNull(findFontFor(new PDDocument(), "വീട്")); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testCanDisplayThai() { assertThat(findFontFor("นี่คือการทดสอบ"), is(notNullValue())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCanDisplayThai() { PDFont noto = FontUtils.loadFont(new PDDocument(), UnicodeType0Font.NOTO_SANS_THAI_REGULAR); assertThat(FontUtils.canDisplay("นี่คือการทดสอบ", noto), is(true)); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public void updateWinrate() { Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats(); if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) { history.getData().winrate = stats.maxWinrate; // we won't set playouts here. but setting winrate is ok... it shows the user that we are // computing. i think its fine. } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void updateWinrate() { Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats(); if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) { history.getData().winrate = stats.maxWinrate; if (Lizzie.leelaz.isKataGo) { history.getData().scoreMean = stats.maxScoreMean; } // we won't set playouts here. but setting winrate is ok... it shows the user that we are // computing. i think its fine. } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static boolean save(String filename) throws IOException { FileOutputStream fp = new FileOutputStream(filename); OutputStreamWriter writer = new OutputStreamWriter(fp); try { // add SGF header StringBuilder builder = new StringBuilder(String.format("(;KM[7.5]AP[Lizzie: %s]", Lizzie.lizzieVersion)); // move to the first move BoardHistoryList history = Lizzie.board.getHistory(); while (history.previous() != null); // replay moves, and convert them to tags. // * format: ";B[xy]" or ";W[xy]" // * with 'xy' = coordinates ; or 'tt' for pass. BoardData data; while ((data = history.next()) != null) { String stone; if (Stone.BLACK.equals(data.lastMoveColor)) stone = "B"; else if (Stone.WHITE.equals(data.lastMoveColor)) stone = "W"; else continue; char x = data.lastMove == null ? 't' : (char) (data.lastMove[0] + 'a'); char y = data.lastMove == null ? 't' : (char) (data.lastMove[1] + 'a'); builder.append(String.format(";%s[%c%c]", stone, x, y)); } // close file builder.append(')'); writer.append(builder.toString()); } finally { writer.close(); fp.close(); } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static boolean save(String filename) throws IOException { FileOutputStream fp = new FileOutputStream(filename); OutputStreamWriter writer = new OutputStreamWriter(fp); StringBuilder builder = new StringBuilder(String.format("(;KM[7.5]AP[Lizzie: %s]", Lizzie.lizzieVersion)); BoardHistoryList history = Lizzie.board.getHistory(); while (history.previous() != null) ; BoardData data = null; while ((data = history.next()) != null) { StringBuilder tag = new StringBuilder(";"); if (data.lastMoveColor.equals(Stone.BLACK)) { tag.append("B"); } else if (data.lastMoveColor.equals(Stone.WHITE)) { tag.append("W"); } else { return false; } char x = (char) data.lastMove[0], y = (char) data.lastMove[1]; x += 'a'; y += 'a'; tag.append(String.format("[%c%c]", x, y)); builder.append(tag); } builder.append(')'); writer.append(builder.toString()); writer.close(); fp.close(); return true; } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGetPropertyType() throws Exception { assertThat(TypeUtil.getPropertyType(A.class, "b.i", "1").equals(Integer.class), equalTo(true)); assertThat(TypeUtil.getPropertyType(A.class, "s", "2").equals(String.class), equalTo(true)); TypeUtil.getPropertyType(A.class, "b.j", "3"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetPropertyType() throws Exception { assertThat(TypeUtil.getPropertyType(A.class, "b.i").equals(Integer.class), equalTo(true)); assertThat(TypeUtil.getPropertyType(A.class, "s").equals(String.class), equalTo(true)); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public RegistryCenterConfiguration findConfigByNamespace(String namespace) { if(Strings.isNullOrEmpty(namespace)){ return null; } Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values(); for (ZkCluster zkCluster: zkClusters) { for(RegistryCenterConfiguration each: zkCluster.getRegCenterConfList()) { if (each != null && namespace.equals(each.getNamespace())) { return each; } } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public RegistryCenterConfiguration findConfigByNamespace(String namespace) { if(Strings.isNullOrEmpty(namespace)){ return null; } Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values(); for (ZkCluster zkCluster: zkClusters) { for(RegistryCenterConfiguration each: REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr())) { if (each != null && namespace.equals(each.getNamespace())) { return each; } } } return null; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public static void startNamespaceShardingManagerList(int count) throws Exception { assertThat(nestedZkUtils.isStarted()); for (int i = 0; i < count; i++) { ZookeeperRegistryCenter shardingRegCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration(-1, nestedZkUtils.getZkString(), NAMESPACE, 1000, 3000, 3)); shardingRegCenter.init(); NamespaceShardingManager namespaceShardingManager = new NamespaceShardingManager((CuratorFramework) shardingRegCenter.getRawClient(),NAMESPACE, "127.0.0.1-" + i); namespaceShardingManager.start(); namespaceShardingManagerList.add(namespaceShardingManager); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void startNamespaceShardingManagerList(int count) throws Exception { assertThat(nestedZkUtils.isStarted()); for (int i = 0; i < count; i++) { shardingRegCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration(-1, nestedZkUtils.getZkString(), NAMESPACE, 1000, 3000, 3)); shardingRegCenter.init(); NamespaceShardingManager namespaceShardingManager = new NamespaceShardingManager((CuratorFramework) shardingRegCenter.getRawClient(),NAMESPACE, "127.0.0.1-" + i); namespaceShardingManager.start(); namespaceShardingManagerList.add(namespaceShardingManager); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main (String[] args) throws Exception { // Prepare our context and sockets ZMQ.Context context = ZMQ.context(1); // Connect to task ventilator ZMQ.Socket receiver = context.socket(ZMQ.PULL); receiver.connect("tcp://localhost:5557"); // Connect to weather server ZMQ.Socket subscriber = context.socket(ZMQ.SUB); subscriber.connect("tcp://localhost:5556"); subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET)); // Process messages from both sockets // We prioritize traffic from the task ventilator while (!Thread.currentThread ().isInterrupted ()) { // Process any waiting tasks byte[] task; while((task = receiver.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process task"); } // Process any waiting weather updates byte[] update; while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process weather update"); } // No activity, so sleep for 1 msec Thread.sleep(1000); } receiver.close (); subscriber.close (); context.term (); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main (String[] args) throws Exception { // Prepare our context and sockets ZMQ.Context context = ZMQ.context(1); // Connect to task ventilator ZMQ.Socket receiver = context.socket(ZMQ.PULL); receiver.connect("tcp://localhost:5557"); // Connect to weather server ZMQ.Socket subscriber = context.socket(ZMQ.SUB); subscriber.connect("tcp://localhost:5556"); subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET)); // Process messages from both sockets // We prioritize traffic from the task ventilator while (!Thread.currentThread ().isInterrupted ()) { // Process any waiting tasks byte[] task; while((task = receiver.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process task"); } // Process any waiting weather updates byte[] update; while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process weather update"); } // No activity, so sleep for 1 msec Thread.sleep(1000); } subscriber.close (); context.term (); } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testConnectResolve() throws IOException { int port = Utils.findOpenPort(); System.out.println("test_connect_resolve running...\n"); Ctx ctx = ZMQ.init(1); assertThat(ctx, notNullValue()); // Create pair of socket, each with high watermark of 2. Thus the total // buffer space should be 4 messages. SocketBase sock = ZMQ.socket(ctx, ZMQ.ZMQ_PUB); assertThat(sock, notNullValue()); boolean brc = ZMQ.connect(sock, "tcp://localhost:" + port); assertThat(brc, is(true)); /* try { brc = ZMQ.connect (sock, "tcp://foobar123xyz:" + port); assertTrue(false); } catch (IllegalArgumentException e) { } */ ZMQ.close(sock); ZMQ.term(ctx); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConnectResolve() { System.out.println("test_connect_resolve running...\n"); Ctx ctx = ZMQ.init(1); assertThat(ctx, notNullValue()); // Create pair of socket, each with high watermark of 2. Thus the total // buffer space should be 4 messages. SocketBase sock = ZMQ.socket(ctx, ZMQ.ZMQ_PUB); assertThat(sock, notNullValue()); boolean brc = ZMQ.connect(sock, "tcp://localhost:1234"); assertThat(brc, is(true)); /* try { brc = ZMQ.connect (sock, "tcp://foobar123xyz:1234"); assertTrue(false); } catch (IllegalArgumentException e) { } */ ZMQ.close(sock); ZMQ.term(ctx); } #location 26 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testIssue476() throws InterruptedException, IOException, ExecutionException { final int front = Utils.findOpenPort(); final int back = Utils.findOpenPort(); final int max = 20; ExecutorService service = Executors.newFixedThreadPool(3); try (final ZContext ctx = new ZContext()) { service.submit(() -> { Thread.currentThread().setName("Proxy"); Socket xpub = ctx.createSocket(SocketType.XPUB); xpub.bind("tcp://*:" + back); Socket xsub = ctx.createSocket(SocketType.XSUB); xsub.bind("tcp://*:" + front); Socket ctrl = ctx.createSocket(SocketType.PAIR); ctrl.bind("inproc://ctrl-proxy"); ZMQ.proxy(xpub, xsub, null, ctrl); }); final AtomicReference<Throwable> error = testIssue476(front, back, max, service, ctx); ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR); ctrl.connect("inproc://ctrl-proxy"); ctrl.send(ZMQ.PROXY_TERMINATE); ctrl.close(); service.shutdown(); service.awaitTermination(2, TimeUnit.SECONDS); assertThat(error.get(), nullValue()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testIssue476() throws InterruptedException, IOException, ExecutionException { final int front = Utils.findOpenPort(); final int back = Utils.findOpenPort(); final int max = 10; ExecutorService service = Executors.newFixedThreadPool(3); final ZContext ctx = new ZContext(); service.submit(new Runnable() { @Override public void run() { Thread.currentThread().setName("Proxy"); ZMQ.Socket xpub = ctx.createSocket(SocketType.XPUB); xpub.bind("tcp://*:" + back); ZMQ.Socket xsub = ctx.createSocket(SocketType.XSUB); xsub.bind("tcp://*:" + front); ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR); ctrl.bind("inproc://ctrl-proxy"); ZMQ.proxy(xpub, xsub, null, ctrl); } }); final AtomicReference<Throwable> error = testIssue476(front, back, max, service, ctx); ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR); ctrl.connect("inproc://ctrl-proxy"); ctrl.send(ZMQ.PROXY_TERMINATE); ctrl.close(); service.shutdown(); service.awaitTermination(2, TimeUnit.SECONDS); assertThat(error.get(), nullValue()); ctx.close(); } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @SuppressWarnings("unchecked") private void loadFromFile() { try { File file = new File(filename); if (file.exists()) { try (InputStreamReader in = new InputStreamReader(new FileInputStream(file))) { Map<String, BootstrapConfig> config = gson.fromJson(in, gsonType); bootstrapByEndpoint.putAll(config); } } else { // TODO temporary code for retro compatibility: remove it later. if (DEFAULT_FILE.equals(filename)) { file = new File("data/bootstrap.data");// old bootstrap configurations default filename if (file.exists()) { try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) { bootstrapByEndpoint.putAll((Map<String, BootstrapConfig>) in.readObject()); } } } } } catch (Exception e) { LOG.error("Could not load bootstrap infos from file", e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") private void loadFromFile() { try { File file = new File(filename); if (file.exists()) { try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) { bootstrapByEndpoint.putAll((Map<String, BootstrapConfig>) in.readObject()); } } } catch (Exception e) { LOG.error("Could not load bootstrap infos from file", e); } } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @SuppressWarnings("unchecked") private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass) throws CodecException { LOG.trace("Parsing TLV content for path {}: {}", path, tlvs); // Object if (nodeClass == LwM2mObject.class) { List<LwM2mObjectInstance> instances = new ArrayList<>(); // is it an array of TLV resources? if (tlvs.length > 0 && // (tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) { ObjectModel oModel = model.getObjectModel(path.getObjectId()); if (oModel == null) { LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object", path.getObjectId()); instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model)); } else if (!oModel.multiple) { instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model)); } else { throw new CodecException(String .format("Object instance TLV is mandatory for multiple instances object [path:%s]", path)); } } else { for (Tlv tlv : tlvs) { if (tlv.getType() != TlvType.OBJECT_INSTANCE) throw new CodecException( String.format("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]", tlv.getType().name(), path)); instances.add(parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(), tlv.getIdentifier(), model)); } } return (T) new LwM2mObject(path.getObjectId(), instances); } // Object instance else if (nodeClass == LwM2mObjectInstance.class) { if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) { if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) { throw new CodecException(String.format("Id conflict between path [%s] and instance TLV [%d]", path, tlvs[0].getIdentifier())); } // object instance TLV return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(), model); } else { // array of TLV resources // try to retrieve the instanceId from the path or the model Integer instanceId = path.getObjectInstanceId(); if (instanceId == null) { // single instance object? ObjectModel oModel = model.getObjectModel(path.getObjectId()); if (oModel != null && !oModel.multiple) { instanceId = 0; } else { instanceId = LwM2mObjectInstance.UNDEFINED; } } return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model); } } // Resource else if (nodeClass == LwM2mResource.class) { ResourceModel resourceModel = model.getResourceModel(path.getObjectId(), path.getResourceId()); if (tlvs.length == 0 && resourceModel != null && !resourceModel.multiple) { // If there is no TlV value and we know that this resource is a single resource we raise an exception // else we consider this is a multi-instance resource throw new CodecException(String.format("TLV payload is mandatory for single resource %s", path)); } else if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) { if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) { throw new CodecException(String.format("Id conflict between path [%s] and resource TLV [%s]", path, tlvs[0].getIdentifier())); } return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model); } else { Type expectedRscType = getResourceType(path, model); return (T) LwM2mMultipleResource.newResource(path.getResourceId(), parseTlvValues(tlvs, expectedRscType, path), expectedRscType); } } else { throw new IllegalArgumentException("invalid node class: " + nodeClass); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass) throws CodecException { LOG.trace("Parsing TLV content for path {}: {}", path, tlvs); // Object if (nodeClass == LwM2mObject.class) { List<LwM2mObjectInstance> instances = new ArrayList<>(); // is it an array of TLV resources? if (tlvs.length > 0 && // (tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) { ObjectModel oModel = model.getObjectModel(path.getObjectId()); if (oModel == null) { LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object", path.getObjectId()); instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model)); } else if (!oModel.multiple) { instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model)); } else { throw new CodecException(String .format("Object instance TLV is mandatory for multiple instances object [path:%s]", path)); } } else { for (Tlv tlv : tlvs) { if (tlv.getType() != TlvType.OBJECT_INSTANCE) throw new CodecException( String.format("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]", tlv.getType().name(), path)); instances.add(parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(), tlv.getIdentifier(), model)); } } return (T) new LwM2mObject(path.getObjectId(), instances); } // Object instance else if (nodeClass == LwM2mObjectInstance.class) { if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) { if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) { throw new CodecException(String.format("Id conflict between path [%s] and instance TLV [%d]", path, tlvs[0].getIdentifier())); } // object instance TLV return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(), model); } else { // array of TLV resources // try to retrieve the instanceId from the path or the model Integer instanceId = path.getObjectInstanceId(); if (instanceId == null) { // single instance object? ObjectModel oModel = model.getObjectModel(path.getObjectId()); if (oModel != null && !oModel.multiple) { instanceId = 0; } else { instanceId = LwM2mObjectInstance.UNDEFINED; } } return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model); } } // Resource else if (nodeClass == LwM2mResource.class) { if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) { if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) { throw new CodecException(String.format("Id conflict between path [%s] and resource TLV [%s]", path, tlvs[0].getIdentifier())); } return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model); } else { Type expectedRscType = getResourceType(path, model); return (T) LwM2mMultipleResource.newResource(path.getResourceId(), parseTlvValues(tlvs, expectedRscType, path), expectedRscType); } } else { throw new IllegalArgumentException("invalid node class: " + nodeClass); } } #location 76 #vulnerability type NULL_DEREFERENCE
#fixed code protected void beginTransaction() { transactionalListener.beginTransaction(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void beginTransaction() { if (listener != null) { listener.beginTransaction(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void createClient() { // Create objects Enabler ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(createObjectModels())); initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec( "coap://" + server.getUnsecuredAddress().getHostString() + ":" + server.getUnsecuredAddress().getPort(), 12345)); initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false)); initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U") { @Override public ExecuteResponse execute(int resourceid, String params) { if (resourceid == 4) { return ExecuteResponse.success(); } else { return super.execute(resourceid, params); } } }); List<LwM2mObjectEnabler> objects = initializer.createMandatory(); objects.addAll(initializer.create(2, 2000)); // Build Client LeshanClientBuilder builder = new LeshanClientBuilder(currentEndpointIdentifier.get()); builder.setObjects(objects); client = builder.build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void createClient() { // Create objects Enabler ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(createObjectModels())); initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec( "coap://" + server.getNonSecureAddress().getHostString() + ":" + server.getNonSecureAddress().getPort(), 12345)); initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false)); initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U") { @Override public ExecuteResponse execute(int resourceid, String params) { if (resourceid == 4) { return ExecuteResponse.success(); } else { return super.execute(resourceid, params); } } }); List<LwM2mObjectEnabler> objects = initializer.createMandatory(); objects.addAll(initializer.create(2, 2000)); // Build Client LeshanClientBuilder builder = new LeshanClientBuilder(currentEndpointIdentifier.get()); builder.setObjects(objects); client = builder.build(); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code protected void endTransaction() { transactionalListener.endTransaction(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void endTransaction() { if (listener != null) { listener.endTransaction(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Field<O> setLiteralInitializer(final String value) { String stub = "public class Stub { private String stub = " + value + " }"; JavaClass temp = (JavaClass) JavaParser.parse(stub); VariableDeclarationFragment tempFrag = (VariableDeclarationFragment) temp.getFields().get(0).getInternal(); fragment.setInitializer((Expression) ASTNode.copySubtree(ast, tempFrag.getInitializer())); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Field<O> setLiteralInitializer(final String value) { String stub = "public class Stub { private String stub = " + value + " }"; JavaClass temp = (JavaClass) JavaParser.parse(stub); FieldDeclaration internal = (FieldDeclaration) temp.getFields().get(0).getInternal(); for (Object f : internal.fragments()) { if (f instanceof VariableDeclarationFragment) { VariableDeclarationFragment tempFrag = (VariableDeclarationFragment) f; VariableDeclarationFragment localFrag = getFragment(field); localFrag.setInitializer((Expression) ASTNode.copySubtree(ast, tempFrag.getInitializer())); break; } } return this; } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code public static String toString(final InputStream stream) { StringBuilder out = new StringBuilder(); try { final char[] buffer = new char[0x10000]; Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8); int read; do { read = in.read(buffer, 0, buffer.length); if (read > 0) { out.append(buffer, 0, read); } } while (read >= 0); } catch (IOException e) { throw new RuntimeException(e); } return out.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String toString(final InputStream stream) { StringBuilder out = new StringBuilder(); try { final char[] buffer = new char[0x10000]; Reader in = new InputStreamReader(stream, "UTF-8"); int read; do { read = in.read(buffer, 0, buffer.length); if (read > 0) { out.append(buffer, 0, read); } } while (read >= 0); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return out.toString(); } #location 27 #vulnerability type RESOURCE_LEAK
#fixed code public static void beginRequest(HttpServletRequest request) { }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void beginRequest(HttpServletRequest request) { ManagerImpl manager = (ManagerImpl) JNDI.lookup("manager"); SessionContext sessionContext = (SessionContext) manager.getContext(SessionScoped.class); BeanMap sessionBeans = (BeanMap) request.getAttribute(SESSION_BEANMAP_KEY); sessionContext.setBeans(sessionBeans); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private View getViewOnListLine(AbsListView absListView, int lineIndex){ final long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout(); View view = absListView.getChildAt(lineIndex); while(view == null){ final boolean timedOut = SystemClock.uptimeMillis() > endTime; if (timedOut){ Assert.fail("View is null and can therefore not be clicked!"); } sleeper.sleep(); absListView = (AbsListView) viewFetcher.getIdenticalView(absListView); if(absListView != null){ view = absListView.getChildAt(lineIndex); } } return view; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private View getViewOnListLine(AbsListView absListView, int lineIndex){ final long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout(); View view = absListView.getChildAt(lineIndex); while(view == null){ final boolean timedOut = SystemClock.uptimeMillis() > endTime; if (timedOut){ Assert.fail("View is null and can therefore not be clicked!"); } sleeper.sleep(); absListView = (AbsListView) viewFetcher.getIdenticalView(absListView); view = absListView.getChildAt(lineIndex); } return view; } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code private static void init() { try { LOGGER.info("Load "+PATH_FILE); InputStream input=GoKeyRule.class.getResourceAsStream(PATH_FILE); if(input==null){ throw new FileNotFoundException(PATH_FILE); } prop.load(input); } catch (IOException e) { LOGGER.error("Unable to load the config file", e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void init() { try { prop.load(new FileInputStream(new File(PATH_FILE))); } catch (FileNotFoundException e) { LOGGER.error("Unable to load the config file", e); } catch (IOException e) { LOGGER.error("Unable to load the config file", e); } } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Override public RulesProfile createProfile(ValidationMessages validation) { LOGGER.info("Golint Quality profile"); RulesProfile profile = RulesProfile.create("Golint Rules", GoLanguage.KEY); profile.setDefaultProfile(Boolean.TRUE); Properties prop=new Properties(); try { prop.load(GoQualityProfile.class.getResourceAsStream(GoQualityProfile.PROFILE_PATH)); for (Entry<Object, Object> e : prop.entrySet()) { if(Boolean.TRUE.equals(Boolean.parseBoolean((String) e.getValue()))){ profile.activateRule(Rule.create(REPO_KEY,(String) e.getKey(),REPO_NAME), null); } } }catch (IOException e) { LOGGER.error((new StringBuilder()).append("Unable to load ").append(PROFILE_PATH).toString(), e); } LOGGER.info((new StringBuilder()).append("Profil generate: ").append(profile.getActiveRules()).toString()); return profile; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public RulesProfile createProfile(ValidationMessages validation) { LOGGER.info("Golint Quality profile"); RulesProfile profile = RulesProfile.create("Golint Rules", GoLanguage.KEY); profile.setDefaultProfile(Boolean.TRUE); Properties prop=new Properties(); try { prop.load(new FileInputStream(new File(PROFILE_PATH))); for (Entry<Object, Object> e : prop.entrySet()) { if(Boolean.TRUE.equals(Boolean.parseBoolean((String) e.getValue()))){ profile.activateRule(Rule.create(REPO_KEY,(String) e.getKey(),REPO_NAME), null); } } }catch (IOException e) { LOGGER.error((new StringBuilder()).append("Unable to load ").append(PROFILE_PATH).toString(), e); } LOGGER.info((new StringBuilder()).append("Profil generate: ").append(profile.getActiveRules()).toString()); return profile; } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testByte() throws Exception { assertArrayEquals(new byte[]{-34}, BeginBin().Byte(-34).End().toByteArray()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testByte() throws Exception { assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBitArrayAsInts() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(1, 3, 0, 2, 4, 1, 3, 7).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(1, 3, 0, 7).End().toByteArray()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBitArrayAsInts() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException { int result; final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber(); if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) { result = this.readByteFromStream(); this.byteCounter++; return result; } else { result = 0; if (numOfBitsAsNumber == this.bitsInBuffer) { result = this.bitBuffer; this.bitBuffer = 0; this.bitsInBuffer = 0; if (numOfBitsAsNumber == 8) { this.byteCounter++; } return result; } int i = numOfBitsAsNumber; int theBitBuffer = this.bitBuffer; int theBitBufferCounter = this.bitsInBuffer; while (i > 0) { if (theBitBufferCounter == 0) { final int nextByte = this.readByteFromStream(); if (nextByte < 0) { if (i == numOfBitsAsNumber) { return nextByte; } else { break; } } else { theBitBuffer = nextByte; theBitBufferCounter = 8; this.byteCounter++; } } result = (result << 1) | (theBitBuffer & 1); theBitBuffer >>= 1; theBitBufferCounter--; i--; } this.bitBuffer = theBitBuffer; this.bitsInBuffer = theBitBufferCounter; return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException { int result; final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber(); if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) { result = this.readByteFromStream(); return result; } else { result = 0; if (numOfBitsAsNumber == this.bitsInBuffer){ result = this.bitBuffer; this.bitBuffer = 0; this.bitsInBuffer = 0; return result; } int i = numOfBitsAsNumber; int theBitBuffer = this.bitBuffer; int theBitBufferCounter = this.bitsInBuffer; while (i > 0) { if (theBitBufferCounter == 0) { final int nextByte = this.readByteFromStream(); if (nextByte < 0) { if (i == numOfBitsAsNumber) { return nextByte; } else { break; } } else { theBitBuffer = nextByte; theBitBufferCounter = 8; } } result = (result << 1) | (theBitBuffer & 1); theBitBuffer >>= 1; theBitBufferCounter--; i--; } this.bitBuffer = theBitBuffer; this.bitsInBuffer = theBitBufferCounter; return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i)); } } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testComplexWriting_1() throws Exception { final byte [] array = BeginBin(). Bit(1, 2, 3, 0). Bit(true, false, true). Align(). Byte(5). Short(1, 2, 3, 4, 5). Bool(true, false, true, true). Int(0xABCDEF23, 0xCAFEBABE). Long(0x123456789ABCDEF1L, 0x212356239091AB32L). End().toByteArray(); assertEquals(40, array.length); assertArrayEquals(new byte[]{ (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 }, array); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testComplexWriting_1() throws Exception { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); final JBBPOut begin = new JBBPOut(buffer); begin. Bit(1, 2, 3, 0). Bit(true, false, true). Align(). Byte(5). Short(1, 2, 3, 4, 5). Bool(true, false, true, true). Int(0xABCDEF23, 0xCAFEBABE). Long(0x123456789ABCDEF1L, 0x212356239091AB32L). end(); final byte[] array = buffer.toByteArray(); assertEquals(40, array.length); assertArrayEquals(new byte[]{ (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 }, array); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testAlign() throws Exception { assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align().Byte(0xFF).End().toByteArray()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAlign() throws Exception { assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).End().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testLong_BigEndian() throws Exception { assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, BeginBin().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).End().toByteArray()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testLong_BigEndian() throws Exception { assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public byte[] readBitsArray(final int items, final JBBPBitNumber bitNumber) throws IOException { return _readArray(items, bitNumber); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public byte[] readBitsArray(final int items, final JBBPBitNumber bitNumber) throws IOException { int pos = 0; if (items < 0) { byte[] buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE]; // till end while (true) { final int next = readBits(bitNumber); if (next < 0) { break; } if (buffer.length == pos) { final byte[] newbuffer = new byte[buffer.length << 1]; System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); buffer = newbuffer; } buffer[pos++] = (byte) next; } if (buffer.length == pos) { return buffer; } final byte[] result = new byte[pos]; System.arraycopy(buffer, 0, result, 0, pos); return result; } else { // number final byte[] buffer = new byte[items]; for (int i = 0; i < items; i++) { final int next = readBits(bitNumber); if (next < 0) { throw new EOFException("Have read only " + i + " bit portions instead of " + items); } buffer[i] = (byte) next; } return buffer; } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testBitArrayAsBooleans() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(true, true, false, false, false, true, true, true).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(true, true, false, true).End().toByteArray()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBitArrayAsBooleans() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException { int result; final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber(); if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) { result = this.readByteFromStream(); this.byteCounter++; return result; } else { result = 0; if (numOfBitsAsNumber == this.bitsInBuffer) { result = this.bitBuffer; this.bitBuffer = 0; this.bitsInBuffer = 0; if (numOfBitsAsNumber == 8) { this.byteCounter++; } return result; } int i = numOfBitsAsNumber; int theBitBuffer = this.bitBuffer; int theBitBufferCounter = this.bitsInBuffer; while (i > 0) { if (theBitBufferCounter == 0) { final int nextByte = this.readByteFromStream(); if (nextByte < 0) { if (i == numOfBitsAsNumber) { return nextByte; } else { break; } } else { theBitBuffer = nextByte; theBitBufferCounter = 8; this.byteCounter++; } } result = (result << 1) | (theBitBuffer & 1); theBitBuffer >>= 1; theBitBufferCounter--; i--; } this.bitBuffer = theBitBuffer; this.bitsInBuffer = theBitBufferCounter; return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException { int result; final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber(); if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) { result = this.readByteFromStream(); return result; } else { result = 0; if (numOfBitsAsNumber == this.bitsInBuffer){ result = this.bitBuffer; this.bitBuffer = 0; this.bitsInBuffer = 0; return result; } int i = numOfBitsAsNumber; int theBitBuffer = this.bitBuffer; int theBitBufferCounter = this.bitsInBuffer; while (i > 0) { if (theBitBufferCounter == 0) { final int nextByte = this.readByteFromStream(); if (nextByte < 0) { if (i == numOfBitsAsNumber) { return nextByte; } else { break; } } else { theBitBuffer = nextByte; theBitBufferCounter = 8; } } result = (result << 1) | (theBitBuffer & 1); theBitBuffer >>= 1; theBitBufferCounter--; i--; } this.bitBuffer = theBitBuffer; this.bitsInBuffer = theBitBufferCounter; return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i)); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testShortArray_AsIntegers() throws Exception { assertArrayEquals(new byte []{1,2,3,4}, BeginBin().Short(0x0102,0x0304).End().toByteArray()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testShortArray_AsIntegers() throws Exception { assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public void debugHeader() { if (!traceDebugEnabled) { return; } System.out.println("---------------- Trace Information ---------------"); String traceId = getTraceId(); String spanId = getSpanId(); System.out.println(DiscoveryConstant.TRACE_ID + "=" + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY)); System.out.println(DiscoveryConstant.SPAN_ID + "=" + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY)); System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP)); System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE)); System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID)); System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS)); System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION)); System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION)); System.out.println(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT)); String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION); if (StringUtils.isNotEmpty(routeVersion)) { System.out.println(DiscoveryConstant.N_D_VERSION + "=" + routeVersion); } String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION); if (StringUtils.isNotEmpty(routeRegion)) { System.out.println(DiscoveryConstant.N_D_REGION + "=" + routeRegion); } String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS); if (StringUtils.isNotEmpty(routeAddress)) { System.out.println(DiscoveryConstant.N_D_ADDRESS + "=" + routeAddress); } String routeEnvironment = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ENVIRONMENT); if (StringUtils.isNotEmpty(routeEnvironment)) { System.out.println(DiscoveryConstant.N_D_ENVIRONMENT + "=" + routeEnvironment); } String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT); if (StringUtils.isNotEmpty(routeVersionWeight)) { System.out.println(DiscoveryConstant.N_D_VERSION_WEIGHT + "=" + routeVersionWeight); } String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT); if (StringUtils.isNotEmpty(routeRegionWeight)) { System.out.println(DiscoveryConstant.N_D_REGION_WEIGHT + "=" + routeRegionWeight); } Map<String, String> customizationMap = getCustomizationMap(); if (MapUtils.isNotEmpty(customizationMap)) { for (Map.Entry<String, String> entry : customizationMap.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); } } System.out.println("--------------------------------------------------"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void debugHeader() { if (!traceDebugEnabled) { return; } System.out.println("---------------- Trace Information ---------------"); String traceId = getTraceId(); String spanId = getSpanId(); System.out.println(DiscoveryConstant.TRACE_ID + "=" + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY)); System.out.println(DiscoveryConstant.SPAN_ID + "=" + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY)); System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP)); System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE)); System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID)); System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS)); System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION)); System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION)); System.out.println(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT)); String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION); if (StringUtils.isNotEmpty(routeVersion)) { System.out.println(DiscoveryConstant.N_D_VERSION + "=" + routeVersion); } String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION); if (StringUtils.isNotEmpty(routeRegion)) { System.out.println(DiscoveryConstant.N_D_REGION + "=" + routeRegion); } String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS); if (StringUtils.isNotEmpty(routeAddress)) { System.out.println(DiscoveryConstant.N_D_ADDRESS + "=" + routeAddress); } String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT); if (StringUtils.isNotEmpty(routeVersionWeight)) { System.out.println(DiscoveryConstant.N_D_VERSION_WEIGHT + "=" + routeVersionWeight); } String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT); if (StringUtils.isNotEmpty(routeRegionWeight)) { System.out.println(DiscoveryConstant.N_D_REGION_WEIGHT + "=" + routeRegionWeight); } Map<String, String> customizationMap = getCustomizationMap(); if (MapUtils.isNotEmpty(customizationMap)) { for (Map.Entry<String, String> entry : customizationMap.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); } } System.out.println("--------------------------------------------------"); } #location 42 #vulnerability type NULL_DEREFERENCE
#fixed code @Before @SuppressWarnings({ "unchecked", "deprecation" }) public void before() throws IllegalArgumentException, IllegalAccessException, SQLException, SecurityException, NoSuchFieldException, CloneNotSupportedException{ driver = new MockJDBCDriver(new MockJDBCAnswer() { public Connection answer() throws SQLException { return new MockConnection(); } }); mockConfig = EasyMock.createNiceMock(BoneCPConfig.class); expect(mockConfig.clone()).andReturn(mockConfig).anyTimes(); expect(mockConfig.getPartitionCount()).andReturn(2).anyTimes(); expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes(); expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes(); expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(0L).anyTimes(); expect(mockConfig.getIdleMaxAgeInMinutes()).andReturn(1000L).anyTimes(); expect(mockConfig.getUsername()).andReturn(CommonTestUtils.username).anyTimes(); expect(mockConfig.getPassword()).andReturn(CommonTestUtils.password).anyTimes(); expect(mockConfig.getJdbcUrl()).andReturn(CommonTestUtils.url).anyTimes(); expect(mockConfig.getReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes(); expect(mockConfig.getStatementReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes(); expect(mockConfig.getInitSQL()).andReturn(CommonTestUtils.TEST_QUERY).anyTimes(); expect(mockConfig.isCloseConnectionWatch()).andReturn(true).anyTimes(); expect(mockConfig.isLogStatementsEnabled()).andReturn(true).anyTimes(); expect(mockConfig.getConnectionTimeoutInMs()).andReturn(Long.MAX_VALUE).anyTimes(); expect(mockConfig.getServiceOrder()).andReturn("LIFO").anyTimes(); expect(mockConfig.getAcquireRetryDelayInMs()).andReturn(1000L).anyTimes(); expect(mockConfig.getPoolName()).andReturn("poolName").anyTimes(); expect(mockConfig.getPoolAvailabilityThreshold()).andReturn(20).anyTimes(); replay(mockConfig); // once for no {statement, connection} release threads, once with release threads.... testClass = new BoneCP(mockConfig); testClass = new BoneCP(mockConfig); Field field = testClass.getClass().getDeclaredField("partitions"); field.setAccessible(true); ConnectionPartition[] partitions = (ConnectionPartition[]) field.get(testClass); // if all ok assertEquals(2, partitions.length); // switch to our mock version now mockPartition = EasyMock.createNiceMock(ConnectionPartition.class); Array.set(field.get(testClass), 0, mockPartition); Array.set(field.get(testClass), 1, mockPartition); mockKeepAliveScheduler = EasyMock.createNiceMock(ScheduledExecutorService.class); field = testClass.getClass().getDeclaredField("keepAliveScheduler"); field.setAccessible(true); field.set(testClass, mockKeepAliveScheduler); field = testClass.getClass().getDeclaredField("connectionsScheduler"); field.setAccessible(true); mockConnectionsScheduler = EasyMock.createNiceMock(ExecutorService.class); field.set(testClass, mockConnectionsScheduler); mockConnectionHandles = EasyMock.createNiceMock(BoundedLinkedTransferQueue.class); mockConnection = EasyMock.createNiceMock(ConnectionHandle.class); mockLock = EasyMock.createNiceMock(Lock.class); mockLogger = TestUtils.mockLogger(testClass.getClass()); makeThreadSafe(mockLogger, true); mockDatabaseMetadata = EasyMock.createNiceMock(DatabaseMetaData.class); mockResultSet = EasyMock.createNiceMock(MockResultSet.class); mockLogger.error((String)anyObject(), anyObject()); expectLastCall().anyTimes(); reset(mockConfig, mockKeepAliveScheduler, mockConnectionsScheduler, mockPartition, mockConnectionHandles, mockConnection, mockLock); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Before @SuppressWarnings({ "unchecked", "deprecation" }) public void before() throws IllegalArgumentException, IllegalAccessException, SQLException, SecurityException, NoSuchFieldException, CloneNotSupportedException{ mockConfig = EasyMock.createNiceMock(BoneCPConfig.class); expect(mockConfig.clone()).andReturn(mockConfig).anyTimes(); expect(mockConfig.getPartitionCount()).andReturn(2).anyTimes(); expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes(); expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes(); expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(0L).anyTimes(); expect(mockConfig.getIdleMaxAgeInMinutes()).andReturn(1000L).anyTimes(); expect(mockConfig.getUsername()).andReturn(CommonTestUtils.username).anyTimes(); expect(mockConfig.getPassword()).andReturn(CommonTestUtils.password).anyTimes(); expect(mockConfig.getJdbcUrl()).andReturn(CommonTestUtils.url).anyTimes(); expect(mockConfig.getReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes(); expect(mockConfig.getStatementReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes(); expect(mockConfig.getInitSQL()).andReturn(CommonTestUtils.TEST_QUERY).anyTimes(); expect(mockConfig.isCloseConnectionWatch()).andReturn(true).anyTimes(); expect(mockConfig.isLogStatementsEnabled()).andReturn(true).anyTimes(); expect(mockConfig.getConnectionTimeoutInMs()).andReturn(Long.MAX_VALUE).anyTimes(); expect(mockConfig.getServiceOrder()).andReturn("LIFO").anyTimes(); expect(mockConfig.getAcquireRetryDelayInMs()).andReturn(1000L).anyTimes(); expect(mockConfig.getPoolName()).andReturn("poolName").anyTimes(); expect(mockConfig.getPoolAvailabilityThreshold()).andReturn(20).anyTimes(); replay(mockConfig); // once for no {statement, connection} release threads, once with release threads.... testClass = new BoneCP(mockConfig); testClass = new BoneCP(mockConfig); Field field = testClass.getClass().getDeclaredField("partitions"); field.setAccessible(true); ConnectionPartition[] partitions = (ConnectionPartition[]) field.get(testClass); // if all ok assertEquals(2, partitions.length); // switch to our mock version now mockPartition = EasyMock.createNiceMock(ConnectionPartition.class); Array.set(field.get(testClass), 0, mockPartition); Array.set(field.get(testClass), 1, mockPartition); mockKeepAliveScheduler = EasyMock.createNiceMock(ScheduledExecutorService.class); field = testClass.getClass().getDeclaredField("keepAliveScheduler"); field.setAccessible(true); field.set(testClass, mockKeepAliveScheduler); field = testClass.getClass().getDeclaredField("connectionsScheduler"); field.setAccessible(true); mockConnectionsScheduler = EasyMock.createNiceMock(ExecutorService.class); field.set(testClass, mockConnectionsScheduler); mockConnectionHandles = EasyMock.createNiceMock(BoundedLinkedTransferQueue.class); mockConnection = EasyMock.createNiceMock(ConnectionHandle.class); mockLock = EasyMock.createNiceMock(Lock.class); mockLogger = TestUtils.mockLogger(testClass.getClass()); makeThreadSafe(mockLogger, true); mockDatabaseMetadata = EasyMock.createNiceMock(DatabaseMetaData.class); mockResultSet = EasyMock.createNiceMock(MockResultSet.class); mockLogger.error((String)anyObject(), anyObject()); expectLastCall().anyTimes(); reset(mockConfig, mockKeepAliveScheduler, mockConnectionsScheduler, mockPartition, mockConnectionHandles, mockConnection, mockLock); } #location 29 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void onPageLoad() { pageLoaded = true; reset(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onPageLoad() { System.err.println("new page loaded"); pageLoaded = true; reset(); try { Thread.sleep(5000); System.out.println( "on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument()) .optJSONObject("root").optString("documentURL")); } catch (Exception e) { e.printStackTrace(); } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testSpecialStyles() throws Exception { File f = new File("src/test/resources/special_types.xlsx"); Map<Integer, List<Cell>> contents = new HashMap<>(); try(Workbook wb = StreamingReader.builder().open(f)) { for(Row row : wb.getSheetAt(0)) { contents.put(row.getRowNum(), new ArrayList<Cell>()); for(Cell c : row) { if(c.getColumnIndex() > 0) { contents.get(row.getRowNum()).add(c); } } } } SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); assertThat(contents.size(), equalTo(2)); assertThat(contents.get(0).size(), equalTo(4)); assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14")); assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014"))); assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15")); assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015"))); assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015")); assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015"))); assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05")); assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015"))); assertThat(contents.get(1).size(), equalTo(4)); assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12")); assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312)); assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042")); assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0)); assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12")); assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145)); assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)")); assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSpecialStyles() throws Exception { File f = new File("src/test/resources/special_types.xlsx"); Map<Integer, List<Cell>> contents = new HashMap<>(); try(StreamingReader reader = StreamingReader.builder().read(f)) { for(Row row : reader) { contents.put(row.getRowNum(), new ArrayList<Cell>()); for(Cell c : row) { if(c.getColumnIndex() > 0) { contents.get(row.getRowNum()).add(c); } } } } SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); assertThat(contents.size(), equalTo(2)); assertThat(contents.get(0).size(), equalTo(4)); assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14")); assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014"))); assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15")); assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015"))); assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015")); assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015"))); assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05")); assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015"))); assertThat(contents.get(1).size(), equalTo(4)); assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12")); assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312)); assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042")); assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0)); assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12")); assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145)); assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)")); assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0)); } #location 31 #vulnerability type NULL_DEREFERENCE
#fixed code @OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic = false) public static byte[] transformRedefinitions(final Class<?> classBeingRedefined, final byte[] classfileBuffer, final ClassLoader loader) throws IllegalClassFormatException, IOException, RuntimeException { if (NewClassLoaderJavaProxyTransformer.isProxy(classBeingRedefined.getName())) { return NewClassLoaderJavaProxyTransformer.transform(classBeingRedefined, classfileBuffer, loader); } else if (CglibProxyTransformer.isProxy(loader, classBeingRedefined.getName())) { return CglibProxyTransformer.transform(classBeingRedefined, classfileBuffer, loader); } return classfileBuffer; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic = false) public static byte[] transformRedefinitions(final Class<?> classBeingRedefined, final byte[] classfileBuffer, final ClassLoader loader) throws IllegalClassFormatException, IOException, RuntimeException { // load the class in the pool for ClassfileSignatureComparer and JavassistProxyTransformer ClassPool cp = ProxyTransformationUtils.getClassPool(loader); CtClass cc = cp.makeClass(new ByteArrayInputStream(classfileBuffer), false); byte[] result = classfileBuffer; boolean useJavassistProxyTransformer = true; if (useJavassistProxyTransformer) { result = JavassistProxyTransformer.transform(classBeingRedefined, cc, cp, result); } else { result = JavaProxyTransformer.transform(classBeingRedefined, cc, cp, result); } return CglibProxyTransformer.transform(classBeingRedefined, cc, cp, result, loader); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code public static void configureLog(Properties properties) { for (String property : properties.stringPropertyNames()) { if (property.startsWith(LOGGER_PREFIX)) { String classPrefix = getClassPrefix(property); AgentLogger.Level level = getLevel(property, properties.getProperty(property)); if (level != null) { if (classPrefix == null) AgentLogger.setLevel(level); else AgentLogger.setLevel(classPrefix, level); } } else if (property.equals(LOGFILE)) { String logfile = properties.getProperty(LOGFILE); boolean append = parseBoolean(properties.getProperty(LOGFILE_APPEND, "false")); try { PrintStream ps = new PrintStream(new FileOutputStream(new File(logfile), append)); AgentLogger.getHandler().setPrintStream(ps); } catch (FileNotFoundException e) { LOGGER.error("Invalid configuration property {} value '{}'. Unable to create/open the file.", e, LOGFILE, logfile); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void configureLog(Properties properties) { for (String property : properties.stringPropertyNames()) { if (property.startsWith(LOGGER_PREFIX)) { String classPrefix = getClassPrefix(property); AgentLogger.Level level = getLevel(property, properties.getProperty(property)); if (level != null) { if (classPrefix == null) AgentLogger.setLevel(level); else AgentLogger.setLevel(classPrefix, level); } } else if (property.equals(LOGFILE)) { String logfile = properties.getProperty(LOGFILE); try { AgentLogger.getHandler().setPrintStream(new PrintStream(new File(logfile))); } catch (FileNotFoundException e) { LOGGER.error("Invalid configuration property {} value '{}'. Unable to create/open the file.", e, LOGFILE, logfile); } } } } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { // refresh registry try { Class entityManagerFactoryRegistryClazz = loadClass("org.hibernate.ejb.internal.EntityManagerFactoryRegistry"); Object instance = ReflectionHelper.get(null, entityManagerFactoryRegistryClazz, "INSTANCE"); ReflectionHelper.invoke(instance, entityManagerFactoryRegistryClazz, "removeEntityManagerFactory", new Class[] {String.class, EntityManagerFactory.class}, persistenceUnitName, currentInstance); } catch (Exception e) { LOGGER.error("Unable to clear previous instance of entity manager factory"); } buildFreshEntityManagerFactory(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { // refresh registry EntityManagerFactoryRegistry.INSTANCE.removeEntityManagerFactory(persistenceUnitName, currentInstance); // from HibernatePersistence.createContainerEntityManagerFactory() buildFreshEntityManagerFactory(); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void handleError(Session s, Throwable exception) { doSaveExecution(s, session -> { members.unregister(session.getId()); eventBus.post(UNEXPECTED_SITUATION.occurFor(session, exception.getMessage())); } ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void handleError(Session s, Throwable exception) { doSaveExecution(new SessionWrapper(s), session -> { members.unregister(session.getId()); eventBus.post(UNEXPECTED_SITUATION.occurFor(session, exception.getMessage())); } ); } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); server.register(s1); server.register(s2); // when server.handle(Message.create()// .signal("create")// .build(), s1); String conversationKey = s1Matcher.getMessage().getContent(); s1Matcher.reset(); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s2); // then assertThat(s1Matcher.getMessages().size(), is(2)); assertMatch(s1Matcher, 0, "s2", "s1", "joined", EMPTY); assertMatch(s1Matcher, 1, "s2", "s1", "offerRequest", EMPTY); assertThat(s2Matcher.getMessages().size(), is(1)); assertMatch(s2Matcher, 0, EMPTY, "s2", "joined", conversationKey); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); server.register(s1); server.register(s2); // when server.handle(Message.create()// .signal("create")// .build(), s1); String conversationKey = s1Matcher.getMessage().getContent(); s1Matcher.reset(); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s2); // then assertThat(s1Matcher.getMessages().size(), is(2)); assertThat(s1Matcher.getMessage().getFrom(), is("s2")); assertThat(s1Matcher.getMessage().getTo(), is("s1")); assertThat(s1Matcher.getMessage().getSignal(), is("joined")); assertThat(s1Matcher.getMessage(1).getFrom(), is("s2")); assertThat(s1Matcher.getMessage(1).getTo(), is("s1")); assertThat(s1Matcher.getMessage(1).getSignal(), is("offerRequest")); assertThat(s2Matcher.getMessages().size(), is(1)); assertThat(s2Matcher.getMessage().getSignal(), is("joined")); assertThat(s2Matcher.getMessage().getContent(), is(conversationKey)); } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code private void parseProperties(Properties properties) { for (Entry<Object, Object> entry : properties.entrySet()) { String name = (String) entry.getKey(); String value = (String) entry.getValue(); String[] strs = StringUtils.split(value, ','); switch (strs.length) { case 1: createLog(name, strs[0], null, false); break; case 2: if("console".equalsIgnoreCase(strs[1])) { createLog(name, strs[0], null, true); } else { createLog(name, strs[0], strs[1], false); } break; case 3: createLog(name, strs[0], strs[1], "console".equalsIgnoreCase(strs[2])); break; default: System.err.println("The log " + name + " configuration format is illegal. It will use default log configuration"); createLog(name, DEFAULT_LOG_LEVEL, null, false); break; } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void parseProperties(Properties properties) { for (Entry<Object, Object> entry : properties.entrySet()) { String name = (String) entry.getKey(); String value = (String) entry.getValue(); // System.out.println(name + "|" + value); String[] strs = StringUtils.split(value, ','); if (strs.length < 2) { System.err.println("the log configuration file format is illegal"); continue; } String path = strs[1]; FileLog fileLog = new FileLog(); fileLog.setName(name); fileLog.setLevel(LogLevel.fromName(strs[0])); if ("console".equalsIgnoreCase(path)) { fileLog.setFileOutput(false); fileLog.setConsoleOutput(true); } else { File file = new File(path); if(file.exists() && file.isDirectory()) { fileLog.setPath(path); fileLog.setFileOutput(true); } else { boolean success = file.mkdirs(); if(success) { fileLog.setPath(path); fileLog.setFileOutput(true); } else { System.err.println("create directory " + path + " failure"); continue; } } if (strs.length > 2) fileLog.setConsoleOutput("console".equalsIgnoreCase(strs[2])); } logMap.put(name, fileLog); System.out.println("initialize log " + fileLog.toString() + " success"); } } #location 32 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Server receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Fields headers = stream.createFields(); headers.put("response", "ok"); stream.reply(Version.V3, (byte)0, headers); stream.sendLastData("the server has received messages".getBytes()); } }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn((short)3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(barRef); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(carRef); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.Integer>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(parRef); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(sarRef); MethodGenericTypeBind list = getterMap.get("list"); System.out.println(list.getType().getTypeName()); Assert.assertThat(list.getType().getTypeName(), is("java.util.List<java.util.Map<java.lang.String, test.utils.lang.TestGenericTypeReference$Foo>>")); MethodGenericTypeBind sar = getterMap.get("sar"); Assert.assertThat(sar.getType().getTypeName(), is("java.lang.Integer")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Bar<List<String>>>() { }, null); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Car<List<String>>>() { }, null); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Par>() { }, null); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) throws Throwable{ Certificate[] certificates = getCertificates("fireflySSLkeys.jks", "fireflySSLkeys"); for(Certificate certificate : certificates) { System.out.println(certificate); } certificates = getCertificates("fireflykeys", "fireflysource"); for(Certificate certificate : certificates) { System.out.println(certificate); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Throwable { FileInputStream in = null; ByteArrayOutputStream out = null; try { in = new FileInputStream(new File("/Users/qiupengtao", "fireflykeys")); out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; for (int i = 0; (i = in.read(buf)) != -1;) { byte[] temp = new byte[i]; System.arraycopy(buf, 0, temp, 0, i); out.write(temp); } byte[] ret = out.toByteArray(); // System.out.println(ret.length); System.out.println(Arrays.toString(ret)); } finally { in.close(); out.close(); } } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code public static Word2VecModel fromBinFile(File file, ByteOrder byteOrder) throws IOException { try (FileInputStream fis = new FileInputStream(file);) { final FileChannel channel = fis.getChannel(); final long oneGB = 1024 * 1024 * 1024; MappedByteBuffer buffer = channel.map( FileChannel.MapMode.READ_ONLY, 0, Math.min(channel.size(), Integer.MAX_VALUE)); buffer.order(byteOrder); int bufferCount = 1; // Java's NIO only allows memory-mapping up to 2GB. To work around this problem, we re-map // every gigabyte. To calculate offsets correctly, we have to keep track how many gigabytes // we've already skipped. That's what this is for. StringBuilder sb = new StringBuilder(); char c = (char)buffer.get(); while (c != '\n') { sb.append(c); c = (char)buffer.get(); } String firstLine = sb.toString(); int index = firstLine.indexOf(' '); Preconditions.checkState(index != -1, "Expected a space in the first line of file '%s': '%s'", file.getAbsolutePath(), firstLine); final int vocabSize = Integer.parseInt(firstLine.substring(0, index)); final int layerSize = Integer.parseInt(firstLine.substring(index + 1)); logger.info( String.format("Loading %d vectors with dimensionality %d", vocabSize, layerSize)); List<String> vocabs = new ArrayList<String>(vocabSize); double vectors[] = new double[vocabSize * layerSize]; long lastLogMessage = System.currentTimeMillis(); final float[] floats = new float[layerSize]; for (int lineno = 0; lineno < vocabSize; lineno++) { // read vocab sb.setLength(0); c = (char)buffer.get(); while (c != ' ') { // ignore newlines in front of words (some binary files have newline, // some don't) if (c != '\n') { sb.append(c); } c = (char)buffer.get(); } vocabs.add(sb.toString()); // read vector final FloatBuffer floatBuffer = buffer.asFloatBuffer(); floatBuffer.get(floats); for(int i = 0; i < floats.length; ++i) { vectors[lineno * layerSize + i] = floats[i]; } buffer.position(buffer.position() + 4 * layerSize); // print log final long now = System.currentTimeMillis(); if(now - lastLogMessage > 1000) { final double percentage = ((double)(lineno + 1) / (double)vocabSize) * 100.0; logger.info( String.format("Loaded %d/%d vectors (%f%%)", lineno + 1, vocabSize, percentage)); lastLogMessage = now; } // remap file if(buffer.position() > oneGB) { final int newPosition = (int)(buffer.position() - oneGB); final long size = Math.min(channel.size() - oneGB * bufferCount, Integer.MAX_VALUE); logger.debug( String.format( "Remapping for GB number %d. Start: %d, size: %d", bufferCount, oneGB * bufferCount, size)); buffer = channel.map( FileChannel.MapMode.READ_ONLY, oneGB * bufferCount, size); buffer.order(byteOrder); buffer.position(newPosition); bufferCount += 1; } } return new Word2VecModel(vocabs, layerSize, vectors); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Word2VecModel fromBinFile(File file, ByteOrder byteOrder) throws IOException { try (FileInputStream fis = new FileInputStream(file);) { DataInput in = (byteOrder == ByteOrder.BIG_ENDIAN) ? new DataInputStream(fis) : new SwappedDataInputStream(fis); StringBuilder sb = new StringBuilder(); char c = (char) in.readByte(); while (c != '\n') { sb.append(c); c = (char) in.readByte(); } String firstLine = sb.toString(); int index = firstLine.indexOf(' '); Preconditions.checkState(index != -1, "Expected a space in the first line of file '%s': '%s'", file.getAbsolutePath(), firstLine); int vocabSize = Integer.parseInt(firstLine.substring(0, index)); int layerSize = Integer.parseInt(firstLine.substring(index + 1)); List<String> vocabs = Lists.newArrayList(); List<Double> vectors = Lists.newArrayList(); for (int lineno = 0; lineno < vocabSize; lineno++) { sb = new StringBuilder(); c = (char) in.readByte(); while (c != ' ') { // ignore newlines in front of words (some binary files have newline, // some don't) if (c != '\n') { sb.append(c); } c = (char) in.readByte(); } vocabs.add(sb.toString()); for (int i = 0; i < layerSize; i++) { vectors.add((double) in.readFloat()); } } return fromThrift(new Word2VecModelThrift() .setLayerSize(layerSize) .setVocab(vocabs) .setVectors(vectors)); } } #location 44 #vulnerability type RESOURCE_LEAK
#fixed code @Override public Flux<Payload> requestStream(Payload payload) { RSocket service = findRSocket(payload); return service.requestStream(payload); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Flux<Payload> requestStream(Payload payload) { List<String> metadata = getRoutingMetadata(payload); RSocket service = findRSocket(metadata); if (service != null) { return service.requestStream(payload); } MonoProcessor<RSocket> processor = MonoProcessor.create(); this.registry.pendingRequest(metadata, processor); return processor .log("pending-request") .flatMapMany(rSocket -> rSocket.requestStream(payload)); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); // Clear array content directMemoryService.setMemory(arrayIndexStartAddress, arrayIndexScale * length, (byte) 0); primitiveArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); this.primitiveArray = (A) directMemoryService.getObject(allocationStartAddress); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(allocationStartAddress); switch (JvmUtil.getAddressSize()) { case JvmUtil.SIZE_32_BIT: jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder(); break; case JvmUtil.SIZE_64_BIT: int referenceSize = JvmUtil.getReferenceSize(); switch (referenceSize) { case JvmUtil.ADDRESSING_4_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; case JvmUtil.ADDRESSING_8_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; default: throw new AssertionError("Unsupported reference size: " + referenceSize); } break; default: throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize()); } } #location 59 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void objectRetrievedSuccessfullyFromExtendableObjectOffHeapPoolWithDefaultObjectOffHeapPool() { ExtendableObjectOffHeapPool<SampleOffHeapClass> extendableObjectPool = offHeapService.createOffHeapPool( new DefaultExtendableObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>(). elementType(SampleOffHeapClass.class). build()); List<SampleOffHeapClass> objList = new ArrayList<SampleOffHeapClass>(); for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = extendableObjectPool.get(); Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); Assert.assertEquals(i, obj.getOrder()); objList.add(obj); } for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objList.get(i); Assert.assertEquals(i, obj.getOrder()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void objectRetrievedSuccessfullyFromExtendableObjectOffHeapPoolWithDefaultObjectOffHeapPool() { ExtendableObjectOffHeapPool<SampleOffHeapClass> extendableObjectPool = offHeapService.createOffHeapPool( new DefaultExtendableObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>(). elementType(SampleOffHeapClass.class). build()); List<SampleOffHeapClass> objList = new ArrayList<SampleOffHeapClass>(); for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = extendableObjectPool.get(); obj.setOrder(i); objList.add(obj); } for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objList.get(i); Assert.assertEquals(i, obj.getOrder()); } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void init() { super.init(); objectsStartAddress = allocationStartAddress; // Allocated objects must start aligned as address size from start address of allocated address long addressMod = objectsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void init() { super.init(); objectsStartAddress = allocationStartAddress; objectsEndAddress = allocationEndAddress; currentAddress = allocationStartAddress - objectSize; long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = allocationStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; sampleStr = new String(); sampleStrAddress = JvmUtil.addressOf(sampleStr); sampleCharArray = new char[0]; init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType); // All index in object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(arrayStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void init() { super.init(); currentAddress = stringsStartAddress; full = false; currentSegmentIndex = INDEX_NOT_YET_USED; currentSegmentBlockIndex = INDEX_NOT_YET_USED; directMemoryService.setMemory(inUseBlockAddress, inUseBlockCount, (byte)0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void init() { super.init(); currentAddress = stringsStartAddress; full = false; currentIndex = INDEX_NOT_YET_USED; currentBlockIndex = INDEX_NOT_YET_USED; directMemoryService.setMemory(inUseBlockAddress, inUseBlockCount, (byte)0); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private Block doPacking(PocMeetingMember self, PocMeetingRound round) throws NulsException, IOException { Block bestBlock = this.blockService.getBestBlock(); List<Transaction> allTxList = txCacheManager.getTxList(); allTxList.sort(TxTimeComparator.getInstance()); BlockData bd = new BlockData(); bd.setHeight(bestBlock.getHeader().getHeight() + 1); bd.setPreHash(bestBlock.getHeader().getHash()); BlockRoundData roundData = new BlockRoundData(); roundData.setRoundIndex(round.getIndex()); roundData.setConsensusMemberCount(round.getMemberCount()); roundData.setPackingIndexOfRound(self.getPackingIndexOfRound()); roundData.setRoundStartTime(round.getStartTime()); bd.setRoundData(roundData); List<Integer> outTxList = new ArrayList<>(); List<Transaction> packingTxList = new ArrayList<>(); List<NulsDigestData> outHashList = new ArrayList<>(); long totalSize = 0L; for (int i = 0; i < allTxList.size(); i++) { if ((self.getPackEndTime() - TimeService.currentTimeMillis()) <= 500L) { break; } Transaction tx = allTxList.get(i); tx.setBlockHeight(bd.getHeight()); if ((totalSize + tx.size()) >= PocConsensusConstant.MAX_BLOCK_SIZE) { break; } outHashList.add(tx.getHash()); ValidateResult result = tx.verify(); if (result.isFailed()) { Log.error(result.getMessage()); outTxList.add(i); BlockLog.info("discard tx:" + tx.getHash()); continue; } try { ledgerService.approvalTx(tx); } catch (Exception e) { Log.error(e); outTxList.add(i); BlockLog.info("discard tx:" + tx.getHash()); continue; } packingTxList.add(tx); totalSize += tx.size(); confirmingTxCacheManager.putTx(tx); } txCacheManager.removeTx(outHashList); if (totalSize < PocConsensusConstant.MAX_BLOCK_SIZE) { addOrphanTx(packingTxList, totalSize, self, bd.getHeight()); } addConsensusTx(bestBlock, packingTxList, self, round); bd.setTxList(packingTxList); Block newBlock = ConsensusTool.createBlock(bd, round.getLocalPacker()); ValidateResult result = newBlock.verify(); if (result.isFailed()) { BlockLog.warn("packing block error:" + result.getMessage()); for (Transaction tx : newBlock.getTxs()) { ledgerService.rollbackTx(tx); } return null; } return newBlock; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Block doPacking(PocMeetingMember self, PocMeetingRound round) throws NulsException, IOException { Block bestBlock = this.blockService.getBestBlock(); List<Transaction> allTxList = txCacheManager.getTxList(); allTxList.sort(TxTimeComparator.getInstance()); BlockData bd = new BlockData(); bd.setHeight(bestBlock.getHeader().getHeight() + 1); bd.setPreHash(bestBlock.getHeader().getHash()); BlockRoundData roundData = new BlockRoundData(); roundData.setRoundIndex(round.getIndex()); roundData.setConsensusMemberCount(round.getMemberCount()); roundData.setPackingIndexOfRound(self.getPackingIndexOfRound()); roundData.setRoundStartTime(round.getStartTime()); StringBuilder str = new StringBuilder(); str.append(self.getPackingAddress()); str.append(" ,order:" + self.getPackingIndexOfRound()); str.append(",packTime:" + new Date(self.getPackEndTime())); str.append("\n"); BlockLog.debug("pack round:" + str); bd.setRoundData(roundData); List<Integer> outTxList = new ArrayList<>(); List<Transaction> packingTxList = new ArrayList<>(); List<NulsDigestData> outHashList = new ArrayList<>(); long totalSize = 0L; for (int i = 0; i < allTxList.size(); i++) { if ((self.getPackEndTime() - TimeService.currentTimeMillis()) <= 500L) { break; } Transaction tx = allTxList.get(i); tx.setBlockHeight(bd.getHeight()); if ((totalSize + tx.size()) >= PocConsensusConstant.MAX_BLOCK_SIZE) { break; } outHashList.add(tx.getHash()); ValidateResult result = tx.verify(); if (result.isFailed()) { Log.error(result.getMessage()); outTxList.add(i); continue; } try { ledgerService.approvalTx(tx); } catch (Exception e) { Log.error(e); outTxList.add(i); continue; } packingTxList.add(tx); totalSize += tx.size(); confirmingTxCacheManager.putTx(tx); } txCacheManager.removeTx(outHashList); if (totalSize < PocConsensusConstant.MAX_BLOCK_SIZE) { addOrphanTx(packingTxList, totalSize, self,bd.getHeight()); } addConsensusTx(bestBlock, packingTxList, self, round); bd.setTxList(packingTxList); Log.info("txCount:" + packingTxList.size()); Block newBlock = ConsensusTool.createBlock(bd, round.getLocalPacker()); System.out.printf("========height:" + newBlock.getHeader().getHeight() + ",time:" + DateUtil.convertDate(new Date(newBlock.getHeader().getTime())) + ",packEndTime:" + DateUtil.convertDate(new Date(self.getPackEndTime()))); ValidateResult result = newBlock.verify(); if (result.isFailed()) { Log.warn("packing block error:" + result.getMessage()); for (Transaction tx : newBlock.getTxs()) { ledgerService.rollbackTx(tx); } return null; } return newBlock; } #location 63 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code public boolean createQueue(String queueName, long maxSize, int latelySecond) { try { NulsFQueue queue = new NulsFQueue(queueName, maxSize); QueueManager.initQueue(queueName, queue, latelySecond); return true; } catch (Exception e) { Log.error("", e); return false; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean createQueue(String queueName, long maxSize, int latelySecond) { try { InchainFQueue queue = new InchainFQueue(queueName, maxSize); QueueManager.initQueue(queueName, queue, latelySecond); return true; } catch (Exception e) { Log.error("", e); return false; } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void getMemoryTxs() throws Exception { assertNotNull(service); Transaction tx = new TestTransaction(); tx.setTime(0l); assertEquals(tx.getHash().getDigestHex(), "0020c7f397ae78f2c1d12b3edc916e8112bcac576a98444c4c26034c207c9a7ad281"); Result result = service.newTx(tx); assertNotNull(result); assertTrue(result.isSuccess()); assertFalse(result.isFailed()); List<Transaction> memoryTxs = service.getMemoryTxs(); assertNotNull(memoryTxs); assertEquals(1, memoryTxs.size()); tx = memoryTxs.get(0); assertNotNull(tx); assertEquals(tx.getHash().getDigestHex(), "0020c7f397ae78f2c1d12b3edc916e8112bcac576a98444c4c26034c207c9a7ad281"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void getMemoryTxs() throws Exception { assertNotNull(service); Transaction tx = new TestTransaction(); tx.setTime(0l); assertEquals(tx.getHash().getDigestHex(), "08001220d194faf5b314f54c3a299ca9ea086f3f8856c75dc44a1e0c43bcc4d80b47909c"); Result result = service.newTx(tx); assertNotNull(result); assertTrue(result.isSuccess()); assertFalse(result.isFailed()); List<Transaction> memoryTxs = service.getMemoryTxs(); assertNotNull(memoryTxs); assertEquals(1, memoryTxs.size()); tx = memoryTxs.get(0); assertNotNull(tx); assertEquals(tx.getHash().getDigestHex(), "08001220d194faf5b314f54c3a299ca9ea086f3f8856c75dc44a1e0c43bcc4d80b47909c"); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code private void checkIt() { int maxSize = 0; BlockHeaderChain longestChain = null; StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:"); for (BlockHeaderChain chain : chainList) { str.append("+++++++++++\nchain:start-" + chain.getHeaderDigestList().get(0).getHeight() + ", end-" + chain.getHeaderDigestList().get(chain.size() - 1).getHeight()); int listSize = chain.size(); if (maxSize < listSize) { maxSize = listSize; longestChain = chain; } else if (maxSize == listSize) { HeaderDigest hd = chain.getLastHd(); HeaderDigest hd_long = longestChain.getLastHd(); if (hd.getTime() < hd_long.getTime()) { longestChain = chain; } } } if (tempIndex % 10 == 0) { BlockLog.info(str.toString()); tempIndex++; } if (this.approvingChain != null && !this.approvingChain.getId().equals(longestChain.getId())) { BlockService blockService = NulsContext.getServiceBean(BlockService.class); for (int i=approvingChain.size()-1;i>=0;i--) { HeaderDigest hd = approvingChain.getHeaderDigestList().get(i); try { blockService.rollbackBlock(hd.getHash()); } catch (NulsException e) { Log.error(e); } } for(int i=0;i<longestChain.getHeaderDigestList().size();i++){ HeaderDigest hd = longestChain.getHeaderDigestList().get(i); blockService.approvalBlock(hd.getHash()); } } this.approvingChain = longestChain; Set<String> rightHashSet = new HashSet<>(); Set<String> removeHashSet = new HashSet<>(); for (int i = chainList.size() - 1; i >= 0; i--) { BlockHeaderChain chain = chainList.get(i); if (chain.size() < (maxSize - 6)) { removeHashSet.addAll(chain.getHashSet()); this.chainList.remove(chain); } else { rightHashSet.addAll(chain.getHashSet()); } } for (String hash : removeHashSet) { if (!rightHashSet.contains(hash)) { confirmingBlockCacheManager.removeBlock(hash); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void checkIt() { int maxSize = 0; BlockHeaderChain longestChain = null; StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:"); for (BlockHeaderChain chain : chainList) { str.append("+++++++++++\nchain:start-" + chain.getHeaderDigestList().get(0).getHeight() + ", end-" + chain.getHeaderDigestList().get(chain.size() - 1).getHeight()); int listSize = chain.size(); if (maxSize < listSize) { maxSize = listSize; longestChain = chain; } else if (maxSize == listSize) { HeaderDigest hd = chain.getLastHd(); HeaderDigest hd_long = longestChain.getLastHd(); if (hd.getTime() < hd_long.getTime()) { longestChain = chain; } } } if (tempIndex % 10 == 0) { BlockLog.info(str.toString()); tempIndex++; } if (this.approvingChain != null || !this.approvingChain.getId().equals(longestChain.getId())) { BlockService blockService = NulsContext.getServiceBean(BlockService.class); for (int i=approvingChain.size()-1;i>=0;i--) { HeaderDigest hd = approvingChain.getHeaderDigestList().get(i); try { blockService.rollbackBlock(hd.getHash()); } catch (NulsException e) { Log.error(e); } } for(int i=0;i<longestChain.getHeaderDigestList().size();i++){ HeaderDigest hd = longestChain.getHeaderDigestList().get(i); blockService.approvalBlock(hd.getHash()); } } this.approvingChain = longestChain; Set<String> rightHashSet = new HashSet<>(); Set<String> removeHashSet = new HashSet<>(); for (int i = chainList.size() - 1; i >= 0; i--) { BlockHeaderChain chain = chainList.get(i); if (chain.size() < (maxSize - 6)) { removeHashSet.addAll(chain.getHashSet()); this.chainList.remove(chain); } else { rightHashSet.addAll(chain.getHashSet()); } } for (String hash : removeHashSet) { if (!rightHashSet.contains(hash)) { confirmingBlockCacheManager.removeBlock(hash); } } } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code boolean verifyPublicKey(){ //verify the public-KEY-hashes are the same byte[] publicKey = scriptSig.getPublicKey(); byte[] reedmAccount = Utils.sha256hash160(Utils.sha256hash160(publicKey)); if(Arrays.equals(reedmAccount,script.getPublicKeyDigest().getDigestBytes())){ return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean verifyPublicKey(){ //verify the public-KEY-hashes are the same byte[] publicKey = scriptSig.getPublicKey(); NulsDigestData digestData = NulsDigestData.calcDigestData(publicKey,NulsDigestData.DIGEST_ALG_SHA160); if(Arrays.equals(digestData.getDigestBytes(),script.getPublicKeyDigest().getDigestBytes())){ return true; } return false; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override @DbSession public void save(CoinData coinData, Transaction tx) throws NulsException { UtxoData utxoData = (UtxoData) coinData; List<UtxoInputPo> inputPoList = new ArrayList<>(); List<UtxoOutput> spends = new ArrayList<>(); List<UtxoOutputPo> spendPoList = new ArrayList<>(); List<TxAccountRelationPo> txRelations = new ArrayList<>(); Set<String> addressSet = new HashSet<>(); lock.lock(); try { processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet); List<UtxoOutputPo> outputPoList = new ArrayList<>(); for (int i = 0; i < utxoData.getOutputs().size(); i++) { UtxoOutput output = utxoData.getOutputs().get(i); output = ledgerCacheService.getUtxo(output.getKey()); if (output == null) { throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND); } if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) { Log.error("-----------------------------------save() output status is" + output.getStatus().name()); throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo"); } if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); } UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output); outputPoList.add(outputPo); addressSet.add(Address.fromHashs(output.getAddress()).getBase58()); } for (String address : addressSet) { TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address); txRelations.add(relationPo); } outputDataService.updateStatus(spendPoList); inputDataService.save(inputPoList); outputDataService.save(outputPoList); relationDataService.save(txRelations); afterSaveDatabase(spends, utxoData, tx); for (String address : addressSet) { UtxoTransactionTool.getInstance().calcBalance(address, true); } } catch (Exception e) { //rollback // Log.warn(e.getMessage(), e); // for (UtxoOutput output : utxoData.getOutputs()) { // ledgerCacheService.removeUtxo(output.getKey()); // } // for (UtxoOutput spend : spends) { // ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT); // } throw e; } finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @DbSession public void save(CoinData coinData, Transaction tx) throws NulsException { UtxoData utxoData = (UtxoData) coinData; List<UtxoInputPo> inputPoList = new ArrayList<>(); List<UtxoOutput> spends = new ArrayList<>(); List<UtxoOutputPo> spendPoList = new ArrayList<>(); List<TxAccountRelationPo> txRelations = new ArrayList<>(); Set<String> addressSet = new HashSet<>(); try { processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet); List<UtxoOutputPo> outputPoList = new ArrayList<>(); for (int i = 0; i < utxoData.getOutputs().size(); i++) { UtxoOutput output = utxoData.getOutputs().get(i); output = ledgerCacheService.getUtxo(output.getKey()); if (output == null) { throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND); } if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) { Log.error("-----------------------------------save() output status is" + output.getStatus().name()); throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo"); } if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); } UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output); outputPoList.add(outputPo); addressSet.add(Address.fromHashs(output.getAddress()).getBase58()); } for (String address : addressSet) { TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address); txRelations.add(relationPo); } outputDataService.updateStatus(spendPoList); inputDataService.save(inputPoList); outputDataService.save(outputPoList); relationDataService.save(txRelations); afterSaveDatabase(spends, utxoData, tx); for (String address : addressSet) { UtxoTransactionTool.getInstance().calcBalance(address, true); } } catch (Exception e) { //rollback // Log.warn(e.getMessage(), e); // for (UtxoOutput output : utxoData.getOutputs()) { // ledgerCacheService.removeUtxo(output.getKey()); // } // for (UtxoOutput spend : spends) { // ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT); // } throw e; } } #location 37 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void requestTxGroup(NulsDigestData blockHash, String nodeId) { GetTxGroupRequest request = new GetTxGroupRequest(); GetTxGroupParam data = new GetTxGroupParam(); data.setBlockHash(blockHash); List<NulsDigestData> txHashList = new ArrayList<>(); SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex()); for (NulsDigestData txHash : smb.getTxHashList()) { boolean exist = txCacheManager.txExist(txHash); if (!exist) { txHashList.add(txHash); } } if (txHashList.isEmpty()) { BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex()); if (null == header) { return; } Block block = new Block(); block.setHeader(header); List<Transaction> txs = new ArrayList<>(); for (NulsDigestData txHash : smb.getTxHashList()) { Transaction tx = txCacheManager.getTx(txHash); if (null == tx) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } txs.add(tx); } block.setTxs(txs); ValidateResult vResult = block.verify(); if (vResult.isFailed()&&vResult.getErrorCode()!=ErrorCode.ORPHAN_BLOCK&&vResult.getErrorCode()!=ErrorCode.ORPHAN_TX) { return; } blockManager.addBlock(block, false,nodeId); AssembledBlockNotice notice = new AssembledBlockNotice(); notice.setEventBody(header); eventBroadcaster.publishToLocal(notice); return; } data.setTxHashList(txHashList); request.setEventBody(data); tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis()); Integer value = tgRequestCount.get(blockHash.getDigestHex()); if (null == value) { value = 0; } tgRequestCount.put(blockHash.getDigestHex(), 1 + value); if (StringUtils.isBlank(nodeId)) { eventBroadcaster.broadcastAndCache(request, false); } else { eventBroadcaster.sendToNode(request, nodeId); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void requestTxGroup(NulsDigestData blockHash, String nodeId) { GetTxGroupRequest request = new GetTxGroupRequest(); GetTxGroupParam data = new GetTxGroupParam(); data.setBlockHash(blockHash); List<NulsDigestData> txHashList = new ArrayList<>(); SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex()); for (NulsDigestData txHash : smb.getTxHashList()) { boolean exist = txCacheManager.txExist(txHash); if (!exist) { txHashList.add(txHash); } } if (txHashList.isEmpty()) { BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex()); if (null == header) { return; } Block block = new Block(); block.setHeader(header); List<Transaction> txs = new ArrayList<>(); for (NulsDigestData txHash : smb.getTxHashList()) { Transaction tx = txCacheManager.getTx(txHash); if (null == tx) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } txs.add(tx); } block.setTxs(txs); ValidateResult<RedPunishData> vResult = block.verify(); if (null == vResult || vResult.isFailed()) { if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { RedPunishData redPunishData = vResult.getObject(); ConsensusMeetingRunner.putPunishData(redPunishData); } return; } blockManager.addBlock(block, false,nodeId); AssembledBlockNotice notice = new AssembledBlockNotice(); notice.setEventBody(header); eventBroadcaster.publishToLocal(notice); return; } data.setTxHashList(txHashList); request.setEventBody(data); tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis()); Integer value = tgRequestCount.get(blockHash.getDigestHex()); if (null == value) { value = 0; } tgRequestCount.put(blockHash.getDigestHex(), 1 + value); if (StringUtils.isBlank(nodeId)) { eventBroadcaster.broadcastAndCache(request, false); } else { eventBroadcaster.sendToNode(request, nodeId); } } #location 32 #vulnerability type NULL_DEREFERENCE
#fixed code public PocMeetingRound getCurrentRound() { return currentRound; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public PocMeetingRound getCurrentRound() { Block currentBlock = NulsContext.getInstance().getBestBlock(); BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend()); PocMeetingRound round = ROUND_MAP.get(currentRoundData.getRoundIndex()); if (null == round) { round = resetCurrentMeetingRound(); } return round; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void reset() { lock.lock();try{ this.needReSet = true; ROUND_MAP.clear(); this.init();}finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void reset() { this.needReSet = true; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Result saveLocalTx(Transaction tx) { if (tx == null) { return Result.getFailed(KernelErrorCode.NULL_PARAMETER); } byte[] txHashBytes = new byte[0]; try { txHashBytes = tx.getHash().serialize(); } catch (IOException e) { throw new NulsRuntimeException(e); } CoinData coinData = tx.getCoinData(); if (coinData != null) { // delete - from List<Coin> froms = coinData.getFrom(); Set<byte[]> fromsSet = new HashSet<>(); for (Coin from : froms) { byte[] fromSource = from.getOwner(); byte[] utxoFromSource = new byte[tx.getHash().size()]; byte[] fromIndex = new byte[fromSource.length - utxoFromSource.length]; System.arraycopy(fromSource, 0, utxoFromSource, 0, tx.getHash().size()); System.arraycopy(fromSource, tx.getHash().size(), fromIndex, 0, fromIndex.length); Transaction sourceTx = null; try { sourceTx = ledgerService.getTx(NulsDigestData.fromDigestHex(Hex.encode(fromSource))); } catch (Exception e) { throw new NulsRuntimeException(e); } if (sourceTx == null) { return Result.getFailed(AccountLedgerErrorCode.SOURCE_TX_NOT_EXSITS); } byte[] address = sourceTx.getCoinData().getTo().get((int) new VarInt(fromIndex, 0).value).getOwner(); fromsSet.add(org.spongycastle.util.Arrays.concatenate(address, from.getOwner())); } storageService.batchDeleteUTXO(fromsSet); // save utxo - to List<Coin> tos = coinData.getTo(); byte[] indexBytes; Map<byte[], byte[]> toMap = new HashMap<>(); for (int i = 0, length = tos.size(); i < length; i++) { try { byte[] outKey = org.spongycastle.util.Arrays.concatenate(tos.get(i).getOwner(), tx.getHash().serialize(), new VarInt(i).encode()); toMap.put(outKey, tos.get(i).serialize()); } catch (IOException e) { throw new NulsRuntimeException(e); } } storageService.batchSaveUTXO(toMap); } return Result.getSuccess(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Result saveLocalTx(Transaction tx) { if (tx == null) { return Result.getFailed(KernelErrorCode.NULL_PARAMETER); } byte[] txHashBytes = new byte[0]; try { txHashBytes = tx.getHash().serialize(); } catch (IOException e) { throw new NulsRuntimeException(e); } CoinData coinData = tx.getCoinData(); if (coinData != null) { // delete - from List<Coin> froms = coinData.getFrom(); Set<byte[]> fromsSet = new HashSet<>(); for (Coin from : froms) { byte[] fromSource = from.getOwner(); byte[] utxoFromSource = new byte[tx.getHash().size()]; byte[] fromIndex = new byte[fromSource.length - utxoFromSource.length]; System.arraycopy(fromSource, 0, utxoFromSource, 0, tx.getHash().size()); System.arraycopy(fromSource, tx.getHash().size(), fromIndex, 0, fromIndex.length); Transaction sourceTx = null; try { sourceTx = ledgerService.getTx(NulsDigestData.fromDigestHex(Hex.encode(fromSource))); if (sourceTx == null) { sourceTx = getUnconfirmedTransaction(NulsDigestData.fromDigestHex(Hex.encode(fromSource))).getData(); } } catch (Exception e) { throw new NulsRuntimeException(e); } if(sourceTx == null){ return Result.getFailed(); } byte[] address = sourceTx.getCoinData().getTo().get((int) new VarInt(fromIndex, 0).value).getOwner(); fromsSet.add(org.spongycastle.util.Arrays.concatenate(address, from.getOwner())); } storageService.batchDeleteUTXO(fromsSet); // save utxo - to List<Coin> tos = coinData.getTo(); byte[] indexBytes; Map<byte[], byte[]> toMap = new HashMap<>(); for (int i = 0, length = tos.size(); i < length; i++) { try { byte[] outKey = org.spongycastle.util.Arrays.concatenate(tos.get(i).getOwner(), tx.getHash().serialize(), new VarInt(i).encode()); toMap.put(outKey, tos.get(i).serialize()); } catch (IOException e) { throw new NulsRuntimeException(e); } } storageService.batchSaveUTXO(toMap); } return Result.getSuccess(); } #location 46 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public ValidateResult validate(AliasTransaction tx) { Alias alias = tx.getTxData(); if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length != 23) { return ValidateResult.getFailedResult("The address format error"); } if (!StringUtils.validAlias(alias.getAlias())) { return ValidateResult.getFailedResult("The alias is between 3 to 20 characters"); } List<Transaction> txList = getLedgerService().getCacheTxList(TransactionConstant.TX_TYPE_SET_ALIAS); if (txList != null && tx.size() > 0) { for (Transaction trx : txList) { Alias a = ((AliasTransaction) trx).getTxData(); if(alias.getAddress().equals(a.getAlias())) { return ValidateResult.getFailedResult("The alias has been occupied"); } if(alias.getAlias().equals(a.getAlias())){ return ValidateResult.getFailedResult("The alias has been occupied"); } } } AliasPo aliasPo = getAliasDataService().get(alias.getAlias()); if (aliasPo != null) { return ValidateResult.getFailedResult("The alias has been occupied"); } return ValidateResult.getSuccessResult(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ValidateResult validate(AliasTransaction tx) { Alias alias = tx.getTxData(); if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length != 23) { return ValidateResult.getFailedResult("The address format error"); } if (!StringUtils.validAlias(alias.getAlias())) { return ValidateResult.getFailedResult("The alias is between 3 to 20 characters"); } AliasPo aliasPo = getAliasDataService().get(alias.getAlias()); if (aliasPo != null) { return ValidateResult.getFailedResult("The alias has been occupied"); } return ValidateResult.getSuccessResult(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Result<Balance> getBalance(byte[] address) throws NulsException { if (address == null || address.length != AddressTool.HASH_LENGTH) { return Result.getFailed(AccountLedgerErrorCode.PARAMETER_ERROR); } if (!isLocalAccount(address)) { return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST); } Balance balance = balanceManager.getBalance(address).getData(); if (balance == null) { return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST); } return Result.getSuccess().setData(balance); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Result<Balance> getBalance(byte[] address) throws NulsException { if (address == null || address.length != AddressTool.HASH_LENGTH) { return Result.getFailed(AccountLedgerErrorCode.PARAMETER_ERROR); } if (!isLocalAccount(address)) { return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST); } Balance balance = balanceProvider.getBalance(address).getData(); if (balance == null) { return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST); } return Result.getSuccess().setData(balance); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void init() { cacheService = LedgerCacheService.getInstance(); registerService(); ledgerService = NulsContext.getServiceBean(LedgerService.class); coinManager = UtxoCoinManager.getInstance(); UtxoOutputDataService outputDataService = NulsContext.getServiceBean(UtxoOutputDataService.class); coinManager.setOutputDataService(outputDataService); addNormalTxValidator(); this.registerTransaction(TransactionConstant.TX_TYPE_COIN_BASE, CoinBaseTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_TRANSFER, TransferTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_UNLOCK, UnlockNulsTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_LOCK, LockNulsTransaction.class, CoinDataTxService.getInstance()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void init() { cacheService = LedgerCacheService.getInstance(); registerService(); ledgerService = NulsContext.getServiceBean(LedgerService.class); coinManager = UtxoCoinManager.getInstance(); UtxoOutputDataService outputDataService = NulsContext. getServiceBean(UtxoOutputDataService.class); coinManager.setOutputDataService(outputDataService); ledgerService.init(); addNormalTxValidator(); UtxoCoinDataProvider provider = NulsContext.getServiceBean(UtxoCoinDataProvider.class); provider.setInputDataService(NulsContext.getServiceBean(UtxoInputDataService.class)); provider.setOutputDataService(outputDataService); this.registerTransaction(TransactionConstant.TX_TYPE_COIN_BASE, CoinBaseTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_TRANSFER, TransferTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_UNLOCK, UnlockNulsTransaction.class, CoinDataTxService.getInstance()); this.registerTransaction(TransactionConstant.TX_TYPE_LOCK, LockNulsTransaction.class, CoinDataTxService.getInstance()); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void init(Map<String, String> initParams) { String databaseType = null; if(initParams.get("databaseType") != null) { databaseType = initParams.get("databaseType"); } if (!StringUtils.isEmpty(databaseType) && hasType(databaseType)) { String path = "classpath:/database-" + databaseType + ".xml"; NulsContext.setApplicationContext(new ClassPathXmlApplicationContext(new String[]{path}, true, NulsContext.getApplicationContext())); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void init(Map<String, String> initParams) { String dataBaseType = null; if(initParams.get("dataBaseType") != null) { dataBaseType = initParams.get("dataBaseType"); } if (!StringUtils.isEmpty(dataBaseType) && hasType(dataBaseType)) { String path = "classpath:/database-" + dataBaseType + ".xml"; NulsContext.setApplicationContext(new ClassPathXmlApplicationContext(new String[]{path}, true, NulsContext.getApplicationContext())); } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public void forcedLog(String fqcn, Priority level, Object message, Throwable t) { org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString()); Message msg = message instanceof Message ? (ObjectMessage) message : new ObjectMessage(message); logger.log(null, fqcn, lvl, msg, t); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void forcedLog(String fqcn, Priority level, Object message, Throwable t) { org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString()); logger.log(null, fqcn, lvl, new ObjectMessage(message), t); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @BeforeClass public static void setUpClass() throws Exception { // TODO: refactor PluginManager.decode() into this module? pluginCategories = new ConcurrentHashMap<String, ConcurrentMap<String, PluginEntry>>(); final Enumeration<URL> resources = PluginProcessor.class.getClassLoader().getResources(CACHE_FILE); while (resources.hasMoreElements()) { final URL url = resources.nextElement(); final DataInputStream in = new DataInputStream(new BufferedInputStream(url.openStream())); try { final int count = in.readInt(); for (int i = 0; i < count; i++) { final String category = in.readUTF(); pluginCategories.putIfAbsent(category, new ConcurrentHashMap<String, PluginEntry>()); final ConcurrentMap<String, PluginEntry> m = pluginCategories.get(category); final int entries = in.readInt(); for (int j = 0; j < entries; j++) { final PluginEntry entry = new PluginEntry(); entry.setKey(in.readUTF()); entry.setClassName(in.readUTF()); entry.setName(in.readUTF()); entry.setPrintable(in.readBoolean()); entry.setDefer(in.readBoolean()); entry.setCategory(category); m.putIfAbsent(entry.getKey(), entry); } pluginCategories.putIfAbsent(category, m); } } finally { in.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @BeforeClass public static void setUpClass() throws Exception { // TODO: refactor PluginManager.decode() into this module? pluginCategories = new ConcurrentHashMap<String, ConcurrentMap<String, PluginEntry>>(); final Enumeration<URL> resources = PluginProcessor.class.getClassLoader().getResources(CACHE_FILE); while (resources.hasMoreElements()) { final URL url = resources.nextElement(); final ObjectInput in = new ObjectInputStream(new BufferedInputStream(url.openStream())); try { final int count = in.readInt(); for (int i = 0; i < count; i++) { final String category = in.readUTF(); pluginCategories.putIfAbsent(category, new ConcurrentHashMap<String, PluginEntry>()); final ConcurrentMap<String, PluginEntry> m = pluginCategories.get(category); final int entries = in.readInt(); for (int j = 0; j < entries; j++) { final PluginEntry entry = new PluginEntry(); entry.setKey(in.readUTF()); entry.setClassName(in.readUTF()); entry.setName(in.readUTF()); entry.setPrintable(in.readBoolean()); entry.setDefer(in.readBoolean()); entry.setCategory(category); m.putIfAbsent(entry.getKey(), entry); } pluginCategories.putIfAbsent(category, m); } } finally { in.close(); } } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code static void reportResult(final String file, final String name, final Histogram histogram) throws IOException { final String result = createSamplingReport(name, histogram); println(result); if (file != null) { final FileWriter writer = new FileWriter(file, true); try { writer.write(result); writer.write(System.getProperty("line.separator")); } finally { writer.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static void reportResult(final String file, final String name, final Histogram histogram) throws IOException { final String result = createSamplingReport(name, histogram); println(result); if (file != null) { final FileWriter writer = new FileWriter(file, true); writer.write(result); writer.write(System.getProperty("line.separator")); writer.close(); } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Override protected void releaseSub() { if (rpcClient != null) { try { rpcClient.close(); } catch (final Exception ex) { LOGGER.error("Attempt to close RPC client failed", ex); } } rpcClient = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void releaseSub() { if (transceiver != null) { try { transceiver.close(); } catch (final IOException ioe) { LOGGER.error("Attempt to clean up Avro transceiver failed", ioe); } } client = null; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public byte[] toByteArray(final LogEvent event) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new PrivateObjectOutputStream(baos); try { oos.writeObject(event); } finally { oos.close(); } } catch (IOException ioe) { LOGGER.error("Serialization of LogEvent failed.", ioe); } return baos.toByteArray(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public byte[] toByteArray(final LogEvent event) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new PrivateObjectOutputStream(baos); oos.writeObject(event); } catch (IOException ioe) { LOGGER.error("Serialization of LogEvent failed.", ioe); } return baos.toByteArray(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void format(final LogEvent event, final StringBuilder toAppendTo) { final long timestamp = event.getTimeMillis(); toAppendTo.append(timestamp - startTime); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void format(final LogEvent event, final StringBuilder toAppendTo) { final long timestamp = event.getTimeMillis(); synchronized (this) { if (timestamp != lastTimestamp) { lastTimestamp = timestamp; relative = Long.toString(timestamp - startTime); } } toAppendTo.append(relative); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected ConfigurationSource getInputFromString(final String config, final ClassLoader loader) { try { final URL url = new URL(config); return new ConfigurationSource(url.openStream(), FileUtils.fileFromUri(url.toURI())); } catch (final Exception ex) { final ConfigurationSource source = getInputFromResource(config, loader); if (source == null) { try { final File file = new File(config); return new ConfigurationSource(new FileInputStream(file), file); } catch (final FileNotFoundException fnfe) { // Ignore the exception LOGGER.catching(Level.DEBUG, fnfe); } } return source; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected ConfigurationSource getInputFromString(final String config, final ClassLoader loader) { try { final URL url = new URL(config); return new ConfigurationSource(url.openStream(), FileUtils.fileFromURI(url.toURI())); } catch (final Exception ex) { final ConfigurationSource source = getInputFromResource(config, loader); if (source == null) { try { final File file = new File(config); return new ConfigurationSource(new FileInputStream(file), file); } catch (final FileNotFoundException fnfe) { // Ignore the exception LOGGER.catching(Level.DEBUG, fnfe); } } return source; } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testTcpAppenderDeadlock() throws Exception { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .withHost("localhost") .withPort(DYN_PORT) .withReconnectDelayMillis(100) .withName("test") .withImmediateFail(false) .build(); // @formatter:on appender.start(); // set appender on root and set level to debug root.addAppender(appender); root.setAdditive(false); root.setLevel(Level.DEBUG); final TCPSocketServer tcpSocketServer = new TCPSocketServer(DYN_PORT); try { tcpSocketServer.start(); root.debug("This message is written because a deadlock never."); final LogEvent event = tcpSocketServer.getQueue().poll(3, TimeUnit.SECONDS); assertNotNull("No event retrieved", event); } finally { tcpSocketServer.shutdown(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testTcpAppenderDeadlock() throws Exception { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .withHost("localhost") .withPort(DYN_PORT) .withReconnectDelayMillis(100) .withName("test") .withImmediateFail(false) .build(); // @formatter:on appender.start(); // set appender on root and set level to debug root.addAppender(appender); root.setAdditive(false); root.setLevel(Level.DEBUG); new TCPSocketServer(DYN_PORT).start(); root.debug("This message is written because a deadlock never."); final LogEvent event = list.poll(3, TimeUnit.SECONDS); assertNotNull("No event retrieved", event); } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testAppender() throws Exception { final Logger logger = ctx.getLogger(); // Trigger the rollover for (int i = 0; i < 10; ++i) { // 30 chars per message: each message triggers a rollover logger.debug("This is a test message number " + i); // 30 chars: } Thread.sleep(100); // Allow time for rollover to complete final File dir = new File(DIR); assertTrue("Dir " + DIR + " should exist", dir.exists()); assertTrue("Dir " + DIR + " should contain files", dir.listFiles().length > 0); final int MAX_TRIES = 20; for (int i = 0; i < MAX_TRIES; i++) { final File[] files = dir.listFiles(); for (File file : files) { System.out.println(file); } if (files.length == 3) { for (File file : files) { assertTrue("test-4.log should have been deleted", Arrays.asList("test-1.log", "test-2.log", "test-3.log").contains(file.getName())); } return; // test succeeded } logger.debug("Adding additional event " + i); Thread.sleep(100); // Allow time for rollover to complete } fail("No rollover files found"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAppender() throws Exception { final Logger logger = ctx.getLogger(); // Trigger the rollover for (int i = 0; i < 10; ++i) { // 30 chars per message: each message triggers a rollover logger.debug("This is a test message number " + i); // 30 chars: } Thread.sleep(100); // Allow time for rollover to complete final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final int MAX_TRIES = 20; for (int i = 0; i < MAX_TRIES; i++) { final File[] files = dir.listFiles(); for (File file : files) { System.out.println(file); } if (files.length == 3) { for (File file : files) { assertTrue("test-4.log.gz should have been deleted", Arrays.asList("test-1.log.gz", "test-2.log.gz", "test-3.log.gz").contains(file.getName())); } return; // test succeeded } logger.debug("Adding additional event " + i); Thread.sleep(100); // Allow time for rollover to complete } fail("No rollover files found"); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void format(final LogEvent event, final StringBuilder output) { final long timestamp = event.getMillis(); synchronized (this) { if (timestamp != lastTimestamp) { lastTimestamp = timestamp; cachedDateString = simpleFormat.format(timestamp); } } output.append(cachedDateString); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void format(final LogEvent event, final StringBuilder output) { final long timestamp = event.getMillis(); synchronized (this) { if (timestamp != lastTimestamp) { lastTimestamp = timestamp; cachedDate = simpleFormat.format(timestamp); } } output.append(cachedDate); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static String[] readFile(String file) { List<String> result = new ArrayList<String>(); System.out.println("readFile(" + file + ")"); try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } result.add(str); } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return result.toArray(new String[result.size()]); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String[] readFile(String file) { List<String> result = new ArrayList<String>(); System.out.println("readFile(" + file + ")"); try { BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } result.add(str); } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return result.toArray(new String[result.size()]); } #location 27 #vulnerability type RESOURCE_LEAK
#fixed code public static String[] readFile(String file) { List<String> result = new ArrayList<String>(); System.out.println("readFile(" + file + ")"); try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } result.add(str); } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return result.toArray(new String[result.size()]); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String[] readFile(String file) { List<String> result = new ArrayList<String>(); System.out.println("readFile(" + file + ")"); try { BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } result.add(str); } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return result.toArray(new String[result.size()]); } #location 27 #vulnerability type RESOURCE_LEAK
#fixed code private void commonInitialization(IntVar[] list, int[] weights, int sum) { queueIndex = 4; assert (list.length == weights.length) : "\nLength of two vectors different in SumWeightDom"; numberArgs = (short) (list.length + 1); numberId = idNumber.incrementAndGet(); this.sum = sum; HashMap<IntVar, Integer> parameters = new HashMap<IntVar, Integer>(); for (int i = 0; i < list.length; i++) { assert (list[i] != null) : i + "-th element of list in SumWeightDom constraint is null"; if (weights[i] == 0) continue; if (parameters.get(list[i]) != null) { // variable ordered in the scope of the Sum Weight constraint. Integer coeff = parameters.get(list[i]); Integer sumOfCoeff = coeff + weights[i]; parameters.put(list[i], sumOfCoeff); } else parameters.put(list[i], weights[i]); } this.list = new IntVar[parameters.size()]; this.weights = new int[parameters.size()]; int i = 0; for (Map.Entry<IntVar,Integer> e : parameters.entrySet()) { this.list[i] = e.getKey(); this.weights[i] = e.getValue(); i++; } checkForOverflow(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void commonInitialization(IntVar[] list, int[] weights, int sum) { queueIndex = 4; assert (list.length == weights.length) : "\nLength of two vectors different in SumWeightDom"; numberArgs = (short) (list.length + 1); numberId = idNumber.incrementAndGet(); this.sum = sum; HashMap<IntVar, Integer> parameters = new HashMap<IntVar, Integer>(); for (int i = 0; i < list.length; i++) { assert (list[i] != null) : i + "-th element of list in SumWeightDom constraint is null"; if (weights[i] == 0) continue; if (parameters.get(list[i]) != null) { // variable ordered in the scope of the Sum Weight constraint. Integer coeff = parameters.get(list[i]); Integer sumOfCoeff = coeff + weights[i]; parameters.put(list[i], sumOfCoeff); } else parameters.put(list[i], weights[i]); } this.list = new IntVar[parameters.size()]; this.weights = new int[parameters.size()]; int i = 0; for (IntVar var : parameters.keySet()) { this.list[i] = var; this.weights[i] = parameters.get(var); i++; } checkForOverflow(); } #location 38 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testLocking() { // a page long start = System.nanoTime(); final DirectStore store1 = DirectStore.allocate(1 << 12); final int lockCount = 20 * 1000 * 1000; new Thread(new Runnable() { @Override public void run() { manyToggles(store1, lockCount, 1, 0); } }).start(); manyToggles(store1, lockCount, 0, 1); store1.free(); long time = System.nanoTime() - start; System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testLocking() throws Exception { // a page long start = System.nanoTime(); final DirectStore store1 = DirectStore.allocate(1 << 12); final int lockCount = 20 * 1000000; Thread t = new Thread(new Runnable() { @Override public void run() { long id = Thread.currentThread().getId(); System.out.println("Thread " + id); assertEquals(0, id >>> 24); try { DirectBytes slice1 = store1.createSlice(); for (int i = 0; i < lockCount; i++) { slice1.busyLockInt(0); int toggle1 = slice1.readInt(4); if (toggle1 == 1) { slice1.writeInt(4, 0); } else { i--; } slice1.unlockInt(0); } } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); long id = Thread.currentThread().getId(); assertEquals(0, id >>> 24); System.out.println("Thread " + id); DirectBytes slice1 = store1.createSlice(); for (int i = 0; i < lockCount; i++) { slice1.busyLockInt(0); int toggle1 = slice1.readInt(4); if (toggle1 == 0) { slice1.writeInt(4, 1); } else { i--; } slice1.unlockInt(0); } store1.free(); long time = System.nanoTime() - start; System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time)); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testLocking() throws Exception { // a page long start = System.nanoTime(); final DirectStore store1 = DirectStore.allocate(1 << 12); final int lockCount = 20 * 1000000; Thread t = new Thread(new Runnable() { @Override public void run() { long id = Thread.currentThread().getId(); System.out.println("Thread " + id); assertEquals(0, id >>> 24); try { DirectBytes slice1 = store1.createSlice(); for (int i = 0; i < lockCount; i++) { slice1.busyLockInt(0); int toggle1 = slice1.readInt(4); if (toggle1 == 1) { slice1.writeInt(4, 0); } else { i--; } slice1.unlockInt(0); } } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); long id = Thread.currentThread().getId(); assertEquals(0, id >>> 24); System.out.println("Thread " + id); DirectBytes slice1 = store1.createSlice(); for (int i = 0; i < lockCount; i++) { slice1.busyLockInt(0); int toggle1 = slice1.readInt(4); if (toggle1 == 0) { slice1.writeInt(4, 1); } else { i--; } slice1.unlockInt(0); } store1.free(); long time = System.nanoTime() - start; System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testLocking() throws Exception { // a page final DirectStore store1 = DirectStore.allocate(1 << 12); final DirectStore store2 = DirectStore.allocate(1 << 12); final int lockCount = 10 * 1000000; Thread t = new Thread(new Runnable() { @Override public void run() { long id = Thread.currentThread().getId(); System.out.println("Thread " + id); assertEquals(0, id >>> 24); int expected = (1 << 24) | (int) id; try { DirectBytes slice1 = store1.createSlice(); DirectBytes slice2 = store2.createSlice(); for (int i = 0; i < lockCount; i += 2) { slice1.busyLockInt(0); slice2.busyLockInt(0); int lockValue1 = slice1.readInt(0); if (lockValue1 != expected) assertEquals(expected, lockValue1); int lockValue2 = slice2.readInt(0); if (lockValue2 != expected) assertEquals(expected, lockValue2); int toggle1 = slice1.readInt(4); if (toggle1 == 1) { slice1.writeInt(4, 0); // if (i % 10000== 0) // System.out.println("t: " + i); } else { i--; } int toggle2 = slice2.readInt(4); if (toggle2 == 1) { slice2.writeInt(4, 0); // if (i % 10000== 0) // System.out.println("t: " + i); } else { i--; } int lockValue1A = slice1.readInt(0); int lockValue2A = slice1.readInt(0); try { slice2.unlockInt(0); slice1.unlockInt(0); } catch (IllegalStateException e) { int lockValue1B = slice1.readInt(0); int lockValue2B = slice2.readInt(0); System.err.println("i= " + i + " lock: " + Integer.toHexString(lockValue1A) + " / " + Integer.toHexString(lockValue2A) + " lock: " + Integer.toHexString(lockValue1B) + " / " + Integer.toHexString(lockValue2B)); throw e; } } } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); long id = Thread.currentThread().getId(); assertEquals(0, id >>> 24); int expected = (1 << 24) | (int) id; System.out.println("Thread " + id); DirectBytes slice1 = store1.createSlice(); DirectBytes slice2 = store2.createSlice(); for (int i = 0; i < lockCount; i += 2) { slice1.busyLockInt(0); slice2.busyLockInt(0); int lockValue1 = slice1.readInt(0); if (lockValue1 != expected) assertEquals(expected, lockValue1); int lockValue2 = slice2.readInt(0); if (lockValue2 != expected) assertEquals(expected, lockValue2); int toggle1 = slice1.readInt(4); if (toggle1 == 0) { slice1.writeInt(4, 1); // if (i % 10000== 0) // System.out.println("t: " + i); } else { i--; } int toggle2 = slice2.readInt(4); if (toggle2 == 0) { slice2.writeInt(4, 1); // if (i % 10000== 0) // System.out.println("t: " + i); } else { i--; } int lockValue1A = slice1.readInt(0); int lockValue2A = slice1.readInt(0); try { slice2.unlockInt(0); slice1.unlockInt(0); } catch (IllegalStateException e) { int lockValue1B = slice1.readInt(0); int lockValue2B = slice2.readInt(0); System.err.println("i= " + i + " lock: " + Integer.toHexString(lockValue1A) + " / " + Integer.toHexString(lockValue2A) + " lock: " + Integer.toHexString(lockValue1B) + " / " + Integer.toHexString(lockValue2B)); throw e; } } store1.free(); store2.free(); } #location 51 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testAllocate() throws Exception { long size = 1L << 24; // 31; don't overload cloud-bees DirectStore store = DirectStore.allocate(size); assertEquals(size, store.size()); DirectBytes slice = store.bytes(); slice.positionAndSize(0, size); slice.writeLong(0, size); slice.writeLong(size - 8, size); store.free(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAllocate() throws Exception { long size = 1L << 24; // 31; don't overload cloud-bees DirectStore store = DirectStore.allocate(size); assertEquals(size, store.size()); DirectBytes slice = store.createSlice(); slice.positionAndSize(0, size); slice.writeLong(0, size); slice.writeLong(size - 8, size); store.free(); } #location 11 #vulnerability type RESOURCE_LEAK