instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String load(String filename) { byte[] bytes = loadBytes(filename); return bytes != null ? new String(bytes) : null; }
#vulnerable code public static String load(String filename) { return new String(loadBytes(filename)); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shouldParseRequest1() { RapidoidHelper req = parse(REQ1); BufGroup bufs = new BufGroup(2); Buf reqbuf = bufs.from(REQ1, "r2"); eq(REQ1, req.verb, "GET"); eq(REQ1, req.path, "/foo/bar"); eqs(REQ1, req.params, "a", "5", "b", "", "n", "%20"); eq(req.params.toMap(reqbuf, true, true, false), U.map("a", "5", "b", "", "n", " ")); eq(REQ1, req.protocol, "HTTP/1.1"); eqs(REQ1, req.headersKV, "Host", "www.test.com", "Set-Cookie", "aaa=2"); isNone(req.body); }
#vulnerable code @Test public void shouldParseRequest1() { ReqData req = parse(REQ1); BufGroup bufs = new BufGroup(2); Buf reqbuf = bufs.from(REQ1, "r2"); eq(REQ1, req.rVerb, "GET"); eq(REQ1, req.rPath, "/foo/bar"); eqs(REQ1, req.params, "a", "5", "b", "", "n", "%20"); eq(req.params.toMap(reqbuf, true, true, false), U.map("a", "5", "b", "", "n", " ")); eq(REQ1, req.rProtocol, "HTTP/1.1"); eqs(REQ1, req.headersKV, "Host", "www.test.com", "Set-Cookie", "aaa=2"); isNone(req.rBody); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void generateIndex(String path) { System.out.println(); System.out.println(); System.out.println("*************** " + path); System.out.println(); System.out.println(); List<Map<String, ?>> examplesl = U.list(); IntWrap nl = new IntWrap(); List<String> eglistl = IO.loadLines("examplesl.txt"); processAll(examplesl, nl, eglistl); List<Map<String, ?>> examplesh = U.list(); IntWrap nh = new IntWrap(); List<String> eglisth = IO.loadLines("examplesh.txt"); processAll(examplesh, nh, eglisth); Map<String, ?> model = U.map("examplesh", examplesh, "examplesl", examplesl, "version", UTILS.version() .replace("-SNAPSHOT", "")); String html = Templates.fromFile("docs.html").render(model); IO.save(path + "index.html", html); }
#vulnerable code private static void generateIndex(String path) { System.out.println(); System.out.println(); System.out.println("*************** " + path); System.out.println(); System.out.println(); List<Map<String, ?>> examples = U.list(); IntWrap nn = new IntWrap(); List<String> eglist = IO.loadLines("examples.txt"); List<String> processed = processAll(examples, nn, eglist); System.out.println("Processed: " + processed); Map<String, ?> model = U.map("examples", examples); String html = Templates.fromFile("docs.html").render(model); IO.save(path + "index.html", html); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void doProcessing() { long now = U.time(); int connectingN = connecting.size(); for (int i = 0; i < connectingN; i++) { ConnectionTarget target = connecting.poll(); assert target != null; if (target.retryAfter < now) { Log.debug("connecting", "address", target.addr); try { SelectionKey newKey = target.socketChannel.register(selector, SelectionKey.OP_CONNECT); newKey.attach(target); } catch (ClosedChannelException e) { Log.warn("Closed channel", e); } } else { connecting.add(target); } } RapidoidChannel channel; while ((channel = connected.poll()) != null) { SocketChannel socketChannel = channel.socketChannel; Log.debug("connected", "address", socketChannel.socket().getRemoteSocketAddress()); try { SelectionKey newKey = socketChannel.register(selector, SelectionKey.OP_READ); U.notNull(channel.protocol, "protocol"); RapidoidConnection conn = attachConn(newKey, channel.protocol); conn.setClient(channel.isClient); try { processNext(conn, true); } finally { conn.setInitial(false); } } catch (ClosedChannelException e) { Log.warn("Closed channel", e); } } RapidoidConnection restartedConn; while ((restartedConn = restarting.poll()) != null) { Log.debug("restarting", "connection", restartedConn); processNext(restartedConn, true); } synchronized (done) { for (int i = 0; i < done.size(); i++) { RapidoidConnection conn = done.get(i); if (conn.key != null && conn.key.isValid()) { conn.key.interestOps(SelectionKey.OP_WRITE); } } done.clear(); } }
#vulnerable code @Override protected void doProcessing() { long now = U.time(); int connectingN = connecting.size(); for (int i = 0; i < connectingN; i++) { ConnectionTarget target = connecting.poll(); assert target != null; if (target.retryAfter < now) { Log.debug("connecting", "address", target.addr); try { SelectionKey newKey = target.socketChannel.register(selector, SelectionKey.OP_CONNECT); newKey.attach(target); } catch (ClosedChannelException e) { Log.warn("Closed channel", e); } } else { connecting.add(target); } } RapidoidChannel channel; while ((channel = connected.poll()) != null) { SocketChannel socketChannel = channel.socketChannel; Log.debug("connected", "address", socketChannel.socket().getRemoteSocketAddress()); try { SelectionKey newKey = socketChannel.register(selector, SelectionKey.OP_READ); RapidoidConnection conn = attachConn(newKey, channel.protocol); conn.setClient(channel.isClient); try { processNext(conn, true); } finally { conn.setInitial(false); } } catch (ClosedChannelException e) { Log.warn("Closed channel", e); } } RapidoidConnection restartedConn; while ((restartedConn = restarting.poll()) != null) { Log.debug("restarting", "connection", restartedConn); processNext(restartedConn, true); } synchronized (done) { for (int i = 0; i < done.size(); i++) { RapidoidConnection conn = done.get(i); if (conn.key != null && conn.key.isValid()) { conn.key.interestOps(SelectionKey.OP_WRITE); } } done.clear(); } } #location 38 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean handleError(Channel channel, boolean isKeepAlive, ReqImpl req, MediaType contentType, Throwable e) { if (req != null) { if (!req.isStopped()) { try { HttpIO.errorAndDone(req, e); } catch (Exception e1) { Log.error("HTTP error handler error!", e1); internalServerError(channel, isKeepAlive, req, contentType); } } return true; } else { Log.error("Low-level HTTP handler error!", e); internalServerError(channel, isKeepAlive, req, contentType); } return false; }
#vulnerable code private boolean handleError(Channel channel, boolean isKeepAlive, ReqImpl req, MediaType contentType, Throwable e) { if (req != null) { if (!req.isStopped()) { HttpIO.errorAndDone(req, e); } return true; } else { Log.error("Low-level HTTP handler error!", e); HttpIO.startResponse(channel, 500, isKeepAlive, contentType); byte[] bytes = HttpUtils.responseToBytes(req, "Internal Server Error!", contentType, routes()[0].custom().jsonResponseRenderer()); HttpIO.writeContentLengthAndBody(channel, bytes); HttpIO.done(channel, isKeepAlive); } return false; } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public int hashCode() { int result = Arrays.hashCode(packages); result = 31 * result + (matching != null ? matching.hashCode() : 0); result = 31 * result + Arrays.hashCode(annotated); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); result = 31 * result + Arrays.hashCode(classpath); result = 31 * result + (bytecodeFilter != null ? bytecodeFilter.hashCode() : 0); return result; }
#vulnerable code @Override public int hashCode() { int result = Arrays.hashCode(packages); result = 31 * result + (matching != null ? matching.hashCode() : 0); result = 31 * result + Arrays.hashCode(annotated); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); return result; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static <T> void invokePostConstruct(T target) { List<Method> methods = Cls.getMethodsAnnotated(target.getClass(), Init.class); for (Method method : methods) { Cls.invoke(method, target); } }
#vulnerable code private static <T> void invokePostConstruct(T target) { List<Method> methods = Cls.getMethodsAnnotated(target.getClass(), Init.class); for (Method method : methods) { Cls.invoke(null, method, target); } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object getParamValue(Req req, Class<?> paramType, String paramName, Map<String, Object> properties) throws Exception { return Customization.of(req).jackson().convertValue(properties, paramType); }
#vulnerable code @Override public Object getParamValue(Req req, Class<?> paramType, String paramName, Map<String, Object> properties) throws Exception { return req.custom().jackson().convertValue(properties, paramType); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScanParams that = (ScanParams) o; if (!Arrays.equals(packages, that.packages)) return false; if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false; if (!Arrays.equals(annotated, that.annotated)) return false; if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false; if (!Arrays.equals(classpath, that.classpath)) return false; return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null; }
#vulnerable code @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScanParams that = (ScanParams) o; if (!Arrays.equals(packages, that.packages)) return false; if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false; if (!Arrays.equals(annotated, that.annotated)) return false; return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null; } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") public static WebApp bootstrap(WebApp app, String[] args, Object... config) { Log.info("Starting Rapidoid...", "version", RapidoidInfo.version()); ConfigHelp.processHelp(args); // FIXME make optional // print internal state // LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); Conf.init(args, config); Log.info("Working directory is: " + System.getProperty("user.dir")); inferAndSetRootPackage(); if (app == null) { app = AppTool.createRootApp(); } registerDefaultPlugins(); Set<String> configArgs = U.set(args); for (Object arg : config) { processArg(configArgs, arg); } String[] configArgsArr = configArgs.toArray(new String[configArgs.size()]); Conf.args(configArgsArr); Log.args(configArgsArr); AOP.reset(); AOP.intercept(new AuthInterceptor(), Admin.class, Manager.class, Moderator.class, LoggedIn.class, DevMode.class, Role.class, HasRole.class); return app; }
#vulnerable code @SuppressWarnings("unchecked") public static WebApp bootstrap(WebApp app, String[] args, Object... config) { Log.info("Starting Rapidoid...", "version", RapidoidInfo.version()); ConfigHelp.processHelp(args); // FIXME make optional // print internal state // LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); Conf.init(args, config); Log.info("Working directory is: " + System.getProperty("user.dir")); inferAndSetRootPackage(); if (app == null) { app = AppTool.createRootApp(); } registerDefaultPlugins(); Set<String> configArgs = U.set(args); for (Object arg : config) { processArg(configArgs, arg); } String[] configArgsArr = configArgs.toArray(new String[configArgs.size()]); Conf.args(configArgsArr); Log.args(configArgsArr); AOP.reset(); AOP.intercept(new AuthInterceptor(), Admin.class, Manager.class, Moderator.class, LoggedIn.class, DevMode.class, Role.class, HasRole.class); return app; } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean handleError(Channel channel, boolean isKeepAlive, ReqImpl req, MediaType contentType, Throwable e) { if (req != null) { if (!req.isStopped()) { HttpIO.errorAndDone(req, e); } return true; } else { Log.error("Low-level HTTP handler error!", e); HttpIO.startResponse(channel, 500, isKeepAlive, contentType); byte[] bytes = HttpUtils.responseToBytes(req, "Internal Server Error!", contentType, routes()[0].custom().jsonResponseRenderer()); HttpIO.writeContentLengthAndBody(channel, bytes); HttpIO.done(channel, isKeepAlive); } return false; }
#vulnerable code private boolean handleError(Channel channel, boolean isKeepAlive, ReqImpl req, MediaType contentType, Throwable e) { if (req != null) { if (!req.isStopped()) { HttpIO.errorAndDone(req, e, customization.errorHandler()); } return true; } else { Log.error("Low-level HTTP handler error!", e); HttpIO.startResponse(channel, 500, isKeepAlive, contentType); byte[] bytes = HttpUtils.responseToBytes(req, "Internal Server Error!", contentType, routes()[0].custom().jsonResponseRenderer()); HttpIO.writeContentLengthAndBody(channel, bytes); HttpIO.done(channel, isKeepAlive); } return false; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void setRootPath(String rootPath) { Log.info("Setting 'root' application path", "path", rootPath); Conf.rootPath = cleanPath(rootPath); setStaticPath(Conf.rootPath + "/static"); setDynamicPath(Conf.rootPath + "/dynamic"); setConfigPath(Conf.rootPath); }
#vulnerable code public static void setRootPath(String rootPath) { Log.info("Setting 'root' application path", "path", rootPath); Conf.rootPath = cleanPath(rootPath); setStaticPath(Conf.rootPath + "/static"); setDynamicPath(Conf.rootPath + "/dynamic"); setConfigPath(Conf.rootPath); setTemplatesPath(Conf.rootPath + "/templates"); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static List<Class<?>> getClassesFromJAR(String jarName, List<Class<?>> classes, String pkg, Pattern regex, Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) { ZipInputStream zip = null; try { String pkgPath = pkgToPath(pkg); File jarFile = new File(jarName); FileInputStream jarInputStream = new FileInputStream(jarFile); zip = new ZipInputStream(jarInputStream); ZipEntry e; while ((e = zip.getNextEntry()) != null) { if (!e.isDirectory()) { String name = e.getName(); if (!ignore(name)) { if (U.isEmpty(pkg) || name.startsWith(pkgPath)) { scanFile(classes, regex, filter, annotated, classLoader, name); } } } } } catch (Exception e) { Log.error("Cannot scan JAR: " + jarName, e); } finally { if (zip != null) { try { zip.close(); } catch (IOException e) { Log.error("Couldn't close the ZIP stream!", e); } } } return classes; }
#vulnerable code private static List<Class<?>> getClassesFromJAR(String jarName, List<Class<?>> classes, String pkg, Pattern regex, Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) { try { String pkgPath = pkgToPath(pkg); ZipInputStream zip = new ZipInputStream(new URL("file://" + jarName).openStream()); ZipEntry e; while ((e = zip.getNextEntry()) != null) { if (!e.isDirectory()) { String name = e.getName(); if (!ignore(name)) { if (U.isEmpty(pkg) || name.startsWith(pkgPath)) { scanFile(classes, regex, filter, annotated, classLoader, name); } } } } } catch (Exception e) { throw U.rte(e); } return classes; } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static DivTag field(FormLayout layout, String name, String desc, FieldType type, Object[] options, Object value) { desc = U.or(desc, name); String inputId = "_" + name; // FIXME Object inp = input_(inputId, name, desc, type, options, value); LabelTag label; Object inputWrap; if (type == FieldType.RADIOS || type == FieldType.CHECKBOXES) { inp = layout == FormLayout.VERTICAL ? div(inp) : span(inp); } if (type == FieldType.CHECKBOX) { label = null; inp = div(label(inp, desc)).classs("checkbox"); inputWrap = layout == FormLayout.HORIZONTAL ? div(inp).classs("col-sm-offset-4 col-sm-8") : inp; } else { if (layout != FormLayout.INLINE) { label = label(desc).for_(inputId); } else { if (type == FieldType.RADIOS) { label = label(desc); } else { label = null; } } if (layout == FormLayout.HORIZONTAL) { label.classs("col-sm-4 control-label"); } inputWrap = layout == FormLayout.HORIZONTAL ? div(inp).classs("col-sm-8") : inp; } DivTag group = label != null ? div(label, inputWrap) : div(inputWrap); group.classs("form-group"); return group; }
#vulnerable code public static DivTag field(FormLayout layout, String name, String desc, FieldType type, Object[] options, Object value) { desc = U.or(desc, name); String inputId = "_" + name; // FIXME Object inp = input_(inputId, name, desc, type, options, value); LabelTag label; Object inputWrap; if (type == FieldType.RADIOS) { inp = layout == FormLayout.VERTICAL ? div(inp) : span(inp); } if (type == FieldType.CHECKBOX) { label = null; inp = div(label(inp, desc)).classs("checkbox"); inputWrap = layout == FormLayout.HORIZONTAL ? div(inp).classs("col-sm-offset-4 col-sm-8") : inp; } else { if (layout != FormLayout.INLINE) { label = label(desc).for_(inputId); } else { if (type == FieldType.RADIOS) { label = label(desc); } else { label = null; } } if (layout == FormLayout.HORIZONTAL) { label.classs("col-sm-4 control-label"); } inputWrap = layout == FormLayout.HORIZONTAL ? div(inp).classs("col-sm-8") : inp; } DivTag group = label != null ? div(label, inputWrap) : div(inputWrap); group.classs("form-group"); return group; } #location 34 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String loadResourceAsString(String filename) { byte[] bytes = loadBytes(filename); return bytes != null ? new String(bytes) : null; }
#vulnerable code public static String loadResourceAsString(String filename) { return new String(loadBytes(filename)); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public int hashCode() { int result = Arrays.hashCode(packages); result = 31 * result + (matching != null ? matching.hashCode() : 0); result = 31 * result + Arrays.hashCode(annotated); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); result = 31 * result + Arrays.hashCode(classpath); result = 31 * result + (bytecodeFilter != null ? bytecodeFilter.hashCode() : 0); return result; }
#vulnerable code @Override public int hashCode() { int result = Arrays.hashCode(packages); result = 31 * result + (matching != null ? matching.hashCode() : 0); result = 31 * result + Arrays.hashCode(annotated); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); return result; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) { final HttpParser parser = new HttpParser(); final Buf[] reqs = {r(REQ1), r(REQ2), r(REQ3), r(REQ4)}; final RapidoidHelper helper = new RapidoidHelper(null); for (int i = 0; i < 100; i++) { Msc.benchmark("parse", 3000000, new Runnable() { int n; @Override public void run() { Buf buf = reqs[n % 4]; buf.position(0); parser.parse(buf, helper); n++; } }); } System.out.println(BUFS.instances() + " buffer instances."); }
#vulnerable code public static void main(String[] args) { final HttpParser parser = new HttpParser(); final Buf[] reqs = {r(REQ1), r(REQ2), r(REQ3), r(REQ4)}; final RapidoidHelper helper = new RapidoidHelper(null); BufRange[] ranges = helper.ranges1.ranges; final BufRanges headers = helper.ranges2; final BoolWrap isGet = helper.booleans[0]; final BoolWrap isKeepAlive = helper.booleans[1]; final BufRange verb = ranges[ranges.length - 1]; final BufRange uri = ranges[ranges.length - 2]; final BufRange path = ranges[ranges.length - 3]; final BufRange query = ranges[ranges.length - 4]; final BufRange protocol = ranges[ranges.length - 5]; final BufRange body = ranges[ranges.length - 6]; for (int i = 0; i < 10; i++) { Msc.benchmark("parse", 3000000, new Runnable() { int n; @Override public void run() { Buf buf = reqs[n % 4]; buf.position(0); parser.parse(buf, isGet, isKeepAlive, body, verb, uri, path, query, protocol, headers, helper); n++; } }); } System.out.println(BUFS.instances() + " buffer instances."); } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void render(Req req, Object value, OutputStream out) throws Exception { Customization.of(req).objectMapper().writeValue(out, value); }
#vulnerable code @Override public void render(Req req, Object value, OutputStream out) throws Exception { Customization.of(req).jackson().writeValue(out, value); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Future<byte[]> post(String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files, Callback<byte[]> callback) { return request("POST", uri, headers, data, files, null, null, callback); }
#vulnerable code public Future<byte[]> post(String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files, Callback<byte[]> callback) { headers = U.safe(headers); data = U.safe(data); files = U.safe(files); HttpPost req = new HttpPost(uri); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, String> entry : files.entrySet()) { String filename = entry.getValue(); File file = IO.file(filename); builder = builder.addBinaryBody(entry.getKey(), file, ContentType.DEFAULT_BINARY, filename); } for (Entry<String, String> entry : data.entrySet()) { builder = builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_TEXT); } ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { builder.build().writeTo(stream); } catch (IOException e) { throw U.rte(e); } byte[] bytes = stream.toByteArray(); NByteArrayEntity entity = new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA); for (Entry<String, String> e : headers.entrySet()) { req.addHeader(e.getKey(), e.getValue()); } req.setEntity(entity); Log.debug("Starting HTTP POST request", "request", req.getRequestLine()); return execute(client, req, callback); } #location 40 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void completeResponse() { U.must(responseCode >= 100); long wrote = output().size() - bodyPos; U.must(wrote <= Integer.MAX_VALUE, "Response too big!"); int pos = startingPos + getResp(responseCode).contentLengthPos + 10; output().putNumAsText(pos, wrote, false); }
#vulnerable code public void completeResponse() { long wrote = output().size() - bodyPos; U.must(wrote <= Integer.MAX_VALUE, "Response too big!"); int pos = startingPos + getResp(responseCode).contentLengthPos + 10; output().putNumAsText(pos, wrote, false); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected byte[] loadRes(String filename) { InputStream input = TestCommons.class.getClassLoader().getResourceAsStream(filename); return input != null ? readBytes(input) : null; }
#vulnerable code protected byte[] loadRes(String filename) { try { URL res = resource(filename); return res != null ? readBytes(new FileInputStream(new File(res.getFile()))) : null; } catch (FileNotFoundException e) { throw new RuntimeException(e); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] render(ReqImpl req, Resp resp) { Object result = resp.result(); if (result != null) { result = wrapGuiContent(result); resp.model().put("result", result); resp.result(result); } ViewRenderer viewRenderer = Customization.of(req).viewRenderer(); U.must(viewRenderer != null, "A view renderer wasn't configured!"); PageRenderer pageRenderer = Customization.of(req).pageRenderer(); U.must(pageRenderer != null, "A page renderer wasn't configured!"); boolean rendered; String viewName = resp.view(); ByteArrayOutputStream out = new ByteArrayOutputStream(); MVCModel basicModel = new MVCModel(req, resp, resp.model(), resp.screen(), result); Object[] renderModel = result != null ? new Object[]{basicModel, resp.model(), result} : new Object[]{basicModel, resp.model()}; try { rendered = viewRenderer.render(req, viewName, renderModel, out); } catch (Throwable e) { throw U.rte("Error while rendering view: " + viewName, e); } String renderResult = rendered ? new String(out.toByteArray()) : null; if (renderResult == null) { Object cnt = U.or(result, ""); renderResult = new String(HttpUtils.responseToBytes(req, cnt, MediaType.HTML_UTF_8, null)); } try { Object response = U.or(pageRenderer.renderPage(req, resp, renderResult), ""); return HttpUtils.responseToBytes(req, response, MediaType.HTML_UTF_8, null); } catch (Exception e) { throw U.rte("Error while rendering page!", e); } }
#vulnerable code public static byte[] render(ReqImpl req, Resp resp) { Object result = resp.result(); if (result != null) { result = wrapGuiContent(result); resp.model().put("result", result); resp.result(result); } ViewRenderer viewRenderer = req.routes().custom().viewRenderer(); U.must(viewRenderer != null, "A view renderer wasn't configured!"); PageRenderer pageRenderer = req.routes().custom().pageRenderer(); U.must(pageRenderer != null, "A page renderer wasn't configured!"); boolean rendered; String viewName = resp.view(); ByteArrayOutputStream out = new ByteArrayOutputStream(); MVCModel basicModel = new MVCModel(req, resp, resp.model(), resp.screen(), result); Object[] renderModel = result != null ? new Object[]{basicModel, resp.model(), result} : new Object[]{basicModel, resp.model()}; try { rendered = viewRenderer.render(req, viewName, renderModel, out); } catch (Throwable e) { throw U.rte("Error while rendering view: " + viewName, e); } String renderResult = rendered ? new String(out.toByteArray()) : null; if (renderResult == null) { Object cnt = U.or(result, ""); renderResult = new String(HttpUtils.responseToBytes(req, cnt, MediaType.HTML_UTF_8, null)); } try { Object response = U.or(pageRenderer.renderPage(req, resp, renderResult), ""); return HttpUtils.responseToBytes(req, response, MediaType.HTML_UTF_8, null); } catch (Exception e) { throw U.rte("Error while rendering page!", e); } } #location 37 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void initWorldConnectedServer() throws Exception { worldRpcConnectManager.initManager(); worldRpcConnectManager.initServers(rpcConfig.getSdWorldServers()); }
#vulnerable code public void initWorldConnectedServer() throws Exception { worldRpcConnectManager.initManager(); worldRpcConnectManager.initServers(sdWorldServers); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(rpcConfig.getSdDbServers()); }
#vulnerable code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(sdDbServers); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(rpcConfig.getSdDbServers()); }
#vulnerable code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(sdDbServers); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void loadPackage(String namespace, String ext) throws Exception { if(fileNames == null){ fileNames = messageScanner.scannerPackage(namespace, ext); } // 加载class,获取协议命令 DefaultClassLoader defaultClassLoader = LocalMananger.getInstance().getLocalSpringServiceManager().getDefaultClassLoader(); defaultClassLoader.resetDynamicGameClassLoader(); DynamicGameClassLoader dynamicGameClassLoader = defaultClassLoader.getDynamicGameClassLoader(); if(fileNames != null) { for (String fileName : fileNames) { String realClass = namespace + "." + fileName.subSequence(0, fileName.length() - (ext.length())); // Class<?> messageClass = null; // FileClassLoader fileClassLoader = defaultClassLoader.getDefaultClassLoader(); // if (!defaultClassLoader.isJarLoad()) { // defaultClassLoader.initClassLoaderPath(realClass, ext); // byte[] bytes = fileClassLoader.getClassData(realClass); // messageClass = dynamicGameClassLoader.findClass(realClass, bytes); // } else { // //读取 game_server_handler.jar包所在位置 // URL url = ClassLoader.getSystemClassLoader().getResource("./"); // File file = new File(url.getPath()); // File parentFile = new File(file.getParent()); // String jarPath = parentFile.getPath() + File.separator + "lib/game_server_handler.jar"; // logger.info("message load jar path:" + jarPath); // JarFile jarFile = new JarFile(new File(jarPath)); // fileClassLoader.initJarPath(jarFile); // byte[] bytes = fileClassLoader.getClassData(realClass); // messageClass = dynamicGameClassLoader.findClass(realClass, bytes); // } Class<?> messageClass = Class.forName(realClass); logger.info("handler load: " + messageClass); IMessageHandler iMessageHandler = getMessageHandler(messageClass); AbstractMessageHandler handler = (AbstractMessageHandler) iMessageHandler; handler.init(); Method[] methods = messageClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(MessageCommandAnnotation.class)) { MessageCommandAnnotation messageCommandAnnotation = (MessageCommandAnnotation) method .getAnnotation(MessageCommandAnnotation.class); if (messageCommandAnnotation != null) { addHandler(messageCommandAnnotation.command(), iMessageHandler); } } } } } }
#vulnerable code public void loadPackage(String namespace, String ext) throws Exception { if(fileNames == null){ fileNames = messageScanner.scannerPackage(namespace, ext); } // 加载class,获取协议命令 DefaultClassLoader defaultClassLoader = LocalMananger.getInstance().getLocalSpringServiceManager().getDefaultClassLoader(); defaultClassLoader.resetDynamicGameClassLoader(); DynamicGameClassLoader dynamicGameClassLoader = defaultClassLoader.getDynamicGameClassLoader(); if(fileNames != null) { for (String fileName : fileNames) { String realClass = namespace + "." + fileName.subSequence(0, fileName.length() - (ext.length())); Class<?> messageClass = null; FileClassLoader fileClassLoader = defaultClassLoader.getDefaultClassLoader(); if (!defaultClassLoader.isJarLoad()) { defaultClassLoader.initClassLoaderPath(realClass, ext); byte[] bytes = fileClassLoader.getClassData(realClass); messageClass = dynamicGameClassLoader.findClass(realClass, bytes); } else { //读取 game_server_handler.jar包所在位置 URL url = ClassLoader.getSystemClassLoader().getResource("./"); File file = new File(url.getPath()); File parentFile = new File(file.getParent()); String jarPath = parentFile.getPath() + File.separator + "lib/game_server_handler.jar"; logger.info("message load jar path:" + jarPath); JarFile jarFile = new JarFile(new File(jarPath)); fileClassLoader.initJarPath(jarFile); byte[] bytes = fileClassLoader.getClassData(realClass); messageClass = dynamicGameClassLoader.findClass(realClass, bytes); } logger.info("handler load: " + messageClass); IMessageHandler iMessageHandler = getMessageHandler(messageClass); AbstractMessageHandler handler = (AbstractMessageHandler) iMessageHandler; handler.init(); Method[] methods = messageClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(MessageCommandAnnotation.class)) { MessageCommandAnnotation messageCommandAnnotation = (MessageCommandAnnotation) method .getAnnotation(MessageCommandAnnotation.class); if (messageCommandAnnotation != null) { addHandler(messageCommandAnnotation.command(), iMessageHandler); } } } } } } #location 31 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(rpcConfig.getSdGameServers()); }
#vulnerable code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(sdGameServers); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") public void init() throws Exception { initWorldConnectedServer(); initGameConnectedServer(); initDbConnectServer(); }
#vulnerable code @SuppressWarnings("unchecked") public void init() throws Exception { Element rootElement = JdomUtils.getRootElemet(FileUtil.getConfigURL(GlobalConstants.ConfigFile.RPC_SERVER_CONFIG).getFile()); Map<Integer, SdServer> serverMap = new HashMap<>(); List<SdServer> sdWorldServers = new ArrayList<SdServer>(); Element element = rootElement.getChild(BOEnum.WORLD.toString().toLowerCase()); List<Element> childrenElements = element.getChildren("server"); for (Element childElement : childrenElements) { SdServer sdServer = new SdServer(); sdServer.load(childElement); sdWorldServers.add(sdServer); } List<SdServer> sdGameServers = new ArrayList<SdServer>(); element = rootElement.getChild(BOEnum.GAME.toString().toLowerCase()); childrenElements = element.getChildren("server"); for (Element childElement : childrenElements) { SdServer sdServer = new SdServer(); sdServer.load(childElement); sdGameServers.add(sdServer); } List<SdServer> sdDbServers = new ArrayList<SdServer>(); element = rootElement.getChild(BOEnum.DB.toString().toLowerCase()); childrenElements = element.getChildren("server"); for (Element childElement : childrenElements) { SdServer sdServer = new SdServer(); sdServer.load(childElement); sdDbServers.add(sdServer); } synchronized (this.lock) { this.sdWorldServers = sdWorldServers; this.sdGameServers = sdGameServers; this.sdDbServers = sdDbServers; } initWorldConnectedServer(); initGameConnectedServer(); initDbConnectServer(); SdRpcServiceProvider sdRpcServiceProvider = new SdRpcServiceProvider(); rootElement = JdomUtils.getRootElemet(FileUtil.getConfigURL(GlobalConstants.ConfigFile.RPC_SERVEICE_CONFIG).getFile()); childrenElements = rootElement.getChildren("service"); for (Element childElement : childrenElements) { sdRpcServiceProvider.load(childElement); } synchronized (this.lock) { this.sdRpcServiceProvider = sdRpcServiceProvider; } } #location 42 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void loadPackage(String namespace, String ext) throws Exception { if(fileNames == null){ fileNames = messageScanner.scannerPackage(namespace, ext); } // 加载class,获取协议命令 DefaultClassLoader defaultClassLoader = LocalMananger.getInstance().getLocalSpringServiceManager().getDefaultClassLoader(); defaultClassLoader.resetDynamicGameClassLoader(); DynamicGameClassLoader dynamicGameClassLoader = defaultClassLoader.getDynamicGameClassLoader(); if(fileNames != null) { for (String fileName : fileNames) { String realClass = namespace + "." + fileName.subSequence(0, fileName.length() - (ext.length())); // Class<?> messageClass = null; // FileClassLoader fileClassLoader = defaultClassLoader.getDefaultClassLoader(); // if (!defaultClassLoader.isJarLoad()) { // defaultClassLoader.initClassLoaderPath(realClass, ext); // byte[] bytes = fileClassLoader.getClassData(realClass); // messageClass = dynamicGameClassLoader.findClass(realClass, bytes); // } else { // //读取 game_server_handler.jar包所在位置 // URL url = ClassLoader.getSystemClassLoader().getResource("./"); // File file = new File(url.getPath()); // File parentFile = new File(file.getParent()); // String jarPath = parentFile.getPath() + File.separator + "lib/game_server_handler.jar"; // logger.info("message load jar path:" + jarPath); // JarFile jarFile = new JarFile(new File(jarPath)); // fileClassLoader.initJarPath(jarFile); // byte[] bytes = fileClassLoader.getClassData(realClass); // messageClass = dynamicGameClassLoader.findClass(realClass, bytes); // } Class<?> messageClass = Class.forName(realClass); logger.info("handler load: " + messageClass); IMessageHandler iMessageHandler = getMessageHandler(messageClass); AbstractMessageHandler handler = (AbstractMessageHandler) iMessageHandler; handler.init(); Method[] methods = messageClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(MessageCommandAnnotation.class)) { MessageCommandAnnotation messageCommandAnnotation = (MessageCommandAnnotation) method .getAnnotation(MessageCommandAnnotation.class); if (messageCommandAnnotation != null) { addHandler(messageCommandAnnotation.command(), iMessageHandler); } } } } } }
#vulnerable code public void loadPackage(String namespace, String ext) throws Exception { if(fileNames == null){ fileNames = messageScanner.scannerPackage(namespace, ext); } // 加载class,获取协议命令 DefaultClassLoader defaultClassLoader = LocalMananger.getInstance().getLocalSpringServiceManager().getDefaultClassLoader(); defaultClassLoader.resetDynamicGameClassLoader(); DynamicGameClassLoader dynamicGameClassLoader = defaultClassLoader.getDynamicGameClassLoader(); if(fileNames != null) { for (String fileName : fileNames) { String realClass = namespace + "." + fileName.subSequence(0, fileName.length() - (ext.length())); Class<?> messageClass = null; FileClassLoader fileClassLoader = defaultClassLoader.getDefaultClassLoader(); if (!defaultClassLoader.isJarLoad()) { defaultClassLoader.initClassLoaderPath(realClass, ext); byte[] bytes = fileClassLoader.getClassData(realClass); messageClass = dynamicGameClassLoader.findClass(realClass, bytes); } else { //读取 game_server_handler.jar包所在位置 URL url = ClassLoader.getSystemClassLoader().getResource("./"); File file = new File(url.getPath()); File parentFile = new File(file.getParent()); String jarPath = parentFile.getPath() + File.separator + "lib/game_server_handler.jar"; logger.info("message load jar path:" + jarPath); JarFile jarFile = new JarFile(new File(jarPath)); fileClassLoader.initJarPath(jarFile); byte[] bytes = fileClassLoader.getClassData(realClass); messageClass = dynamicGameClassLoader.findClass(realClass, bytes); } logger.info("handler load: " + messageClass); IMessageHandler iMessageHandler = getMessageHandler(messageClass); AbstractMessageHandler handler = (AbstractMessageHandler) iMessageHandler; handler.init(); Method[] methods = messageClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(MessageCommandAnnotation.class)) { MessageCommandAnnotation messageCommandAnnotation = (MessageCommandAnnotation) method .getAnnotation(MessageCommandAnnotation.class); if (messageCommandAnnotation != null) { addHandler(messageCommandAnnotation.command(), iMessageHandler); } } } } } } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(rpcConfig.getSdGameServers()); }
#vulnerable code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(sdGameServers); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") public void init() throws Exception { initWorldConnectedServer(); initGameConnectedServer(); initDbConnectServer(); }
#vulnerable code @SuppressWarnings("unchecked") public void init() throws Exception { Element rootElement = JdomUtils.getRootElemet(FileUtil.getConfigURL(GlobalConstants.ConfigFile.RPC_SERVER_CONFIG).getFile()); Map<Integer, SdServer> serverMap = new HashMap<>(); List<SdServer> sdWorldServers = new ArrayList<SdServer>(); Element element = rootElement.getChild(BOEnum.WORLD.toString().toLowerCase()); List<Element> childrenElements = element.getChildren("server"); for (Element childElement : childrenElements) { SdServer sdServer = new SdServer(); sdServer.load(childElement); sdWorldServers.add(sdServer); } List<SdServer> sdGameServers = new ArrayList<SdServer>(); element = rootElement.getChild(BOEnum.GAME.toString().toLowerCase()); childrenElements = element.getChildren("server"); for (Element childElement : childrenElements) { SdServer sdServer = new SdServer(); sdServer.load(childElement); sdGameServers.add(sdServer); } List<SdServer> sdDbServers = new ArrayList<SdServer>(); element = rootElement.getChild(BOEnum.DB.toString().toLowerCase()); childrenElements = element.getChildren("server"); for (Element childElement : childrenElements) { SdServer sdServer = new SdServer(); sdServer.load(childElement); sdDbServers.add(sdServer); } synchronized (this.lock) { this.sdWorldServers = sdWorldServers; this.sdGameServers = sdGameServers; this.sdDbServers = sdDbServers; } initWorldConnectedServer(); initGameConnectedServer(); initDbConnectServer(); SdRpcServiceProvider sdRpcServiceProvider = new SdRpcServiceProvider(); rootElement = JdomUtils.getRootElemet(FileUtil.getConfigURL(GlobalConstants.ConfigFile.RPC_SERVEICE_CONFIG).getFile()); childrenElements = rootElement.getChildren("service"); for (Element childElement : childrenElements) { sdRpcServiceProvider.load(childElement); } synchronized (this.lock) { this.sdRpcServiceProvider = sdRpcServiceProvider; } } #location 43 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected Object getId(Object entity) { entity = ProxyHelper.unwrap(entity); // String keyClassName = entity.getClass().getName(); MappedClass mc = mapr.getMappedClass(entity.getClass()); // // if (mapr.getMappedClasses().containsKey(keyClassName)) // mc = mapr.getMappedClasses().get(keyClassName); // else // mc = new MappedClass(entity.getClass(), getMapper()); // try { return mc.getIdField().get(entity); } catch (Exception e) { return null; } }
#vulnerable code protected Object getId(Object entity) { entity = ProxyHelper.unwrap(entity); MappedClass mc; String keyClassName = entity.getClass().getName(); if (mapr.getMappedClasses().containsKey(keyClassName)) mc = mapr.getMappedClasses().get(keyClassName); else mc = new MappedClass(entity.getClass(), getMapper()); try { return mc.getIdField().get(entity); } catch (Exception e) { return null; } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public <T> Key<T> save(String kind, T entity) { entity = ProxyHelper.unwrap(entity); DBCollection dbColl = getDB().getCollection(kind); return save(dbColl, entity, getWriteConcern(entity)); }
#vulnerable code public <T> Key<T> save(String kind, T entity) { entity = ProxyHelper.unwrap(entity); DBCollection dbColl = getDB().getCollection(kind); return save(dbColl, entity, defConcern); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private <T> Iterable<Key<T>> insert(final DBCollection dbColl, final Iterable<T> entities, final WriteConcern wc) { // return save(entities, wc); final List<DBObject> list = entities instanceof List ? new ArrayList<DBObject>(((List<T>) entities).size()) : new ArrayList<DBObject>(); final Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>(); for (final T ent : entities) { list.add(toDbObject(involvedObjects, ent)); } final WriteResult wr = null; final DBObject[] dbObjects = new DBObject[list.size()]; dbColl.insert(list.toArray(dbObjects), wc); throwOnError(wc, wr); final List<Key<T>> savedKeys = new ArrayList<Key<T>>(); final Iterator<T> entitiesIT = entities.iterator(); final Iterator<DBObject> dbObjectsIT = list.iterator(); while (entitiesIT.hasNext()) { final T entity = entitiesIT.next(); final DBObject dbObj = dbObjectsIT.next(); savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects)); } return savedKeys; }
#vulnerable code private <T> Iterable<Key<T>> insert(final DBCollection dbColl, final Iterable<T> entities, final WriteConcern wc) { final List<DBObject> list = entities instanceof List ? new ArrayList<DBObject>(((List<T>) entities).size()) : new ArrayList<DBObject>(); final Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>(); for (final T ent : entities) { final MappedClass mc = mapper.getMappedClass(ent); if (mc.getAnnotation(NotSaved.class) != null) { throw new MappingException( "Entity type: " + mc.getClazz().getName() + " is marked as NotSaved which means you should not try to save it!"); } list.add(entityToDBObj(ent, involvedObjects)); } final WriteResult wr = null; final DBObject[] dbObjects = new DBObject[list.size()]; dbColl.insert(list.toArray(dbObjects), wc); throwOnError(wc, wr); final List<Key<T>> savedKeys = new ArrayList<Key<T>>(); final Iterator<T> entitiesIT = entities.iterator(); final Iterator<DBObject> dbObjectsIT = list.iterator(); while (entitiesIT.hasNext()) { final T entity = entitiesIT.next(); final DBObject dbObj = dbObjectsIT.next(); savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects)); } return savedKeys; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void updateKeyInfo(final Object entity, final DBObject dbObj, EntityCache cache) { MappedClass mc = getMappedClass(entity); // update id field, if there. if ((mc.getIdField() != null) && (dbObj != null) && (dbObj.get(ID_KEY) != null)) { try { MappedField mf = mc.getMappedIdField(); Object oldIdValue = mc.getIdField().get(entity); readMappedField(dbObj, mf, entity, cache); Object dbIdValue = mc.getIdField().get(entity); if (oldIdValue != null) { // The entity already had an id set. Check to make sure it // hasn't changed. That would be unexpected, and could // indicate a bad state. if (!dbIdValue.equals(oldIdValue)) { mf.setFieldValue(entity, oldIdValue);//put the value back... throw new RuntimeException("@Id mismatch: " + oldIdValue + " != " + dbIdValue + " for " + entity.getClass().getName()); } } else { mc.getIdField().set(entity, dbIdValue); } } catch (Exception e) { if (e.getClass().equals(RuntimeException.class)) { throw (RuntimeException) e; } throw new RuntimeException("Error setting @Id field after save/insert.", e); } } }
#vulnerable code public void updateKeyInfo(final Object entity, final DBObject dbObj, EntityCache cache) { MappedClass mc = getMappedClass(entity); // update id field, if there. if ((mc.getIdField() != null) && (dbObj != null) && (dbObj.get(ID_KEY) != null)) { try { MappedField mf = mc.getMappedField(ID_KEY); Object oldIdValue = mc.getIdField().get(entity); setIdValue(entity, mf, dbObj, cache); Object dbIdValue = mc.getIdField().get(entity); if (oldIdValue != null) { // The entity already had an id set. Check to make sure it // hasn't changed. That would be unexpected, and could // indicate a bad state. if (!dbIdValue.equals(oldIdValue)) { mf.setFieldValue(entity, oldIdValue);//put the value back... throw new RuntimeException("@Id mismatch: " + oldIdValue + " != " + dbIdValue + " for " + entity.getClass().getName()); } } else { mc.getIdField().set(entity, dbIdValue); } } catch (Exception e) { if (e.getClass().equals(RuntimeException.class)) { throw (RuntimeException) e; } throw new RuntimeException("Error setting @Id field after save/insert.", e); } } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void execute() { if (help) { command.usage("init"); } else { try { WalkModFacade facade = new WalkModFacade(OptionsBuilder.options()); Configuration cfg = facade.getConfiguration(); Collection<PluginConfig> installedPlugins = null; if(cfg != null){ installedPlugins = cfg.getPlugins(); } URL searchURL = new URL(MVN_SEARCH_URL); InputStream is = null; Map<String, Boolean> installedList = new LinkedHashMap<String, Boolean>(); Map<String, String> pluginsList = new LinkedHashMap<String, String>(); Map<String, String> pluginsURLs = new LinkedHashMap<String, String>(); try { is = searchURL.openStream(); String content = readInputStreamAsString(is); DefaultJSONParser parser = new DefaultJSONParser(content); JSONObject object = parser.parseObject(); parser.close(); JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs"); for (int i = 0; i < artifactList.size(); i++) { JSONObject artifact = artifactList.getJSONObject(i); String artifactId = artifact.getString("a"); if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) { String groupId = artifact.getString("g"); String latestVersion = artifact.getString("latestVersion"); String pom = artifactId + "-" + latestVersion + ".pom"; String directory = groupId.replaceAll("\\.", "/"); URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/" + latestVersion + "/" + pom); InputStream projectIs = artifactDetailsURL.openStream(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(projectIs); NodeList nList = doc.getElementsByTagName("description"); String description = "unavailable description"; if (nList.getLength() == 1) { description = nList.item(0).getTextContent(); } String id = ""; if (!groupId.equals("org.walkmod")) { id = groupId + ":"; } id += artifactId.substring("walkmod-".length(), artifactId.length() - "-plugin".length()); if (Character.isLowerCase(description.charAt(0))) { description = Character.toUpperCase(description.charAt(0)) + description.substring(1, description.length()); } if (!description.endsWith(".")) { description = description + "."; } pluginsList.put(id, description); nList = doc.getChildNodes().item(0).getChildNodes(); int max = nList.getLength(); String url = "unavailable url"; for (int j = 0; j < max; j++) { String name = nList.item(j).getNodeName(); if (name.equals("url")) { url = nList.item(j).getTextContent(); j = max; } } pluginsURLs.put(id, url); PluginConfig equivalentPluginCfg = new PluginConfigImpl(); equivalentPluginCfg.setGroupId(groupId); equivalentPluginCfg.setArtifactId(artifactId); boolean isInstalled = (installedPlugins != null && installedPlugins .contains(equivalentPluginCfg)); installedList.put(id, isInstalled); } finally { projectIs.close(); } } } } finally { is.close(); } Set<String> keys = pluginsList.keySet(); List<String> sortedKeys = new LinkedList<String>(keys); Collections.sort(sortedKeys); at = new V2_AsciiTable(); at.addRule(); at.addRow("PLUGIN NAME (ID)", "INSTALLED", "URL (DOCUMENTATION)", "DESCRIPTION"); at.addStrongRule(); for (String key : sortedKeys) { String installed = ""; if (installedList.get(key)) { installed = "*"; } at.addRow(key, installed, pluginsURLs.get(key), pluginsList.get(key)); } at.addRule(); } catch (Exception e) { throw new WalkModException("Invalid plugins URL", e); } } }
#vulnerable code public void execute() { if (help) { command.usage("init"); } else { try { WalkModFacade facade = new WalkModFacade(OptionsBuilder.options()); Configuration cfg = facade.getConfiguration(); Collection<PluginConfig> installedPlugins = cfg.getPlugins(); URL searchURL = new URL(MVN_SEARCH_URL); InputStream is = null; Map<String, Boolean> installedList = new LinkedHashMap<String, Boolean>(); Map<String, String> pluginsList = new LinkedHashMap<String, String>(); Map<String, String> pluginsURLs = new LinkedHashMap<String, String>(); try { is = searchURL.openStream(); String content = readInputStreamAsString(is); DefaultJSONParser parser = new DefaultJSONParser(content); JSONObject object = parser.parseObject(); parser.close(); JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs"); for (int i = 0; i < artifactList.size(); i++) { JSONObject artifact = artifactList.getJSONObject(i); String artifactId = artifact.getString("a"); if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) { String groupId = artifact.getString("g"); String latestVersion = artifact.getString("latestVersion"); String pom = artifactId + "-" + latestVersion + ".pom"; String directory = groupId.replaceAll("\\.", "/"); URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/" + latestVersion + "/" + pom); InputStream projectIs = artifactDetailsURL.openStream(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(projectIs); NodeList nList = doc.getElementsByTagName("description"); String description = "unavailable description"; if (nList.getLength() == 1) { description = nList.item(0).getTextContent(); } String id = ""; if (!groupId.equals("org.walkmod")) { id = groupId + ":"; } id += artifactId.substring("walkmod-".length(), artifactId.length() - "-plugin".length()); if (Character.isLowerCase(description.charAt(0))) { description = Character.toUpperCase(description.charAt(0)) + description.substring(1, description.length()); } if (!description.endsWith(".")) { description = description + "."; } pluginsList.put(id, description); nList = doc.getChildNodes().item(0).getChildNodes(); int max = nList.getLength(); String url = "unavailable url"; for (int j = 0; j < max; j++) { String name = nList.item(j).getNodeName(); if (name.equals("url")) { url = nList.item(j).getTextContent(); j = max; } } pluginsURLs.put(id, url); PluginConfig equivalentPluginCfg = new PluginConfigImpl(); equivalentPluginCfg.setGroupId(groupId); equivalentPluginCfg.setArtifactId(artifactId); boolean isInstalled = (installedPlugins != null && installedPlugins .contains(equivalentPluginCfg)); installedList.put(id, isInstalled); } finally { projectIs.close(); } } } } finally { is.close(); } Set<String> keys = pluginsList.keySet(); List<String> sortedKeys = new LinkedList<String>(keys); Collections.sort(sortedKeys); at = new V2_AsciiTable(); at.addRule(); at.addRow("PLUGIN NAME (ID)", "INSTALLED", "URL (DOCUMENTATION)", "DESCRIPTION"); at.addStrongRule(); for (String key : sortedKeys) { String installed = ""; if (installedList.get(key)) { installed = "*"; } at.addRow(key, installed, pluginsURLs.get(key), pluginsList.get(key)); } at.addRule(); } catch (Exception e) { throw new WalkModException("Invalid plugins URL", e); } } } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void execute() { if (help) { command.usage("init"); } else { try { URL searchURL = new URL(MVN_SEARCH_URL); InputStream is = null; Map<String, String> pluginsList = new LinkedHashMap<String, String>(); Map<String, String> pluginsURLs = new LinkedHashMap<String, String>(); try { is = searchURL.openStream(); String content = readInputStreamAsString(is); DefaultJSONParser parser = new DefaultJSONParser(content); JSONObject object = parser.parseObject(); parser.close(); JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs"); for (int i = 0; i < artifactList.size(); i++) { JSONObject artifact = artifactList.getJSONObject(i); String artifactId = artifact.getString("a"); if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) { String groupId = artifact.getString("g"); String latestVersion = artifact.getString("latestVersion"); String pom = artifactId + "-" + latestVersion + ".pom"; String directory = groupId.replaceAll("\\.", "/"); URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/" + latestVersion + "/" + pom); InputStream projectIs = artifactDetailsURL.openStream(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(projectIs); NodeList nList = doc.getElementsByTagName("description"); String description = "unavailable description"; if (nList.getLength() == 1) { description = nList.item(0).getTextContent(); } String id = ""; if (!groupId.equals("org.walkmod")) { id = groupId + ":"; } id += artifactId.substring("walkmod-".length(), artifactId.length() - "-plugin".length()); if (Character.isLowerCase(description.charAt(0))) { description = Character.toUpperCase(description.charAt(0)) + description.substring(1, description.length()); } if (!description.endsWith(".")) { description = description + "."; } pluginsList.put(id, description); nList = doc.getChildNodes().item(0).getChildNodes(); int max = nList.getLength(); String url = "unavailable url"; for (int j = 0; j < max; j++) { String name = nList.item(j).getNodeName(); if (name.equals("url")) { url = nList.item(j).getTextContent(); j = max; } } pluginsURLs.put(id, url); } finally { projectIs.close(); } } } } finally { is.close(); } Set<String> keys = pluginsList.keySet(); List<String> sortedKeys = new LinkedList<String>(keys); Collections.sort(sortedKeys); V2_AsciiTable at = new V2_AsciiTable(); at.addRule(); at.addRow("PLUGIN NAME (ID)", "URL", "DESCRIPTION"); at.addStrongRule(); for (String key : sortedKeys) { at.addRow(key, pluginsURLs.get(key), pluginsList.get(key)); } at.addRule(); V2_AsciiTableRenderer rend = new V2_AsciiTableRenderer(); rend.setTheme(V2_E_TableThemes.UTF_LIGHT.get()); rend.setWidth(new WidthLongestLine()); RenderedTable rt = rend.render(at); System.out.println(rt); } catch (Exception e) { throw new WalkModException("Invalid plugins URL", e); } } }
#vulnerable code public void execute() { if (help) { command.usage("init"); } else { try { URL searchURL = new URL(MVN_SEARCH_URL); InputStream is = null; Map<String, String> pluginsList = new LinkedHashMap<String, String>(); Map<String, String> pluginsURLs = new LinkedHashMap<String, String>(); try { is = searchURL.openStream(); String content = readInputStreamAsString(is); DefaultJSONParser parser = new DefaultJSONParser(content); JSONObject object = parser.parseObject(); parser.close(); JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs"); for (int i = 0; i < artifactList.size(); i++) { JSONObject artifact = artifactList.getJSONObject(i); String artifactId = artifact.getString("a"); if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) { String groupId = artifact.getString("g"); String latestVersion = artifact.getString("latestVersion"); String pom = artifactId + "-" + latestVersion + ".pom"; String directory = groupId.replaceAll("\\.", "/"); URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/" + latestVersion + "/" + pom); InputStream projectIs = artifactDetailsURL.openStream(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(projectIs); NodeList nList = doc.getElementsByTagName("description"); String description = "unavailable description"; if (nList.getLength() == 1) { description = nList.item(0).getTextContent(); } String id =""; if(!groupId.equals("org.walkmod")){ id = groupId+":"; } id+= artifactId.substring("walkmod-".length(), artifactId.length()-"-plugin".length()); if (Character.isLowerCase(description.charAt(0))){ description = Character.toUpperCase(description.charAt(0))+ description.substring(1, description.length()); } if(!description.endsWith(".")){ description = description +"."; } pluginsList.put(id, description); nList = doc.getChildNodes().item(0).getChildNodes(); int max = nList.getLength(); String url = "unavailable url"; for(int j = 0; j < max; j++){ String name = nList.item(j).getNodeName(); if(name.equals("url")){ url = nList.item(j).getTextContent(); j = max; } } pluginsURLs.put(id, url); } finally { projectIs.close(); } } } } finally { is.close(); } Set<String> keys = pluginsList.keySet(); List<String> sortedKeys = new LinkedList<String>(keys); Collections.sort(sortedKeys); String line = ""; for (int i = 0; i < 2 + 23 +63 + 103; i++) { line = line + "-"; } System.out.println(line); System.out.printf("| %-20s | %-60s | %-100s |%n", StringUtils.center("PLUGIN NAME (ID)", 20), StringUtils.center("URL", 60), StringUtils.center("DESCRIPTION", 100)); System.out.println(line); for(String key: sortedKeys){ System.out.printf("| %-20s | %-60s | %-100s |%n", fill(key, 20), fill(pluginsURLs.get(key), 60), pluginsList.get(key)); } System.out.println(line); } catch (Exception e) { throw new WalkModException("Invalid plugins URL", e); } } } #location 93 #vulnerability type CHECKERS_PRINTF_ARGS
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static List<File> findFiles(final File parent, boolean recurse) { final List<File> result = new ArrayList<File>(); if (parent.isDirectory()) { File[] files = parent.listFiles(); files = (files != null ? files : new File[0]); for (File child : files) { if (child.isFile() && child.getName().endsWith(".java")) { result.add(child); } } if (recurse) { for (File child : files) { if (child.isDirectory() && child.getName().startsWith(".") == false) { result.addAll(findFiles(child, recurse)); } } } } else { if (parent.getName().endsWith(".java")) { result.add(parent); } } return result; }
#vulnerable code private static List<File> findFiles(final File parent, boolean recurse) { final List<File> result = new ArrayList<File>(); if (parent.isDirectory()) { File[] files = parent.listFiles(); for (File child : files) { if (child.isFile() && child.getName().endsWith(".java")) { result.add(child); } } if (recurse) { for (File child : files) { if (child.isDirectory() && child.getName().startsWith(".") == false) { result.addAll(findFiles(child, recurse)); } } } } else { if (parent.getName().endsWith(".java")) { result.add(parent); } } return result; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void writeElements(final String currentIndent, final SerIterator itemIterator) { // find converter once for performance, and before checking if key is bean StringConverter<Object> keyConverter = null; StringConverter<Object> rowConverter = null; StringConverter<Object> columnConverter = null; boolean keyBean = false; if (itemIterator.category() == SerCategory.TABLE || itemIterator.category() == SerCategory.GRID) { try { rowConverter = settings.getConverter().findConverterNoGenerics(itemIterator.keyType()); } catch (RuntimeException ex) { throw new IllegalArgumentException("Unable to write map as declared key type is neither a bean nor a simple type: " + itemIterator.keyType().getName(), ex); } try { columnConverter = settings.getConverter().findConverterNoGenerics(itemIterator.columnType()); } catch (RuntimeException ex) { throw new IllegalArgumentException("Unable to write map as declared column type is neither a bean nor a simple type: " + itemIterator.columnType().getName(), ex); } } else if (itemIterator.category() == SerCategory.MAP) { // if key type is known and convertible use short key format, else use full bean format if (settings.getConverter().isConvertible(itemIterator.keyType())) { keyConverter = settings.getConverter().findConverterNoGenerics(itemIterator.keyType()); } else { keyBean = true; } } // output each item while (itemIterator.hasNext()) { itemIterator.next(); StringBuilder attr = new StringBuilder(32); if (keyConverter != null) { String keyStr = convertToString(keyConverter, itemIterator.key(), "map key"); appendAttribute(attr, KEY, keyStr); } if (rowConverter != null) { String rowStr = convertToString(rowConverter, itemIterator.key(), "table row"); appendAttribute(attr, ROW, rowStr); String colStr = convertToString(columnConverter, itemIterator.column(), "table column"); appendAttribute(attr, COL, colStr); } if (itemIterator.count() != 1) { appendAttribute(attr, COUNT, Integer.toString(itemIterator.count())); } if (keyBean) { Object key = itemIterator.key(); builder.append(currentIndent).append('<').append(ENTRY).append(attr).append('>').append(settings.getNewLine()); writeKeyElement(currentIndent + settings.getIndent(), key, itemIterator); writeValueElement(currentIndent + settings.getIndent(), ITEM, new StringBuilder(), itemIterator); builder.append(currentIndent).append('<').append('/').append(ENTRY).append('>').append(settings.getNewLine()); } else { String tagName = itemIterator.category() == SerCategory.MAP ? ENTRY : ITEM; writeValueElement(currentIndent, tagName, attr, itemIterator); } } }
#vulnerable code private void writeElements(final String currentIndent, final SerIterator itemIterator) { // find converter once for performance, and before checking if key is bean StringConverter<Object> keyConverter = null; StringConverter<Object> rowConverter = null; StringConverter<Object> columnConverter = null; boolean keyBean = false; if (itemIterator.category() == SerCategory.TABLE || itemIterator.category() == SerCategory.GRID) { try { rowConverter = settings.getConverter().findConverterNoGenerics(itemIterator.keyType()); } catch (RuntimeException ex) { throw new IllegalArgumentException("Unable to write map as declared key type is neither a bean nor a simple type: " + itemIterator.keyType().getName(), ex); } try { columnConverter = settings.getConverter().findConverterNoGenerics(itemIterator.columnType()); } catch (RuntimeException ex) { throw new IllegalArgumentException("Unable to write map as declared column type is neither a bean nor a simple type: " + itemIterator.columnType().getName(), ex); } } else if (itemIterator.category() == SerCategory.MAP) { if (settings.getConverter().isConvertible(itemIterator.keyType())) { keyConverter = settings.getConverter().findConverterNoGenerics(itemIterator.keyType()); } else if (Bean.class.isAssignableFrom(itemIterator.keyType())) { keyBean = true; } else { throw new IllegalArgumentException("Unable to write map as declared key type is neither a bean nor a simple type: " + itemIterator.keyType().getName()); } } // output each item while (itemIterator.hasNext()) { itemIterator.next(); StringBuilder attr = new StringBuilder(32); if (keyConverter != null) { String keyStr = convertToString(keyConverter, itemIterator.key(), "map key"); appendAttribute(attr, KEY, keyStr); } if (rowConverter != null) { String rowStr = convertToString(rowConverter, itemIterator.key(), "table row"); appendAttribute(attr, ROW, rowStr); String colStr = convertToString(columnConverter, itemIterator.column(), "table column"); appendAttribute(attr, COL, colStr); } if (itemIterator.count() != 1) { appendAttribute(attr, COUNT, Integer.toString(itemIterator.count())); } if (keyBean) { Object key = itemIterator.key(); if (key == null) { throw new IllegalArgumentException("Unable to write map key as it cannot be null: " + key); } builder.append(currentIndent).append('<').append(ENTRY).append(attr).append('>').append(settings.getNewLine()); writeKeyValueElement(currentIndent + settings.getIndent(), key, itemIterator); builder.append(currentIndent).append('<').append('/').append(ENTRY).append('>').append(settings.getNewLine()); } else { String tagName = itemIterator.category() == SerCategory.MAP ? ENTRY : ITEM; writeValueElement(currentIndent, tagName, attr, itemIterator); } } } #location 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSystemGc() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); GCResource gcResource = new GCResource("SampleIBMJ9_R27_SR1_global.txt"); gcResource.getLogger().addHandler(handler); DataReader reader = getDataReader(gcResource); GCModel model = reader.read(); assertThat("model size", model.size(), is(1)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.075863, 0.0000001)); assertThat("number of errors", handler.getCount(), is(0)); }
#vulnerable code @Test public void testSystemGc() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); IMP_LOGGER.addHandler(handler); DATA_READER_FACTORY_LOGGER.addHandler(handler); InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R27_SR1_global.txt"); DataReader reader = new DataReaderIBM_J9_R28(in); GCModel model = reader.read(); assertThat("model size", model.size(), is(1)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.075863, 0.0000001)); assertThat("number of errors", handler.getCount(), is(0)); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws IOException, InterruptedException { IntData performanceData = new IntData(); for (int i=0; i<10; i++) { long start = System.currentTimeMillis(); DataReader dataReader = new DataReaderFactory().getDataReader(new FileInputStream(args[0])); dataReader.read(); performanceData.add((int)(System.currentTimeMillis() - start)); } printIntData(args[0], performanceData); }
#vulnerable code public static void main(String[] args) throws IOException, InterruptedException { IntData performanceData = new IntData(); for (int i=0; i<50; i++) { long start = System.currentTimeMillis(); DataReader dataReader = new DataReaderSun1_6_0(new FileInputStream(args[0])); dataReader.read(); performanceData.add((int)(System.currentTimeMillis() - start)); } printIntData(args[0], performanceData); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void handleGcStart(XMLEventReader eventReader, StartElement startElement, GCEvent event) throws XMLStreamException { event.setType(Type.lookup(getAttributeValue(startElement, "type"))); if (event.getExtendedType() == null) { LOG.warning("could not determine type of event " + startElement.toString()); return; } String currentElementName = ""; while (eventReader.hasNext() && !currentElementName.equals(GC_START)) { XMLEvent xmlEvent = eventReader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startEl = xmlEvent.asStartElement(); if (startEl.getName().getLocalPart().equals("mem-info")) { setTotalAndPreUsed(event, startEl); } else if (startEl.getName().getLocalPart().equals("mem")) { switch (getAttributeValue(startEl, "type")) { case "nursery": GCEvent young = new GCEvent(); young.setType(Type.lookup("nursery")); setTotalAndPreUsed(young, startEl); event.add(young); break; case "tenure": GCEvent tenured = new GCEvent(); tenured.setType(Type.lookup("tenure")); setTotalAndPreUsed(tenured, startEl); event.add(tenured); break; // all other are ignored } } } else if (xmlEvent.isEndElement()) { EndElement endElement = xmlEvent.asEndElement(); currentElementName = endElement.getName().getLocalPart(); } } }
#vulnerable code private void handleGcStart(XMLEventReader eventReader, StartElement startElement, GCEvent event) throws XMLStreamException { event.setType(Type.lookup(getAttributeValue(startElement, "type"))); if (event.getExtendedType() == null) { LOG.warning("could not determine type of event " + startElement.toString()); return; } String currentElementName = ""; while (eventReader.hasNext() && !currentElementName.equals(GC_START)) { XMLEvent xmlEvent = eventReader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startEl = xmlEvent.asStartElement(); if (startEl.getName().getLocalPart().equals("mem-info")) { event.setTotal(NumberParser.parseInt(getAttributeValue(startEl, "total")) / 1024); event.setPreUsed(event.getTotal() - (NumberParser.parseInt(getAttributeValue(startEl, "free")) / 1024)); } else if (startEl.getName().getLocalPart().equals("mem")) { switch (getAttributeValue(startEl, "type")) { case "nursery": // TODO read young break; } } } else if (xmlEvent.isEndElement()) { EndElement endElement = xmlEvent.asEndElement(); currentElementName = endElement.getName().getLocalPart(); } } } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean isParseablePhaseEvent(String line) { Matcher phaseStringMatcher = line != null ? PATTERN_INCLUDE_STRINGS_PHASE.matcher(line) : null; if (phaseStringMatcher != null && phaseStringMatcher.find()) { String phaseType = phaseStringMatcher.group(GROUP_DECORATORS_GC_TYPE); if (phaseType != null && AbstractGCEvent.Type.lookup(phaseType) != null) { return true; } } return false; }
#vulnerable code private boolean isParseablePhaseEvent(String line) { Matcher phaseStringMatcher = line != null ? PATTERN_INCLUDE_STRINGS_PHASE.matcher(line) : null; if (phaseStringMatcher.find()) { String phaseType = phaseStringMatcher.group(GROUP_DECORATORS_GC_TYPE); if (phaseType != null && AbstractGCEvent.Type.lookup(phaseType) != null) { return true; } } return false; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void loadModelIllegalArgument() throws Exception { try { dataReaderFacade.loadModel(new GcResourceFile("http://")); } catch (DataReaderException e) { assertNotNull("cause", e.getCause()); Class expectedClass; String javaVersion = System.getProperty("java.version"); if (javaVersion.startsWith("14") || javaVersion.startsWith("15")) { expectedClass = IOException.class; } else { expectedClass = IllegalArgumentException.class; } assertEquals("expected exception in cause", expectedClass.getName(), e.getCause().getClass().getName()); } }
#vulnerable code @Test public void loadModelIllegalArgument() throws Exception { try { dataReaderFacade.loadModel(new GcResourceFile("http://")); } catch (DataReaderException e) { assertNotNull("cause", e.getCause()); Class expectedClass; if (System.getProperty("java.version").startsWith("14")) { expectedClass = IOException.class; } else { expectedClass = IllegalArgumentException.class; } assertEquals("expected exception in cause", expectedClass.getName(), e.getCause().getClass().getName()); } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSystemGc() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); GCResource gcResource = new GCResource("SampleIBMJ9_R26_GAFP1_global.txt"); gcResource.getLogger().addHandler(handler); DataReader reader = getDataReader(gcResource); GCModel model = reader.read(); assertThat("model size", model.size(), is(1)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.036392, 0.0000001)); assertThat("total before", event.getTotal(), is(toKiloBytes(514064384))); assertThat("free before", event.getPreUsed(), is(toKiloBytes(514064384 - 428417552))); assertThat("free after", event.getPostUsed(), is(toKiloBytes(514064384 - 479900360))); assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(111411200))); assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(111411200 - 29431656))); assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(111411200 - 80831520))); assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184))); assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 398985896))); assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 399068840))); assertThat("number of errors", handler.getCount(), is(0)); }
#vulnerable code @Test public void testSystemGc() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); IMP_LOGGER.addHandler(handler); DATA_READER_FACTORY_LOGGER.addHandler(handler); InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R26_GAFP1_global.txt"); DataReader reader = new DataReaderIBM_J9_R28(in); GCModel model = reader.read(); assertThat("model size", model.size(), is(1)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.036392, 0.0000001)); assertThat("total before", event.getTotal(), is(toKiloBytes(514064384))); assertThat("free before", event.getPreUsed(), is(toKiloBytes(514064384 - 428417552))); assertThat("free after", event.getPostUsed(), is(toKiloBytes(514064384 - 479900360))); assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(111411200))); assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(111411200 - 29431656))); assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(111411200 - 80831520))); assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184))); assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 398985896))); assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 399068840))); assertThat("number of errors", handler.getCount(), is(0)); } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSystemGc() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); GCResource gcResource = new GCResource("SampleIBMJ9_R28_global.txt"); gcResource.getLogger().addHandler(handler); DataReader reader = getDataReader(gcResource); GCModel model = reader.read(); assertThat("model size", model.size(), is(1)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.097756, 0.0000001)); assertThat("number of errors", handler.getCount(), is(0)); }
#vulnerable code @Test public void testSystemGc() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); IMP_LOGGER.addHandler(handler); DATA_READER_FACTORY_LOGGER.addHandler(handler); InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R28_global.txt"); DataReader reader = new DataReaderIBM_J9_R28(in); GCModel model = reader.read(); assertThat("model size", model.size(), is(1)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.097756, 0.0000001)); assertThat("number of errors", handler.getCount(), is(0)); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unused") public ListBoxModel doFillCredentialsIdItems(@QueryParameter String credentialsId) { return createListBoxModel(credentialsId); }
#vulnerable code @SuppressWarnings("unused") public ListBoxModel doFillCredentialsIdItems(@QueryParameter String credentialsId) { if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) { return new StandardListBoxModel().includeCurrentValue(credentialsId); } return new StandardListBoxModel() .includeEmptyValue() .includeMatchingAs( ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class, Collections.emptyList(), CredentialsMatchers.always() ); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String getIconFileName() { PluginWrapper wrapper = Jenkins.getInstanceOrNull().getPluginManager() .getPlugin(SonarPlugin.class); return "/plugin/" + wrapper.getShortName() + "/images/waves_48x48.png"; }
#vulnerable code @Override public String getIconFileName() { PluginWrapper wrapper = Jenkins.getInstance().getPluginManager() .getPlugin(SonarPlugin.class); return "/plugin/" + wrapper.getShortName() + "/images/waves_48x48.png"; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onFirstRow (final int index, final ButtonEvent event) { if (event == ButtonEvent.DOWN) return; if (event == ButtonEvent.UP) { final CursorDeviceProxy cd = this.model.getCursorDevice (); if (!cd.hasSelectedDevice ()) return; if (!this.showDevices) { cd.setSelectedParameterPageInBank (index); return; } if (cd.getPositionInBank () != index) { cd.selectSibling (index); return; } final ModeManager modeManager = this.surface.getModeManager (); if (!cd.hasLayers ()) { ((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (false); return; } final ChannelData layer = cd.getSelectedLayerOrDrumPad (); if (layer == null) cd.selectLayerOrDrumPad (0); modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER); return; } // LONG press - move upwards this.surface.setButtonConsumed (PushControlSurface.PUSH_BUTTON_ROW1_1 + index); this.moveUp (); }
#vulnerable code @Override public void onFirstRow (final int index, final ButtonEvent event) { if (event == ButtonEvent.DOWN) return; final CursorDeviceProxy cd = this.model.getCursorDevice (); final ModeManager modeManager = this.surface.getModeManager (); if (event == ButtonEvent.UP) { if (!cd.hasSelectedDevice ()) return; if (!this.showDevices) { cd.setSelectedParameterPageInBank (index); return; } if (cd.getPositionInBank () != index) { cd.selectSibling (index); return; } final boolean isContainer = cd.hasLayers (); if (!isContainer) { ((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (false); return; } final ChannelData layer = cd.getSelectedLayerOrDrumPad (); if (layer == null) cd.selectLayerOrDrumPad (0); modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER); return; } // LONG press - move upwards this.surface.setButtonConsumed (PushControlSurface.PUSH_BUTTON_ROW1_1 + index); // There is no device on the track move upwards to the track view if (!cd.hasSelectedDevice ()) { this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN); return; } // Parameter banks are shown -> show devices final DeviceParamsMode deviceParamsMode = (DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS); if (!deviceParamsMode.isShowDevices ()) { deviceParamsMode.setShowDevices (true); return; } // Devices are shown, if nested show the layers otherwise move up to the tracks if (cd.isNested ()) { cd.selectParent (); modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER); deviceParamsMode.setShowDevices (false); cd.selectChannel (); return; } // Move up to the track this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN); } #location 48 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onValueKnobTouch (final int index, final boolean isTouched) { final CursorDeviceProxy cd = this.model.getCursorDevice (); final ChannelData l = cd.getSelectedLayerOrDrumPad (); if (l == null) return; this.isKnobTouched[index] = isTouched; if (isTouched) { if (this.surface.isDeletePressed ()) { this.surface.setButtonConsumed (this.surface.getDeleteButtonId ()); switch (index) { case 0: cd.resetLayerOrDrumPadVolume (l.getIndex ()); break; case 1: cd.resetLayerOrDrumPadPan (l.getIndex ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.resetLayerSend (l.getIndex (), sendIndex); break; } return; } switch (index) { case 0: this.surface.getDisplay ().notify ("Volume: " + l.getVolumeStr ()); break; case 1: this.surface.getDisplay ().notify ("Pan: " + l.getPanStr ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); final EffectTrackBankProxy fxTrackBank = this.model.getEffectTrackBank (); final String name = fxTrackBank == null ? l.getSends ()[sendIndex].getName () : fxTrackBank.getTrack (sendIndex).getName (); if (!name.isEmpty ()) this.surface.getDisplay ().notify ("Send " + name + ": " + l.getSends ()[sendIndex].getDisplayedValue ()); break; } } switch (index) { case 0: cd.touchLayerOrDrumPadVolume (l.getIndex (), isTouched); break; case 1: cd.touchLayerOrDrumPadPan (l.getIndex (), isTouched); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.touchLayerOrDrumPadSend (l.getIndex (), sendIndex, isTouched); break; } this.checkStopAutomationOnKnobRelease (isTouched); }
#vulnerable code @Override public void onValueKnobTouch (final int index, final boolean isTouched) { final CursorDeviceProxy cd = this.model.getCursorDevice (); final ChannelData l = cd.getSelectedLayerOrDrumPad (); this.isKnobTouched[index] = isTouched; if (isTouched) { if (this.surface.isDeletePressed ()) { this.surface.setButtonConsumed (this.surface.getDeleteButtonId ()); switch (index) { case 0: cd.resetLayerOrDrumPadVolume (l.getIndex ()); break; case 1: cd.resetLayerOrDrumPadPan (l.getIndex ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.resetLayerSend (l.getIndex (), sendIndex); break; } return; } switch (index) { case 0: this.surface.getDisplay ().notify ("Volume: " + l.getVolumeStr ()); break; case 1: this.surface.getDisplay ().notify ("Pan: " + l.getPanStr ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); final EffectTrackBankProxy fxTrackBank = this.model.getEffectTrackBank (); final String name = fxTrackBank == null ? l.getSends ()[sendIndex].getName () : fxTrackBank.getTrack (sendIndex).getName (); if (!name.isEmpty ()) this.surface.getDisplay ().notify ("Send " + name + ": " + l.getSends ()[sendIndex].getDisplayedValue ()); break; } } switch (index) { case 0: cd.touchLayerOrDrumPadVolume (l.getIndex (), isTouched); break; case 1: cd.touchLayerOrDrumPadPan (l.getIndex (), isTouched); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.touchLayerOrDrumPadSend (l.getIndex (), sendIndex, isTouched); break; } this.checkStopAutomationOnKnobRelease (isTouched); } #location 55 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onFirstRow (final int index, final ButtonEvent event) { if (event == ButtonEvent.DOWN) return; if (event == ButtonEvent.UP) { final CursorDeviceProxy cd = this.model.getCursorDevice (); if (!cd.hasSelectedDevice ()) return; final int offset = getDrumPadIndex (cd); final ChannelData layer = cd.getLayerOrDrumPad (offset + index); if (!layer.doesExist ()) return; final int layerIndex = layer.getIndex (); if (!layer.isSelected ()) { cd.selectLayerOrDrumPad (layerIndex); return; } cd.enterLayerOrDrumPad (layer.getIndex ()); cd.selectFirstDeviceInLayerOrDrumPad (layer.getIndex ()); final ModeManager modeManager = this.surface.getModeManager (); modeManager.setActiveMode (Modes.MODE_DEVICE_PARAMS); ((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (true); return; } // LONG press this.surface.setButtonConsumed (PushControlSurface.PUSH_BUTTON_ROW1_1 + index); this.moveUp (); }
#vulnerable code @Override public void onFirstRow (final int index, final ButtonEvent event) { if (event == ButtonEvent.DOWN) return; final CursorDeviceProxy cd = this.model.getCursorDevice (); final ModeManager modeManager = this.surface.getModeManager (); if (event == ButtonEvent.UP) { if (!cd.hasSelectedDevice ()) return; final int offset = getDrumPadIndex (cd); final ChannelData layer = cd.getLayerOrDrumPad (offset + index); if (!layer.doesExist ()) return; final int layerIndex = layer.getIndex (); if (!layer.isSelected ()) { cd.selectLayerOrDrumPad (layerIndex); return; } cd.enterLayerOrDrumPad (layer.getIndex ()); cd.selectFirstDeviceInLayerOrDrumPad (layer.getIndex ()); modeManager.setActiveMode (Modes.MODE_DEVICE_PARAMS); ((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (true); return; } // LONG press this.surface.setButtonConsumed (PushControlSurface.PUSH_BUTTON_ROW1_1 + index); // There is no device on the track move upwards to the track view if (!cd.hasSelectedDevice ()) { this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN); return; } modeManager.setActiveMode (Modes.MODE_DEVICE_PARAMS); cd.selectChannel (); ((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (true); } #location 42 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void sendDisplayData () { if (this.hidDevice == null) return; synchronized (this.busySendingDisplay) { final ByteBuffer displayBuffer = this.displayBlock.createByteBuffer (); for (int row = 0; row < 3; row++) { fillHeader (displayBuffer, row); if (row == 0) { for (int j = 0; j < 72; j++) { final int col = j / 8; displayBuffer.put ((byte) this.bars[col][j - col * 8]); if (j % 8 == 7) { displayBuffer.put ((byte) this.bars[col][8]); } else { if (this.dots[0][j] && this.dots[1][j]) displayBuffer.put ((byte) 255); else if (this.dots[0][j]) displayBuffer.put ((byte) 253); else if (this.dots[1][j]) displayBuffer.put ((byte) 254); else displayBuffer.put ((byte) 0); } } // Padding for (int j = 0; j < 96; j++) displayBuffer.put ((byte) 0); } else { for (int j = 0; j < 72; j++) displayBuffer.put (this.getCharacter (row - 1, j)); // Padding for (int j = 0; j < 96; j++) displayBuffer.put ((byte) 0); } // TODO Use Memory object for interface; also rewind on createByteBuffer with Reaper displayBuffer.rewind (); final byte [] data = new byte [DATA_SZ]; displayBuffer.get (data); this.hidDevice.sendOutputReport ((byte) 0xE0, data, DATA_SZ); } } }
#vulnerable code public void sendDisplayData () { if (this.usbEndpointDisplay == null) return; synchronized (this.busySendingDisplay) { final ByteBuffer displayBuffer = this.displayBlock.createByteBuffer (); displayBuffer.rewind (); for (int row = 0; row < 3; row++) { fillHeader (displayBuffer, row); if (row == 0) { for (int j = 0; j < 72; j++) { final int col = j / 8; displayBuffer.put ((byte) this.bars[col][j - col * 8]); if (j % 8 == 7) { displayBuffer.put ((byte) this.bars[col][8]); } else { if (this.dots[0][j] && this.dots[1][j]) displayBuffer.put ((byte) 255); else if (this.dots[0][j]) displayBuffer.put ((byte) 253); else if (this.dots[1][j]) displayBuffer.put ((byte) 254); else displayBuffer.put ((byte) 0); } } // Padding for (int j = 0; j < 96; j++) displayBuffer.put ((byte) 0); } else { for (int j = 0; j < 72; j++) displayBuffer.put (this.getCharacter (row - 1, j)); // Padding for (int j = 0; j < 96; j++) displayBuffer.put ((byte) 0); } // TODO TEST final byte [] data = new byte [DATA_SZ]; displayBuffer.get (data); this.hidDevice.sendOutputReport ((byte) 0, data, DATA_SZ); // this.usbEndpointDisplay.send (this.displayBlock, TIMEOUT); } } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onValueKnobTouch (final int index, final boolean isTouched) { final CursorDeviceProxy cd = this.model.getCursorDevice (); final ChannelData l = cd.getSelectedLayerOrDrumPad (); if (l == null) return; this.isKnobTouched[index] = isTouched; if (isTouched) { if (this.surface.isDeletePressed ()) { this.surface.setButtonConsumed (this.surface.getDeleteButtonId ()); switch (index) { case 0: cd.resetLayerOrDrumPadVolume (l.getIndex ()); break; case 1: cd.resetLayerOrDrumPadPan (l.getIndex ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.resetLayerSend (l.getIndex (), sendIndex); break; } return; } switch (index) { case 0: this.surface.getDisplay ().notify ("Volume: " + l.getVolumeStr ()); break; case 1: this.surface.getDisplay ().notify ("Pan: " + l.getPanStr ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); final EffectTrackBankProxy fxTrackBank = this.model.getEffectTrackBank (); final String name = fxTrackBank == null ? l.getSends ()[sendIndex].getName () : fxTrackBank.getTrack (sendIndex).getName (); if (!name.isEmpty ()) this.surface.getDisplay ().notify ("Send " + name + ": " + l.getSends ()[sendIndex].getDisplayedValue ()); break; } } switch (index) { case 0: cd.touchLayerOrDrumPadVolume (l.getIndex (), isTouched); break; case 1: cd.touchLayerOrDrumPadPan (l.getIndex (), isTouched); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.touchLayerOrDrumPadSend (l.getIndex (), sendIndex, isTouched); break; } this.checkStopAutomationOnKnobRelease (isTouched); }
#vulnerable code @Override public void onValueKnobTouch (final int index, final boolean isTouched) { final CursorDeviceProxy cd = this.model.getCursorDevice (); final ChannelData l = cd.getSelectedLayerOrDrumPad (); this.isKnobTouched[index] = isTouched; if (isTouched) { if (this.surface.isDeletePressed ()) { this.surface.setButtonConsumed (this.surface.getDeleteButtonId ()); switch (index) { case 0: cd.resetLayerOrDrumPadVolume (l.getIndex ()); break; case 1: cd.resetLayerOrDrumPadPan (l.getIndex ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.resetLayerSend (l.getIndex (), sendIndex); break; } return; } switch (index) { case 0: this.surface.getDisplay ().notify ("Volume: " + l.getVolumeStr ()); break; case 1: this.surface.getDisplay ().notify ("Pan: " + l.getPanStr ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); final EffectTrackBankProxy fxTrackBank = this.model.getEffectTrackBank (); final String name = fxTrackBank == null ? l.getSends ()[sendIndex].getName () : fxTrackBank.getTrack (sendIndex).getName (); if (!name.isEmpty ()) this.surface.getDisplay ().notify ("Send " + name + ": " + l.getSends ()[sendIndex].getDisplayedValue ()); break; } } switch (index) { case 0: cd.touchLayerOrDrumPadVolume (l.getIndex (), isTouched); break; case 1: cd.touchLayerOrDrumPadPan (l.getIndex (), isTouched); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.touchLayerOrDrumPadSend (l.getIndex (), sendIndex, isTouched); break; } this.checkStopAutomationOnKnobRelease (isTouched); } #location 64 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void moveUp () { // There is no device on the track move upwards to the track view final CursorDeviceProxy cd = this.model.getCursorDevice (); final View activeView = this.surface.getViewManager ().getActiveView (); if (!cd.hasSelectedDevice ()) { activeView.executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN); return; } // Parameter banks are shown -> show devices final ModeManager modeManager = this.surface.getModeManager (); final DeviceParamsMode deviceParamsMode = (DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS); if (!deviceParamsMode.isShowDevices ()) { deviceParamsMode.setShowDevices (true); return; } // Devices are shown, if nested show the layers otherwise move up to the tracks if (cd.isNested ()) { cd.selectParent (); modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER); deviceParamsMode.setShowDevices (false); cd.selectChannel (); return; } // Move up to the track if (this.model.isCursorDeviceOnMasterTrack ()) { activeView.executeTriggerCommand (Commands.COMMAND_MASTERTRACK, ButtonEvent.DOWN); activeView.executeTriggerCommand (Commands.COMMAND_MASTERTRACK, ButtonEvent.UP); } else activeView.executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN); }
#vulnerable code protected void moveUp () { // There is no device on the track move upwards to the track view final CursorDeviceProxy cd = this.model.getCursorDevice (); if (!cd.hasSelectedDevice ()) { this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN); return; } // Parameter banks are shown -> show devices final ModeManager modeManager = this.surface.getModeManager (); final DeviceParamsMode deviceParamsMode = (DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS); if (!deviceParamsMode.isShowDevices ()) { deviceParamsMode.setShowDevices (true); return; } // Devices are shown, if nested show the layers otherwise move up to the tracks if (cd.isNested ()) { cd.selectParent (); modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER); deviceParamsMode.setShowDevices (false); cd.selectChannel (); return; } // Move up to the track this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onValueKnobTouch (final int index, final boolean isTouched) { final CursorDeviceProxy cd = this.model.getCursorDevice (); final ChannelData l = cd.getSelectedLayerOrDrumPad (); if (l == null) return; this.isKnobTouched[index] = isTouched; if (isTouched) { if (this.surface.isDeletePressed ()) { this.surface.setButtonConsumed (this.surface.getDeleteButtonId ()); switch (index) { case 0: cd.resetLayerOrDrumPadVolume (l.getIndex ()); break; case 1: cd.resetLayerOrDrumPadPan (l.getIndex ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.resetLayerSend (l.getIndex (), sendIndex); break; } return; } switch (index) { case 0: this.surface.getDisplay ().notify ("Volume: " + l.getVolumeStr ()); break; case 1: this.surface.getDisplay ().notify ("Pan: " + l.getPanStr ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); final EffectTrackBankProxy fxTrackBank = this.model.getEffectTrackBank (); final String name = fxTrackBank == null ? l.getSends ()[sendIndex].getName () : fxTrackBank.getTrack (sendIndex).getName (); if (!name.isEmpty ()) this.surface.getDisplay ().notify ("Send " + name + ": " + l.getSends ()[sendIndex].getDisplayedValue ()); break; } } switch (index) { case 0: cd.touchLayerOrDrumPadVolume (l.getIndex (), isTouched); break; case 1: cd.touchLayerOrDrumPadPan (l.getIndex (), isTouched); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.touchLayerOrDrumPadSend (l.getIndex (), sendIndex, isTouched); break; } this.checkStopAutomationOnKnobRelease (isTouched); }
#vulnerable code @Override public void onValueKnobTouch (final int index, final boolean isTouched) { final CursorDeviceProxy cd = this.model.getCursorDevice (); final ChannelData l = cd.getSelectedLayerOrDrumPad (); this.isKnobTouched[index] = isTouched; if (isTouched) { if (this.surface.isDeletePressed ()) { this.surface.setButtonConsumed (this.surface.getDeleteButtonId ()); switch (index) { case 0: cd.resetLayerOrDrumPadVolume (l.getIndex ()); break; case 1: cd.resetLayerOrDrumPadPan (l.getIndex ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.resetLayerSend (l.getIndex (), sendIndex); break; } return; } switch (index) { case 0: this.surface.getDisplay ().notify ("Volume: " + l.getVolumeStr ()); break; case 1: this.surface.getDisplay ().notify ("Pan: " + l.getPanStr ()); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); final EffectTrackBankProxy fxTrackBank = this.model.getEffectTrackBank (); final String name = fxTrackBank == null ? l.getSends ()[sendIndex].getName () : fxTrackBank.getTrack (sendIndex).getName (); if (!name.isEmpty ()) this.surface.getDisplay ().notify ("Send " + name + ": " + l.getSends ()[sendIndex].getDisplayedValue ()); break; } } switch (index) { case 0: cd.touchLayerOrDrumPadVolume (l.getIndex (), isTouched); break; case 1: cd.touchLayerOrDrumPadPan (l.getIndex (), isTouched); break; default: if (this.isPush2 && index < 4) break; final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2); cd.touchLayerOrDrumPadSend (l.getIndex (), sendIndex, isTouched); break; } this.checkStopAutomationOnKnobRelease (isTouched); } #location 58 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void setPermissions(File workdir) { if (!System.getProperty("os.name").startsWith("Windows")) { try { new ProcessBuilder("chmod", "755", workdir + "/bin/ld").start().waitFor(); new ProcessBuilder("chmod", "755", workdir + "/bin/windres").start().waitFor(); } catch (InterruptedException e) { getLog().warn("Interrupted while chmodding platform-specific binaries", e); } catch (IOException e) { getLog().warn("Unable to set platform-specific binaries to 755", e); } } }
#vulnerable code private void setPermissions(File workdir) { if (!System.getProperty("os.name").startsWith("Windows")) { Runtime r = Runtime.getRuntime(); try { r.exec("chmod 755 " + workdir + "/bin/ld").waitFor(); r.exec("chmod 755 " + workdir + "/bin/windres").waitFor(); } catch (InterruptedException e) { getLog().warn("Interrupted while chmodding platform-specific binaries", e); } catch (IOException e) { getLog().warn("Unable to set platform-specific binaries to 755", e); } } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void setPermissions(File workdir) { if (!System.getProperty("os.name").startsWith("Windows")) { try { new ProcessBuilder("chmod", "755", workdir + "/bin/ld").start().waitFor(); new ProcessBuilder("chmod", "755", workdir + "/bin/windres").start().waitFor(); } catch (InterruptedException e) { getLog().warn("Interrupted while chmodding platform-specific binaries", e); } catch (IOException e) { getLog().warn("Unable to set platform-specific binaries to 755", e); } } }
#vulnerable code private void setPermissions(File workdir) { if (!System.getProperty("os.name").startsWith("Windows")) { Runtime r = Runtime.getRuntime(); try { r.exec("chmod 755 " + workdir + "/bin/ld").waitFor(); r.exec("chmod 755 " + workdir + "/bin/windres").waitFor(); } catch (InterruptedException e) { getLog().warn("Interrupted while chmodding platform-specific binaries", e); } catch (IOException e) { getLog().warn("Unable to set platform-specific binaries to 755", e); } } } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders, List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException { List<byte[]> piecesList = new ArrayList<byte[]>(piecesCount); FileInputStream fin = new FileInputStream(baseFile); for (int i=0; i<piecesCount; i++){ byte[] piece = new byte[pieceSize]; fin.read(piece); piecesList.add(piece); } fin.close(); final long torrentFileLength = baseFile.length(); Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize); File torrentFile = new File(baseFile.getParentFile(), baseFile.getName() + ".torrent"); torrent.save(torrentFile); for (int i=0; i<numSeeders; i++){ final File baseDir = tempFiles.createTempDir(); final File seederPiecesFile = new File(baseDir, baseFile.getName()); RandomAccessFile raf = new RandomAccessFile(seederPiecesFile, "rw"); raf.setLength(torrentFileLength); for (int pieceIdx=i; pieceIdx<piecesCount; pieceIdx += numSeeders){ raf.seek(pieceIdx*pieceSize); raf.write(piecesList.get(pieceIdx)); } Client client = createClient(); clientList.add(client); client.addTorrent(new SharedTorrent(torrent, baseDir, false)); client.start(InetAddress.getLocalHost()); } }
#vulnerable code private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders, List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException { List<byte[]> piecesList = new ArrayList<byte[]>(piecesCount); FileInputStream fin = new FileInputStream(baseFile); for (int i=0; i<piecesCount; i++){ byte[] piece = new byte[pieceSize]; fin.read(piece); piecesList.add(piece); } fin.close(); final long torrentFileLength = baseFile.length(); Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize); File torrentFile = new File(baseFile.getParentFile(), baseFile.getName() + ".torrent"); torrent.save(torrentFile); for (int i=0; i<numSeeders; i++){ final File baseDir = tempFiles.createTempDir(); final File seederPiecesFile = new File(baseDir, baseFile.getName()); RandomAccessFile raf = new RandomAccessFile(seederPiecesFile, "rw"); raf.setLength(torrentFileLength); for (int pieceIdx=i; pieceIdx<piecesCount; pieceIdx += numSeeders){ raf.seek(pieceIdx*pieceSize); raf.write(piecesList.get(pieceIdx)); } Client client = createClient(); clientList.add(client); client.addTorrent(new SharedTorrent(torrent, baseDir, false)); client.share(); } } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents) throws AnnounceException { logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...", new Object[] { this.formatAnnounceEvent(event), this.torrent.getUploaded(), this.torrent.getDownloaded(), this.torrent.getLeft() }); URLConnection conn = null; try { HTTPAnnounceRequestMessage request = this.buildAnnounceRequest(event); // Send announce request (HTTP GET) URL target = request.buildAnnounceURL(this.tracker.toURL()); conn = target.openConnection(); InputStream is = new AutoCloseInputStream(conn.getInputStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(is); // Parse and handle the response HTTPTrackerMessage message = HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray())); this.handleTrackerAnnounceResponse(message, inhibitEvents); } catch (MalformedURLException mue) { throw new AnnounceException("Invalid announce URL (" + mue.getMessage() + ")", mue); } catch (MessageValidationException mve) { throw new AnnounceException("Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve); } catch (IOException ioe) { throw new AnnounceException(ioe.getMessage(), ioe); } finally { if (conn != null && conn instanceof HttpURLConnection) { InputStream err = ((HttpURLConnection) conn).getErrorStream(); if (err != null) { try { err.close(); } catch (IOException ioe) { logger.warn("Problem ensuring error stream closed!", ioe); } } } } }
#vulnerable code @Override public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents) throws AnnounceException { logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...", new Object[] { this.formatAnnounceEvent(event), this.torrent.getUploaded(), this.torrent.getDownloaded(), this.torrent.getLeft() }); try { HTTPAnnounceRequestMessage request = this.buildAnnounceRequest(event); // Send announce request (HTTP GET) URL target = request.buildAnnounceURL(this.tracker.toURL()); URLConnection conn = target.openConnection(); InputStream is = new AutoCloseInputStream(conn.getInputStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(is); // Parse and handle the response HTTPTrackerMessage message = HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray())); this.handleTrackerAnnounceResponse(message, inhibitEvents); } catch (MalformedURLException mue) { throw new AnnounceException("Invalid announce URL (" + mue.getMessage() + ")", mue); } catch (MessageValidationException mve) { throw new AnnounceException("Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve); } catch (IOException ioe) { throw new AnnounceException(ioe.getMessage(), ioe); } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { // First, analyze the torrent's local data. try { this.torrent.init(); } catch (ClosedByInterruptException cbie) { logger.warn("Client was interrupted during initialization. " + "Aborting right away."); this.setState(ClientState.ERROR); return; } catch (IOException ioe) { logger.error("Could not initialize torrent file data!", ioe); this.setState(ClientState.ERROR); return; } // Initial completion test if (this.torrent.isComplete()) { this.seed(); } else { this.setState(ClientState.SHARING); } this.announce.start(); this.service.start(); int optimisticIterations = 0; int rateComputationIterations = 0; while (!this.stop) { optimisticIterations = (optimisticIterations == 0 ? Client.OPTIMISTIC_UNCHOKE_ITERATIONS : optimisticIterations - 1); rateComputationIterations = (rateComputationIterations == 0 ? Client.RATE_COMPUTATION_ITERATIONS : rateComputationIterations - 1); try { this.unchokePeers(optimisticIterations == 0); this.info(); if (rateComputationIterations == 0) { this.resetPeerRates(); } } catch (Exception e) { logger.error("An exception occurred during the BitTorrent " + "client main loop execution!", e); } try { Thread.sleep(Client.UNCHOKING_FREQUENCY*1000); } catch (InterruptedException ie) { logger.trace("BitTorrent main loop interrupted."); } } logger.debug("Stopping BitTorrent client connection service " + "and announce threads..."); this.service.stop(); this.announce.stop(); // Close all peer connections logger.debug("Closing all remaining peer connections..."); for (SharingPeer peer : this.connected.values()) { peer.unbind(true); } this.torrent.close(); // Determine final state if (this.torrent.isComplete()) { this.setState(ClientState.DONE); } else { this.setState(ClientState.ERROR); } logger.info("BitTorrent client signing off."); }
#vulnerable code @Override public void run() { // First, analyze the torrent's local data. try { this.torrent.init(); } catch (ClosedByInterruptException cbie) { logger.warn("Client was interrupted during initialization. " + "Aborting right away."); this.setState(ClientState.ERROR); return; } catch (IOException ioe) { logger.error("Could not initialize torrent file data!", ioe); this.setState(ClientState.ERROR); return; } // Initial completion test if (this.torrent.isComplete()) { this.seed(); } else { this.setState(ClientState.SHARING); } this.announce.start(); this.service.start(); int optimisticIterations = 0; int rateComputationIterations = 0; while (!this.stop) { optimisticIterations = (optimisticIterations == 0 ? Client.OPTIMISTIC_UNCHOKE_ITERATIONS : optimisticIterations - 1); rateComputationIterations = (rateComputationIterations == 0 ? Client.RATE_COMPUTATION_ITERATIONS : rateComputationIterations - 1); try { this.unchokePeers(optimisticIterations == 0); this.info(); if (rateComputationIterations == 0) { this.resetPeerRates(); } } catch (Exception e) { logger.error("An exception occurred during the BitTorrent " + "client main loop execution!", e); } try { Thread.sleep(Client.UNCHOKING_FREQUENCY*1000); } catch (InterruptedException ie) { logger.trace("BitTorrent main loop interrupted."); } } logger.debug("Stopping BitTorrent client connection service " + "and announce threads..."); this.service.stop(); this.announce.stop(); // Close all peer connections logger.debug("Closing all remaining peer connections..."); for (SharingPeer peer : this.connected.values()) { peer.unbind(true); } // Determine final state if (this.torrent.isComplete()) { this.setState(ClientState.DONE); } else { this.setState(ClientState.ERROR); } logger.info("BitTorrent client signing off."); } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents) throws AnnounceException { logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...", new Object[] { this.formatAnnounceEvent(event), this.torrent.getUploaded(), this.torrent.getDownloaded(), this.torrent.getLeft() }); try { State state = State.CONNECT_REQUEST; int tries = 0; while (tries <= UDP_MAX_TRIES) { if (this.lastConnectionTime != null && new Date().before(this.lastConnectionTime)) { state = State.ANNOUNCE_REQUEST; } tries++; } ByteBuffer data = null; UDPTrackerMessage.UDPTrackerResponseMessage message = UDPTrackerMessage.UDPTrackerResponseMessage.parse(data); this.handleTrackerResponse(message, inhibitEvents); } catch (MessageValidationException mve) { logger.error("Tracker message violates expected protocol: {}!", mve.getMessage(), mve); } }
#vulnerable code @Override public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents) throws AnnounceException { logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...", new Object[] { this.formatAnnounceEvent(event), this.torrent.getUploaded(), this.torrent.getDownloaded(), this.torrent.getLeft() }); try { ByteBuffer data = null; UDPTrackerMessage.UDPTrackerResponseMessage message = UDPTrackerMessage.UDPTrackerResponseMessage.parse(data); this.handleTrackerResponse(message, inhibitEvents); } catch (MessageValidationException mve) { logger.error("Tracker message violates expected protocol: {}!", mve.getMessage(), mve); } } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = null; while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket = new Socket("127.0.0.1", serverPort); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (socket == null || !socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); }
#vulnerable code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = new Socket(); while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket.connect(new InetSocketAddress("127.0.0.1", serverPort)); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (!socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = null; while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket = new Socket("127.0.0.1", serverPort); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (socket == null || !socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); }
#vulnerable code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = new Socket(); while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket.connect(new InetSocketAddress("127.0.0.1", serverPort)); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (!socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); } #location 103 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getUploaded() { return myTorrentStatistic.getUploadedBytes(); }
#vulnerable code public long getUploaded() { return this.uploaded; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static SharedTorrent fromFile(File source, File parent, boolean multiThreadHash, boolean seeder, boolean leecher, TorrentStatisticProvider torrentStatisticProvider) throws IOException, NoSuchAlgorithmException { byte[] data = FileUtils.readFileToByteArray(source); return new SharedTorrent(data, parent, multiThreadHash, seeder, leecher, DEFAULT_REQUEST_STRATEGY, torrentStatisticProvider); }
#vulnerable code public static SharedTorrent fromFile(File source, File parent, boolean multiThreadHash, boolean seeder, boolean leecher, TorrentStatisticProvider torrentStatisticProvider) throws IOException, NoSuchAlgorithmException { FileInputStream fis = new FileInputStream(source); byte[] data = new byte[(int) source.length()]; fis.read(data); fis.close(); return new SharedTorrent(data, parent, multiThreadHash, seeder, leecher, DEFAULT_REQUEST_STRATEGY, torrentStatisticProvider); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getLeft() { return myTorrentStatistic.getLeftBytes(); }
#vulnerable code public long getLeft() { return this.left; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void open() throws IOException { try { myLock.writeLock().lock(); this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } finally { myLock.writeLock().unlock(); } }
#vulnerable code public void open() throws IOException { this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; myConnectionManager.initAndRunWorker(); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = myConnectionManager.getBindAddress().getPort(); Socket socket = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); this.myConnectionManager.close(true); }
#vulnerable code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = null; while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket = new Socket("127.0.0.1", serverPort); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (socket == null || !socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); } #location 44 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), TorrentUtils.getTorrentFileNames(torrent).get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } }
#vulnerable code public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } #location 71 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void open() throws IOException { try { myLock.writeLock().lock(); this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } finally { myLock.writeLock().unlock(); } }
#vulnerable code public void open() throws IOException { this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public BitSet getCompletedPieces() { if (!this.isInitialized()) { throw new IllegalStateException("Torrent not yet initialized!"); } synchronized (this.completedPieces) { return (BitSet)this.completedPieces.clone(); } }
#vulnerable code public BitSet getCompletedPieces() { synchronized (this.completedPieces) { return (BitSet)this.completedPieces.clone(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { logger.info("Starting announce loop..."); while (!this.stop && !Thread.currentThread().isInterrupted()) { logger.debug("Starting announce for {} torrents", torrents.size()); for (SharedTorrent torrent : this.torrents) { if (this.stop || Thread.currentThread().isInterrupted()){ break; } try { TrackerClient trackerClient = this.getCurrentTrackerClient(torrent); if (trackerClient != null) { trackerClient.announceAllInterfaces(AnnounceRequestMessage.RequestEvent.NONE, torrent.isFinished(), torrent); } else { logger.warn("Tracker client for {} is null. Torrent is not announced on tracker", torrent.getName()); } } catch (Exception e) { logger.info(e.getMessage()); logger.debug(e.getMessage(), e); } } try { Thread.sleep(this.myAnnounceInterval * 1000); } catch (InterruptedException ie) { break; } } logger.info("Exited announce loop."); }
#vulnerable code @Override public void run() { logger.info("Starting announce loop..."); while (!this.stop && !Thread.currentThread().isInterrupted()) { logger.debug("Starting announce for {} torrents", torrents.size()); for (SharedTorrent torrent : this.torrents) { if (this.stop || Thread.currentThread().isInterrupted()){ break; } try { TrackerClient trackerClient = this.getCurrentTrackerClient(torrent); if (trackerClient != null) { trackerClient.announceAllInterfaces(AnnounceRequestMessage.RequestEvent.NONE, torrent.isFinished(), torrent); } else { logger.warn("Tracker client for {} is null. Torrent is not announced on tracker", torrent.getName()); } } catch (Exception e) { logger.info(e.getMessage()); logger.debug(e.getMessage(), e); } } try { Thread.sleep(this.myAnnounceInterval * 1000); } catch (InterruptedException ie) { break; } } logger.info("Exited announce loop."); if (!this.forceStop) { // Send the final 'stopped' event to the tracker after a little // while. try { Thread.sleep(500); } catch (InterruptedException ie) { // Ignore return; } try { for (SharedTorrent torrent : this.torrents) { this.getCurrentTrackerClient(torrent).announceAllInterfaces(AnnounceRequestMessage.RequestEvent.STOPPED, true, torrent); } } catch (AnnounceException e) { logger.info("Can't announce stop: " + e.getMessage()); logger.debug("Can't announce stop", e); // don't try to announce all. Stop after first error, assuming tracker is already unavailable } } } #location 46 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), TorrentUtils.getTorrentFileNames(torrent).get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } }
#vulnerable code public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } #location 46 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public MetadataBuilder addFile(@NotNull File source) { return addFile(source, source.getName()); }
#vulnerable code public MetadataBuilder addFile(@NotNull File source) { sources.add(new Source(source)); return this; } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void handlePieceCompleted(final SharingPeer peer, Piece piece) throws IOException { final SharedTorrent torrent = peer.getTorrent(); final String torrentHash; synchronized (torrent) { torrentHash = torrent.getHexInfoHash(); if (piece.isValid()) { // Make sure the piece is marked as completed in the torrent // Note: this is required because the order the // PeerActivityListeners are called is not defined, and we // might be called before the torrent's piece completion // handler is. torrent.markCompleted(piece); logger.debug("Completed download of {} from {}, now has {}/{} pieces.", new Object[]{ piece, peer, torrent.getCompletedPieces().cardinality(), torrent.getPieceCount() }); BitSet completed = new BitSet(); completed.or(torrent.getCompletedPieces()); completed.and(peer.getAvailablePieces()); if (completed.equals(peer.getAvailablePieces())) { // send not interested when have no interested pieces; peer.send(PeerMessage.NotInterestedMessage.craft()); } } else { logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer); peer.getPoorlyAvailablePieces().set(piece.getIndex()); } if (torrent.isComplete()) { //close connection with all peers for this torrent logger.info("Download of {} complete.", torrent.getName()); torrent.finish(); try { this.announce.getCurrentTrackerClient(torrent) .announceAllInterfaces(TrackerMessage.AnnounceRequestMessage.RequestEvent.COMPLETED, true, torrent); } catch (AnnounceException e) { logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce()); } } } // Send a HAVE message to all connected peers PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex()); for (SharingPeer remote : getConnectedPeers()) { if (remote.getTorrent().getHexInfoHash().equals(torrentHash)) remote.send(have); } }
#vulnerable code @Override public void handlePieceCompleted(final SharingPeer peer, Piece piece) throws IOException { final SharedTorrent torrent = peer.getTorrent(); synchronized (torrent) { if (piece.isValid()) { // Make sure the piece is marked as completed in the torrent // Note: this is required because the order the // PeerActivityListeners are called is not defined, and we // might be called before the torrent's piece completion // handler is. torrent.markCompleted(piece); logger.debug("Completed download of {} from {}, now has {}/{} pieces.", new Object[]{ piece, peer, torrent.getCompletedPieces().cardinality(), torrent.getPieceCount() }); // Send a HAVE message to all connected peers PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex()); final String torrentHash = torrent.getHexInfoHash(); for (SharingPeer remote : getConnectedPeers()) { if (remote.getTorrent().getHexInfoHash().equals(torrentHash)) remote.send(have); } BitSet completed = new BitSet(); completed.or(torrent.getCompletedPieces()); completed.and(peer.getAvailablePieces()); if (completed.equals(peer.getAvailablePieces())) { // send not interested when have no interested pieces; peer.send(PeerMessage.NotInterestedMessage.craft()); } } else { logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer); peer.getPoorlyAvailablePieces().set(piece.getIndex()); } if (torrent.isComplete()) { //close connection with all peers for this torrent logger.info("Download of {} complete.", torrent.getName()); torrent.finish(); try { this.announce.getCurrentTrackerClient(torrent) .announceAllInterfaces(TrackerMessage.AnnounceRequestMessage.RequestEvent.COMPLETED, true, torrent); } catch (AnnounceException e) { logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce()); } } } } #location 50 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<TorrentFile> parseFiles(Map<String, BEValue> infoTable, boolean torrentContainsManyFiles, String name) throws InvalidBEncodingException { if (!torrentContainsManyFiles) { final BEValue md5Sum = infoTable.get(MD5_SUM); return Collections.singletonList(new TorrentFile( Collections.singletonList(name), getRequiredValueOrThrowException(infoTable, FILE_LENGTH).getLong(), md5Sum == null ? null : md5Sum.getString() )); } List<TorrentFile> result = new ArrayList<TorrentFile>(); for (BEValue file : infoTable.get(FILES).getList()) { Map<String, BEValue> fileInfo = file.getMap(); List<String> path = new ArrayList<String>(); BEValue filePathList = fileInfo.get(FILE_PATH_UTF8); if (filePathList == null) { filePathList = fileInfo.get(FILE_PATH); } for (BEValue pathElement : filePathList.getList()) { path.add(pathElement.getString()); } final BEValue md5Sum = infoTable.get(MD5_SUM); result.add(new TorrentFile( path, fileInfo.get(FILE_LENGTH).getLong(), md5Sum == null ? null : md5Sum.getString())); } return result; }
#vulnerable code private List<TorrentFile> parseFiles(Map<String, BEValue> infoTable, boolean torrentContainsManyFiles, String name) throws InvalidBEncodingException { if (!torrentContainsManyFiles) { final BEValue md5Sum = infoTable.get(MD5_SUM); return Collections.singletonList(new TorrentFile( Collections.singletonList(name), getRequiredValueOrThrowException(infoTable, FILE_LENGTH).getLong(), md5Sum == null ? null : md5Sum.getString() )); } List<TorrentFile> result = new ArrayList<TorrentFile>(); for (BEValue file : infoTable.get(FILES).getList()) { Map<String, BEValue> fileInfo = file.getMap(); List<String> path = new ArrayList<String>(); for (BEValue pathElement : fileInfo.get(FILE_PATH).getList()) { path.add(pathElement.getString()); } final BEValue md5Sum = infoTable.get(MD5_SUM); result.add(new TorrentFile( path, fileInfo.get(FILE_LENGTH).getLong(), md5Sum == null ? null : md5Sum.getString())); } return result; } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void open() throws IOException { try { myLock.writeLock().lock(); this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } finally { myLock.writeLock().unlock(); } }
#vulnerable code public void open() throws IOException { this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void save(File output) throws IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(output); fos.write(this.getEncoded()); logger.info("Wrote torrent file {}.", output.getAbsolutePath()); } finally { if (fos != null) { fos.close(); } } }
#vulnerable code public void save(File output) throws IOException { FileOutputStream fos = new FileOutputStream(output); fos.write(this.getEncoded()); fos.close(); logger.info("Wrote torrent file {}.", output.getAbsolutePath()); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public BitSet getAvailablePieces() { if (!this.isInitialized()) { throw new IllegalStateException("Torrent not yet initialized!"); } BitSet availablePieces = new BitSet(this.pieces.length); synchronized (this.pieces) { for (Piece piece : this.pieces) { if (piece.available()) { availablePieces.set(piece.getIndex()); } } } return availablePieces; }
#vulnerable code public BitSet getAvailablePieces() { BitSet availablePieces = new BitSet(this.pieces.length); synchronized (this.pieces) { for (Piece piece : this.pieces) { if (piece.available()) { availablePieces.set(piece.getIndex()); } } } return availablePieces; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void open() throws IOException { try { myLock.writeLock().lock(); this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } finally { myLock.writeLock().unlock(); } }
#vulnerable code public void open() throws IOException { this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { int numFiles = 50; this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downloadDir = tempFiles.createTempDir(); Client seeder = createClient("seeder"); seeder.start(InetAddress.getLocalHost()); Client leech = null; try { URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); final Set<String> names = new HashSet<String>(); List<File> filesToShare = new ArrayList<File>(); for (int i = 0; i < numFiles; i++) { File tempFile = tempFiles.createTempFile(513 * 1024); File srcFile = new File(srcDir, tempFile.getName()); assertTrue(tempFile.renameTo(srcFile)); Torrent torrent = TorrentCreator.create(srcFile, announceURI, "Test"); File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); filesToShare.add(srcFile); names.add(srcFile.getName()); } for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); seeder.addTorrent(torrentFile.getAbsolutePath(), f.getParent()); } leech = createClient("leecher"); leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null, new SelectorFactoryImpl()); for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath()); } new WaitFor(60 * 1000) { @Override protected boolean condition() { final Set<String> strings = listFileNames(downloadDir); int count = 0; final List<String> partItems = new ArrayList<String>(); for (String s : strings) { if (s.endsWith(".part")) { count++; partItems.add(s); } } if (count < 5) { System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray())); } return strings.containsAll(names); } }; assertEquals(listFileNames(downloadDir), names); } finally { leech.stop(); seeder.stop(); } }
#vulnerable code public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { int numFiles = 50; this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downloadDir = tempFiles.createTempDir(); Client seeder = createClient("seeder"); seeder.start(InetAddress.getLocalHost()); Client leech = null; try { URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); final Set<String> names = new HashSet<String>(); List<File> filesToShare = new ArrayList<File>(); for (int i = 0; i < numFiles; i++) { File tempFile = tempFiles.createTempFile(513 * 1024); File srcFile = new File(srcDir, tempFile.getName()); assertTrue(tempFile.renameTo(srcFile)); Torrent torrent = TorrentCreator.create(srcFile, announceURI, "Test"); File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); filesToShare.add(srcFile); names.add(srcFile.getName()); } for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); seeder.addTorrent(torrentFile.getAbsolutePath(), f.getParent()); } leech = createClient("leecher"); leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null); for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath()); } new WaitFor(60 * 1000) { @Override protected boolean condition() { final Set<String> strings = listFileNames(downloadDir); int count = 0; final List<String> partItems = new ArrayList<String>(); for (String s : strings) { if (s.endsWith(".part")) { count++; partItems.add(s); } } if (count < 5) { System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray())); } return strings.containsAll(names); } }; assertEquals(listFileNames(downloadDir), names); } finally { leech.stop(); seeder.stop(); } } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void process(final String uri, final String hostAddress, RequestHandler requestHandler) throws IOException { // Prepare the response headers. /** * Parse the query parameters into an announce request message. * * We need to rely on our own query parsing function because * SimpleHTTP's Query map will contain UTF-8 decoded parameters, which * doesn't work well for the byte-encoded strings we expect. */ HTTPAnnounceRequestMessage announceRequest = null; try { announceRequest = this.parseQuery(uri, hostAddress); } catch (MessageValidationException mve) { LoggerUtils.warnAndDebugDetails(logger, "Unable to parse request message. Request url is {}", uri, mve); serveError(Status.BAD_REQUEST, mve.getMessage(), requestHandler); return; } AnnounceRequestMessage.RequestEvent event = announceRequest.getEvent(); if (event == null) { event = AnnounceRequestMessage.RequestEvent.NONE; } TrackedTorrent torrent = myTorrentsRepository.getTorrent(announceRequest.getHexInfoHash()); // The requested torrent must be announced by the tracker if and only if myAcceptForeignTorrents is false if (!this.myAcceptForeignTorrents && torrent == null) { logger.warn("Requested torrent hash was: {}", announceRequest.getHexInfoHash()); serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.UNKNOWN_TORRENT, requestHandler); return; } final boolean isSeeder = (event == AnnounceRequestMessage.RequestEvent.COMPLETED) || (announceRequest.getLeft() == 0); if (myAddressChecker.isBadAddress(announceRequest.getIp())) { if (torrent == null) { writeEmptyResponse(announceRequest, requestHandler); } else { writeAnnounceResponse(torrent, null, isSeeder, requestHandler); } return; } final Peer peer = new Peer(announceRequest.getIp(), announceRequest.getPort()); try { torrent = myTorrentsRepository.putIfAbsentAndUpdate(announceRequest.getHexInfoHash(), new TrackedTorrent(announceRequest.getInfoHash()),event, ByteBuffer.wrap(announceRequest.getPeerId()), announceRequest.getHexPeerId(), announceRequest.getIp(), announceRequest.getPort(), announceRequest.getUploaded(), announceRequest.getDownloaded(), announceRequest.getLeft()); } catch (IllegalArgumentException iae) { LoggerUtils.warnAndDebugDetails(logger, "Unable to update peer torrent. Request url is {}", uri, iae); serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT, requestHandler); return; } // Craft and output the answer writeAnnounceResponse(torrent, peer, isSeeder, requestHandler); }
#vulnerable code public void process(final String uri, final String hostAddress, RequestHandler requestHandler) throws IOException { // Prepare the response headers. /** * Parse the query parameters into an announce request message. * * We need to rely on our own query parsing function because * SimpleHTTP's Query map will contain UTF-8 decoded parameters, which * doesn't work well for the byte-encoded strings we expect. */ HTTPAnnounceRequestMessage announceRequest = null; try { announceRequest = this.parseQuery(uri, hostAddress); } catch (MessageValidationException mve) { LoggerUtils.warnAndDebugDetails(logger, "Unable to parse request message. Request url is {}", uri, mve); serveError(Status.BAD_REQUEST, mve.getMessage(), requestHandler); return; } // The requested torrent must be announced by the tracker if and only if myAcceptForeignTorrents is false final ConcurrentMap<String, TrackedTorrent> torrentsMap = requestHandler.getTorrentsMap(); TrackedTorrent torrent = torrentsMap.get(announceRequest.getHexInfoHash()); if (!this.myAcceptForeignTorrents && torrent == null) { logger.warn("Requested torrent hash was: {}", announceRequest.getHexInfoHash()); serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.UNKNOWN_TORRENT, requestHandler); return; } if (torrent == null) { torrent = new TrackedTorrent(announceRequest.getInfoHash()); TrackedTorrent oldTorrent = requestHandler.getTorrentsMap().putIfAbsent(torrent.getHexInfoHash(), torrent); if (oldTorrent != null) { torrent = oldTorrent; } } AnnounceRequestMessage.RequestEvent event = announceRequest.getEvent(); PeerUID peerUID = new PeerUID(new InetSocketAddress(announceRequest.getIp(), announceRequest.getPort()), announceRequest.getHexInfoHash()); // When no event is specified, it's a periodic update while the client // is operating. If we don't have a peer for this announce, it means // the tracker restarted while the client was running. Consider this // announce request as a 'started' event. if ((event == null || AnnounceRequestMessage.RequestEvent.NONE.equals(event)) && torrent.getPeer(peerUID) == null) { event = AnnounceRequestMessage.RequestEvent.STARTED; } if (myAddressChecker.isBadAddress(announceRequest.getIp())) { writeAnnounceResponse(torrent, null, requestHandler); return; } if (event != null && torrent.getPeer(peerUID) == null && AnnounceRequestMessage.RequestEvent.STOPPED.equals(event)) { writeAnnounceResponse(torrent, null, requestHandler); return; } // If an event other than 'started' is specified and we also haven't // seen the peer on this torrent before, something went wrong. A // previous 'started' announce request should have been made by the // client that would have had us register that peer on the torrent this // request refers to. if (event != null && torrent.getPeer(peerUID) == null && !(AnnounceRequestMessage.RequestEvent.STARTED.equals(event) || AnnounceRequestMessage.RequestEvent.COMPLETED.equals(event))) { serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT, requestHandler); return; } // Update the torrent according to the announce event TrackedPeer peer = null; try { peer = torrent.update(event, ByteBuffer.wrap(announceRequest.getPeerId()), announceRequest.getHexPeerId(), announceRequest.getIp(), announceRequest.getPort(), announceRequest.getUploaded(), announceRequest.getDownloaded(), announceRequest.getLeft()); } catch (IllegalArgumentException iae) { LoggerUtils.warnAndDebugDetails(logger, "Unable to update peer torrent. Request url is {}", uri, iae); serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT, requestHandler); return; } // Craft and output the answer writeAnnounceResponse(torrent, peer, requestHandler); } #location 77 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void removeTorrent(TorrentHash torrentHash) { logger.info("Stopping seeding " + torrentHash.getHexInfoHash()); final TorrentsPair torrentsPair = torrentsStorage.removeActiveAndAnnounceableTorrent(torrentHash.getHexInfoHash()); SharedTorrent torrent = torrentsPair.getSharedTorrent(); if (torrent != null) { torrent.setClientState(ClientState.DONE); torrent.close(); } else { logger.warn(String.format("Torrent %s already removed from myTorrents", torrentHash.getHexInfoHash())); } sendStopEvent(torrentsPair.getAnnounceableFileTorrent(), torrentHash.getHexInfoHash()); }
#vulnerable code public void removeTorrent(TorrentHash torrentHash) { logger.info("Stopping seeding " + torrentHash.getHexInfoHash()); final TorrentsPair torrentsPair = torrentsStorage.removeActiveAndAnnounceableTorrent(torrentHash.getHexInfoHash()); SharedTorrent torrent = torrentsPair.getSharedTorrent(); if (torrent != null) { torrent.setClientState(ClientState.DONE); torrent.close(); } else { logger.warn(String.format("Torrent %s already removed from myTorrents", torrentHash.getHexInfoHash())); } final AnnounceableFileTorrent announceableFileTorrent = torrentsPair.getAnnounceableFileTorrent(); if (announceableFileTorrent == null) { logger.info("Announceable torrent {} not found in storage on removing torrent", torrentHash.getHexInfoHash()); } try { this.announce.forceAnnounce(announceableFileTorrent, this, STOPPED); } catch (IOException e) { LoggerUtils.warnAndDebugDetails(logger, "can not send force stop announce event on delete torrent {}", torrentHash.getHexInfoHash(), e); } } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void handlePeerDisconnected(SharingPeer peer) { final SharedTorrent peerTorrent = peer.getTorrent(); Peer p = new Peer(peer.getIp(), peer.getPort()); p.setPeerId(peer.getPeerId()); p.setTorrentHash(peer.getHexInfoHash()); PeerUID peerUID = new PeerUID(p.getAddress(), p.getHexInfoHash()); SharingPeer sharingPeer = this.peersStorage.removeSharingPeer(peerUID); logger.debug("Peer {} disconnected, [{}/{}].", new Object[]{ peer, getConnectedPeers().size(), this.peersStorage.getSharingPeers().size() }); }
#vulnerable code @Override public void handlePeerDisconnected(SharingPeer peer) { final SharedTorrent peerTorrent = peer.getTorrent(); Peer p = new Peer(peer.getIp(), peer.getPort()); p.setPeerId(peer.getPeerId()); p.setTorrentHash(peer.getHexInfoHash()); PeerUID peerUID = new PeerUID(p.getStringPeerId(), p.getHexInfoHash()); SharingPeer sharingPeer = this.peersStorage.removeSharingPeer(peerUID); logger.debug("Peer {} disconnected, [{}/{}].", new Object[]{ peer, getConnectedPeers().size(), this.peersStorage.getSharingPeers().size() }); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public MetadataBuilder addFile(@NotNull File source, @NotNull String path) { if (!source.isFile()) { throw new IllegalArgumentException(source + " is not exist"); } checkHashingResultIsNotSet(); filesPaths.add(path); dataSources.add(new FileSourceHolder(source)); return this; }
#vulnerable code public MetadataBuilder addFile(@NotNull File source, @NotNull String path) { if (!source.isFile()) { throw new IllegalArgumentException(source + " is not exist"); } sources.add(new Source(source, path)); return this; } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void send(PeerMessage message) throws IllegalStateException { logger.trace("Sending msg {} to {}", message.getType(), this); if (this.isConnected()) { ByteBuffer data = message.getData(); data.rewind(); connectionManager.offerWrite(new WriteTask(socketChannel, data, new WriteListener() { @Override public void onWriteFailed(String message, Throwable e) { logger.debug(message, e); unbind(true); } @Override public void onWriteDone() { } }), 1, TimeUnit.SECONDS); } else { logger.info("Attempting to send a message to non-connected peer {}!", this); unbind(true); } }
#vulnerable code public void send(PeerMessage message) throws IllegalStateException { logger.trace("Sending msg {} to {}", message.getType(), this); if (this.isConnected()) { ByteBuffer data = message.getData(); data.rewind(); boolean writeTaskAdded = connectionManager.offerWrite(new WriteTask(socketChannel, data, new WriteListener() { @Override public void onWriteFailed(String message, Throwable e) { logger.debug(message, e); unbind(true); } @Override public void onWriteDone() { } }), 1, TimeUnit.SECONDS); if (!writeTaskAdded) { unbind(true); } } else { logger.info("Attempting to send a message to non-connected peer {}!", this); unbind(true); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { // key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); timeoutClose(); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } }
#vulnerable code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } }
#vulnerable code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } ByteBufferStream.free(packet.buffers[1]); clearTimeout(); handler.onSended(this, packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { // key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); timeoutClose(); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } }
#vulnerable code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Map<String, String> filterInfo(Map<String, String> info) { Map<String, String> newInfo = Maps.newHashMap(info); String limitLine = newInfo.remove(PUSH_PROPERTIES_LIMIT); Set<String> limitKeys = getLimitKeys(limitLine); if (limitKeys.isEmpty()) { return newInfo; } ImmutableMap.Builder<String, String> result = ImmutableMap.builder(); for (String key : limitKeys) { result.put(key, newInfo.get(key)); } return result.build(); }
#vulnerable code private Map<String, String> filterInfo(Map<String, String> info) { HashMap<String, String> newInfo = Maps.newHashMap(info); String limit = newInfo.get(PUSH_PROPERTIES_LIMIT); if (Strings.isNullOrEmpty(limit)) { newInfo.remove(PUSH_PROPERTIES_LIMIT); return ImmutableMap.copyOf(newInfo); } List<String> limitList = PUSH_LIMIT_SPLITTER.splitToList(limit); if (limitList.size() == 0) { newInfo.remove(PUSH_PROPERTIES_LIMIT); return ImmutableMap.copyOf(newInfo); } ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (String key : limitList) { builder.put(key, newInfo.get(key)); } return builder.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { // Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") // .header("accept", "application/json") // .field("param1", "value1") // .field("param2","bye") // .asJsonAsync(); // // assertNotNull(future); // HttpResponse<JsonNode> jsonResponse = future.get(); // // assertTrue(jsonResponse.getHeaders().size() > 0); // assertTrue(jsonResponse.getBody().toString().length() > 0); // assertFalse(jsonResponse.getRawBody() == null); // assertEquals(200, jsonResponse.getCode()); // // JsonNode json = jsonResponse.getBody(); // assertFalse(json.isArray()); // assertNotNull(json.getObject()); // assertNotNull(json.getArray()); // assertEquals(1, json.getArray().length()); // assertNotNull(json.getArray().get(0)); Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2", "value2") .asJsonAsync(new Callback<JsonNode>() { public void failed(Exception e) { System.out.println("The request has failed"); } public void completed(HttpResponse<JsonNode> response) { int code = response.getCode(); Map<String, String> headers = response.getHeaders(); JsonNode body = response.getBody(); InputStream rawBody = response.getRawBody(); } public void cancelled() { System.out.println("The request has been cancelled"); } }); }
#vulnerable code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2","bye") .asJsonAsync(); assertNotNull(future); HttpResponse<JsonNode> jsonResponse = future.get(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getCode()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); MultipartBody request = Unirest.post(MockServer.HOST + "/post") .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) .field("name", "Mark") .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); HttpResponse<JsonNode> jsonResponse = request .asJson(); assertEquals(200, jsonResponse.getStatus()); FormCapture json = TestUtils.read(jsonResponse, FormCapture.class); json.assertHeader("Accept", ContentType.MULTIPART_FORM_DATA.toString()); json.assertQuery("name", "Mark"); assertEquals("application/octet-stream", json.getFile("image.jpg").type); // assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); // assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); }
#vulnerable code @Test public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); MultipartBody request = Unirest.post(MockServer.HOST + "/post") .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) .field("name", "Mark") .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); HttpResponse<JsonNode> jsonResponse = request .asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); JSONObject object = json.getObject(); assertNotNull(object); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(object.getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetMultiple() throws JSONException, UnirestException { for (int i = 1; i <= 20; i++) { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON + "?try=" + i).asJson(); parse(response).assertQuery("try", String.valueOf(i)); } }
#vulnerable code @Test public void testGetMultiple() throws JSONException, UnirestException { for (int i = 1; i <= 20; i++) { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get?try=" + i).asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("try"), ((Integer) i).toString()); } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPostCollection() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .field("name", Arrays.asList("Mark", "Tom")) .asJson(); parse(response) .assertParam("name", "Mark") .assertParam("name", "Tom"); }
#vulnerable code @Test public void testPostCollection() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("name", Arrays.asList("Mark", "Tom")).asJson(); JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testQueryStringEncoding() throws JSONException, UnirestException { String testKey = "email2=someKey&email"; String testValue = "[email protected]"; HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .queryString(testKey, testValue) .asJson(); parse(response).assertQuery(testKey, testValue); }
#vulnerable code @Test public void testQueryStringEncoding() throws JSONException, UnirestException { String testKey = "email2=someKey&email"; String testValue = "[email protected]"; HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString(testKey, testValue).asJson(); assertEquals(testValue, response.getBody().getObject().getJSONObject("args").getString(testKey)); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetUTF8() { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .header("accept", "application/json") .queryString("param3", "こんにちは") .asJson(); FormCapture json = TestUtils.read(response, FormCapture.class); json.assertQuery("param3", "こんにちは"); }
#vulnerable code @Test public void testGetUTF8() { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString("param3", "こんにちは").asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("param3"), "こんにちは"); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testObjectMapperWrite() { Unirest.setObjectMapper(new JacksonObjectMapper()); GetResponse postResponseMock = new GetResponse(); postResponseMock.setUrl(MockServer.POST); HttpResponse<JsonNode> postResponse = Unirest.post(postResponseMock.getUrl()) .header("accept", "application/json") .header("Content-Type", "application/json") .body(postResponseMock) .asJson(); assertEquals(200, postResponse.getStatus()); parse(postResponse) .asserBody("{\"url\":\"http://localhost:4567/post\"}"); }
#vulnerable code @Test public void testObjectMapperWrite() { Unirest.setObjectMapper(new JacksonObjectMapper()); GetResponse postResponseMock = new GetResponse(); postResponseMock.setUrl("http://httpbin.org/post"); HttpResponse<JsonNode> postResponse = Unirest.post(postResponseMock.getUrl()).header("accept", "application/json").header("Content-Type", "application/json").body(postResponseMock).asJson(); assertEquals(200, postResponse.getStatus()); assertEquals(postResponse.getBody().getObject().getString("data"), "{\"url\":\"http://httpbin.org/post\"}"); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDelete() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.delete(MockServer.DELETE).asJson(); assertEquals(200, response.getStatus()); response = Unirest.delete(MockServer.DELETE) .field("name", "mark") .field("foo","bar") .asJson(); RequestCapture parse = parse(response); parse.assertParam("name", "mark"); parse.assertParam("foo", "bar"); }
#vulnerable code @Test public void testDelete() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.delete("http://httpbin.org/delete").asJson(); assertEquals(200, response.getStatus()); response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson(); assertEquals("mark", response.getBody().getObject().getJSONObject("form").getString("name")); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCaseInsensitiveHeaders() { GetRequest request = Unirest.get(MockServer.GET) .header("Name", "Marco"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); parse(request.asJson()) .assertHeader("Name", "Marco"); request = Unirest.get(MockServer.GET).header("Name", "Marco").header("Name", "John"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("John", request.getHeaders().get("name").get(1)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("John", request.getHeaders().get("NAme").get(1)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); assertEquals("John", request.getHeaders().get("Name").get(1)); }
#vulnerable code @Test public void testCaseInsensitiveHeaders() { GetRequest request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); JSONObject headers = request.asJson().getBody().getObject().getJSONObject("headers"); assertEquals("Marco", headers.getString("Name")); request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco").header("Name", "John"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("John", request.getHeaders().get("name").get(1)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("John", request.getHeaders().get("NAme").get(1)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); assertEquals("John", request.getHeaders().get("Name").get(1)); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { Future<HttpResponse<JsonNode>> future = Unirest.post(MockServer.POST) .header("accept", "application/json") .field("param1", "value1") .field("param2", "bye") .asJsonAsync(); assertNotNull(future); RequestCapture req = parse(future.get()); req.assertParam("param1", "value1"); req.assertParam("param2", "bye"); }
#vulnerable code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(); assertNotNull(future); HttpResponse<JsonNode> jsonResponse = future.get(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } #location 8 #vulnerability type NULL_DEREFERENCE