input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Override public Object handle(HttpExchange x) throws Exception { int event = U.num(x.data("event")); TagContext ctx = Pages.ctx(x); Map<Integer, Object> inp = Pages.inputs(x); ctx.emit(inp, event); Object page = U.newInstance(currentPage(x)); ctx = Tags.context(); x.setSession(Pages.SESSION_CTX, ctx); Object body = Pages.contentOf(x, page); if (body == null) { } if (body instanceof HttpExchange) { return body; } System.out.println(body); String html = PageRenderer.get().toHTML(ctx, body, x); Map<String, String> changes = U.map(); changes.put("body", html); x.json(); return changes; } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Object handle(HttpExchange x) throws Exception { return Pages.emit(x); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void reset() { super.reset(); isGet.value = false; isKeepAlive.value = false; verb.reset(); uri.reset(); path.reset(); query.reset(); protocol.reset(); body.reset(); multipartBoundary.reset(); params.reset(); headersKV.reset(); headers.reset(); cookies.reset(); data.reset(); files.reset(); parsedParams = false; parsedHeaders = false; parsedBody = false; total = -1; writesBody = false; bodyPos = -1; hasContentType = false; responses = null; responseCode = -1; } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void reset() { super.reset(); isGet.value = false; isKeepAlive.value = false; verb.reset(); uri.reset(); path.reset(); query.reset(); protocol.reset(); body.reset(); multipartBoundary.reset(); params.reset(); headersKV.reset(); headers.reset(); cookies.reset(); data.reset(); files.reset(); parsedParams = false; parsedHeaders = false; parsedBody = false; resetResponse(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String loadResourceAsString(String filename) { return new String(loadBytes(filename)); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public static String loadResourceAsString(String filename) { byte[] bytes = loadBytes(filename); return bytes != null ? new String(bytes) : null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static char[] readPassword(String msg) { Console console = System.console(); if (console != null) { return console.readPassword(msg); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); U.print(msg); try { return reader.readLine().toCharArray(); } catch (IOException e) { throw U.rte(e); } } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code private static char[] readPassword(String msg) { Console console = System.console(); if (console != null) { return console.readPassword(msg); } else { U.print(msg); return readLine().toCharArray(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEncryptWithCustomPassword() { byte[] key = Crypto.pbkdf2("pass".toCharArray()); for (int i = 0; i < 10000; i++) { String msg1 = "" + i; byte[] enc = Crypto.encrypt(msg1.getBytes(), key); byte[] dec = Crypto.decrypt(enc, key); String msg2 = new String(dec); eq(msg2, msg1); } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testEncryptWithCustomPassword() { CryptoKey key = CryptoKey.from("pass".toCharArray()); for (int i = 0; i < 10000; i++) { String msg1 = "" + i; byte[] enc = Crypto.encrypt(msg1.getBytes(), key); byte[] dec = Crypto.decrypt(enc, key); String msg2 = new String(dec); eq(msg2, msg1); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 30000) public void testJDBCPoolC3P0() { JDBC.h2("test1").pooled(); C3P0ConnectionPool pool = (C3P0ConnectionPool) JDBC.defaultApi().pool(); ComboPooledDataSource c3p0 = pool.pool(); // validate default config eq(c3p0.getMinPoolSize(), 5); eq(c3p0.getInitialPoolSize(), 5); eq(c3p0.getAcquireIncrement(), 5); eq(c3p0.getMaxPoolSize(), 100); eq(c3p0.getMaxStatementsPerConnection(), 10); JDBC.execute("create table abc (id int, name varchar)"); JDBC.execute("insert into abc values (?, ?)", 123, "xyz"); final Map<String, ?> expected = U.map("id", 123, "name", "xyz"); Msc.benchmarkMT(100, "select", 100000, () -> { Map<String, Object> record = U.single(JDBC.query("select id, name from abc")); record = Msc.lowercase(record); eq(record, expected); }); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test(timeout = 30000) public void testJDBCPoolC3P0() { JDBC.h2("test1"); C3P0ConnectionPool pool = (C3P0ConnectionPool) JDBC.defaultApi().init().pool(); ComboPooledDataSource c3p0 = pool.pool(); // validate default config eq(c3p0.getMinPoolSize(), 5); eq(c3p0.getInitialPoolSize(), 5); eq(c3p0.getAcquireIncrement(), 5); eq(c3p0.getMaxPoolSize(), 100); eq(c3p0.getMaxStatementsPerConnection(), 10); JDBC.execute("create table abc (id int, name varchar)"); JDBC.execute("insert into abc values (?, ?)", 123, "xyz"); final Map<String, ?> expected = U.map("id", 123, "name", "xyz"); Msc.benchmarkMT(100, "select", 100000, () -> { Map<String, Object> record = U.single(JDBC.query("select id, name from abc")); record = Msc.lowercase(record); eq(record, expected); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private byte[] responseToBytes() { try { return response.renderToBytes(); } catch (Throwable e) { HttpIO.error(this, e, custom().errorHandler()); try { return response.renderToBytes(); } catch (Exception e1) { Log.error("Internal rendering error!", e1); return HttpUtils.getErrorMessageAndSetCode(response, e1).getBytes(); } } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private byte[] responseToBytes() { try { return response.renderToBytes(); } catch (Throwable e) { HttpIO.error(this, e, Customization.of(this).errorHandler()); try { return response.renderToBytes(); } catch (Exception e1) { Log.error("Internal rendering error!", e1); return HttpUtils.getErrorMessageAndSetCode(response, e1).getBytes(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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."); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code @Override public void render(Req req, Object value, OutputStream out) throws Exception { Customization.of(req).objectMapper().writeValue(out, value); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void getClassesFromDir(Collection<Class<?>> classes, File root, File dir, String pkg, Pattern regex, Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) { U.must(dir.isDirectory()); Log.debug("Traversing directory", "root", root, "dir", dir); for (File file : dir.listFiles()) { if (file.isDirectory()) { getClassesFromDir(classes, root, file, pkg, regex, filter, annotated, classLoader); } else { String rootPath = U.trimr(root.getAbsolutePath(), File.separatorChar); int from = rootPath.length() + 1; String relName = file.getAbsolutePath().substring(from); if (!ignore(relName)) { scanFile(classes, regex, filter, annotated, classLoader, relName); } } } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private static void getClassesFromDir(Collection<Class<?>> classes, File root, File dir, String pkg, Pattern regex, Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) { U.must(dir.isDirectory()); Log.debug("Traversing directory", "root", root, "dir", dir); File[] files = dir.listFiles(); if (files == null) { Log.warn("Not a folder!", "dir", dir); return; } for (File file : files) { if (file.isDirectory()) { getClassesFromDir(classes, root, file, pkg, regex, filter, annotated, classLoader); } else { String rootPath = U.trimr(root.getAbsolutePath(), File.separatorChar); int from = rootPath.length() + 1; String relName = file.getAbsolutePath().substring(from); if (!ignore(relName)) { scanFile(classes, regex, filter, annotated, classLoader, relName); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code protected byte[] loadRes(String filename) { InputStream input = TestCommons.class.getClassLoader().getResourceAsStream(filename); return input != null ? readBytes(input) : null; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(sdDbServers); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(rpcConfig.getSdDbServers()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initDbConnectServer() throws Exception{ worldRpcConnectManager.initManager(); dbRpcConnnectManngeer.initServers(sdDbServers); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(sdDbServers); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initWorldConnectedServer() throws Exception { worldRpcConnectManager.initManager(); worldRpcConnectManager.initServers(sdWorldServers); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initWorldConnectedServer() throws Exception { worldRpcConnectManager.initManager(); worldRpcConnectManager.initServers(rpcConfig.getSdWorldServers()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception{ final String data = "博主邮箱:[email protected]"; byte[] bytes = data.getBytes(Charset.forName("UTF-8")); InetSocketAddress targetHost = new InetSocketAddress("127.0.0.1", 9999); // 发送udp内容 DatagramSocket socket = new DatagramSocket(); socket.send(new DatagramPacket(bytes, 0, bytes.length, targetHost)); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws Exception{ final String data = "博主邮箱:[email protected]"; byte[] bytes = data.getBytes(Charset.forName("UTF-8")); InetSocketAddress targetHost = new InetSocketAddress("127.0.0.1", 9999); // 发送udp内容 DatagramSocket socket = new DatagramSocket(); socket.send(new DatagramPacket(bytes, 0, bytes.length, targetHost)); while (true) { //接收数据报的包 DatagramPacket packet = new DatagramPacket(bytes, bytes.length); // DatagramSocket localUDPSocket = LocalUDPSocketProvider.getInstance().getLocalUDPSocket(); // if (localUDPSocket == null || (localUDPSocket.isClosed())) { // continue; // } socket.receive(packet); //解析发来的数据 String response = new String(packet.getData(), 0, packet.getLength(), CharsetUtil.UTF_8); utilLogger.debug("收到服务器信息" + response); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(sdDbServers); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(rpcConfig.getSdDbServers()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initWorldConnectedServer() throws Exception { worldRpcConnectManager.initManager(); worldRpcConnectManager.initServers(sdWorldServers); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initWorldConnectedServer() throws Exception { worldRpcConnectManager.initManager(); worldRpcConnectManager.initServers(rpcConfig.getSdWorldServers()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(sdDbServers); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(rpcConfig.getSdDbServers()); }
Below is the vulnerable code, please generate the patch based on the following information.
#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 41 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") public void init() throws Exception { initWorldConnectedServer(); initGameConnectedServer(); initDbConnectServer(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(sdGameServers); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(rpcConfig.getSdGameServers()); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code @SuppressWarnings("unchecked") public void init() throws Exception { initWorldConnectedServer(); initGameConnectedServer(); initDbConnectServer(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(sdGameServers); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(rpcConfig.getSdGameServers()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initWorldConnectedServer() throws Exception { worldRpcConnectManager.initManager(); worldRpcConnectManager.initServers(sdWorldServers); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initWorldConnectedServer() throws Exception { worldRpcConnectManager.initManager(); worldRpcConnectManager.initServers(rpcConfig.getSdWorldServers()); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code @SuppressWarnings("unchecked") public void init() throws Exception { initWorldConnectedServer(); initGameConnectedServer(); initDbConnectServer(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(sdGameServers); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(rpcConfig.getSdGameServers()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initGameConnectedServer() throws Exception { worldRpcConnectManager.initManager(); gameRpcConnecetMananger.initServers(sdGameServers); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void initGameConnectedServer() throws Exception { gameRpcConnecetMananger.initManager(); gameRpcConnecetMananger.initServers(sdGameServers); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code Object fromDb(DBObject dbObject, final Object entity, EntityCache cache) { // check the history key (a key is the namespace + id) if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null && getMappedClass(entity).getEntityAnnotation() != null) { Key key = new Key(entity.getClass(), dbObject.get(ID_KEY)); Object cachedInstance = cache.getEntity(key); if (cachedInstance != null) return cachedInstance; else cache.putEntity(key, entity); // to avoid stackOverflow in // recursive refs } MappedClass mc = getMappedClass(entity); dbObject = (BasicDBObject) mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this); try { for (MappedField mf : mc.getPersistenceFields()) { readMappedField(dbObject, mf, entity, cache); } } catch (Exception e) { throw new RuntimeException(e); } if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) { Key key = new Key(entity.getClass(), dbObject.get(ID_KEY)); cache.putEntity(key, entity); } mc.callLifecycleMethods(PostLoad.class, entity, dbObject, this); return entity; } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code Object fromDb(DBObject dbObject, final Object entity, EntityCache cache) { // check the history key (a key is the namespace + id) if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null && getMappedClass(entity).getEntityAnnotation() != null) { Key key = new Key(entity.getClass(), dbObject.get(ID_KEY)); Object cachedInstance = cache.getEntity(key); if (cachedInstance != null) return cachedInstance; else cache.putEntity(key, entity); // to avoid stackOverflow in recursive refs } //hack to bypass things and just read the value. if (entity instanceof MappedField) { readMappedField(dbObject, (MappedField) entity, entity, cache); return entity; } MappedClass mc = getMappedClass(entity); dbObject = (BasicDBObject) mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this); try { for (MappedField mf : mc.getPersistenceFields()) { readMappedField(dbObject, mf, entity, cache); } } catch (Exception e) { throw new RuntimeException(e); } if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) { Key key = new Key(entity.getClass(), dbObject.get(ID_KEY)); cache.putEntity(key, entity); } mc.callLifecycleMethods(PostLoad.class, entity, dbObject, this); return entity; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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)); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code Object fromDb(DBObject dbObject, final Object entity, EntityCache cache) { // check the history key (a key is the namespace + id) if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null && getMappedClass(entity).getEntityAnnotation() != null) { Key key = new Key(entity.getClass(), dbObject.get(ID_KEY)); Object cachedInstance = cache.getEntity(key); if (cachedInstance != null) return cachedInstance; else cache.putEntity(key, entity); // to avoid stackOverflow in recursive refs } //hack to bypass things and just read the value. if (entity instanceof MappedField) { readMappedField(dbObject, (MappedField) entity, entity, cache); return entity; } MappedClass mc = getMappedClass(entity); dbObject = (BasicDBObject) mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this); try { for (MappedField mf : mc.getPersistenceFields()) { readMappedField(dbObject, mf, entity, cache); } } catch (Exception e) { throw new RuntimeException(e); } if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) { Key key = new Key(entity.getClass(), dbObject.get(ID_KEY)); cache.putEntity(key, entity); } mc.callLifecycleMethods(PostLoad.class, entity, dbObject, this); return entity; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code Object fromDb(DBObject dbObject, final Object entity, EntityCache cache) { //hack to bypass things and just read the value. if (entity instanceof MappedField) { readMappedField(dbObject, (MappedField) entity, entity, cache); return entity; } // check the history key (a key is the namespace + id) if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null && getMappedClass(entity).getEntityAnnotation() != null) { Key key = new Key(entity.getClass(), dbObject.get(ID_KEY)); Object cachedInstance = cache.getEntity(key); if (cachedInstance != null) return cachedInstance; else cache.putEntity(key, entity); // to avoid stackOverflow in recursive refs } MappedClass mc = getMappedClass(entity); dbObject = (BasicDBObject) mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this); try { for (MappedField mf : mc.getPersistenceFields()) { readMappedField(dbObject, mf, entity, cache); } } catch (Exception e) { throw new RuntimeException(e); } if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) { Key key = new Key(entity.getClass(), dbObject.get(ID_KEY)); cache.putEntity(key, entity); } mc.callLifecycleMethods(PostLoad.class, entity, dbObject, this); return entity; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object toMongoObject(final MappedField mf, final MappedClass mc, final Object value) { Object mappedValue = value; //convert the value to Key (DBRef) if the field is @Reference or type is Key/DBRef, or if the destination class is an @Entity if (isAssignable(mf, value) || isEntity(mc)) { try { if (value instanceof Iterable) { if(isMapped(mf.getSubClass())) { mappedValue = getDBRefs((Iterable) value); } else { mappedValue = value; } } else { final Key<?> key = (value instanceof Key) ? (Key<?>) value : getKey(value); if (key == null) { mappedValue = toMongoObject(value, false); } else { mappedValue = keyToRef(key); if (mappedValue == value) { throw new ValidationException("cannot map to @Reference/Key<T>/DBRef field: " + value); } } } } catch (Exception e) { log.error("Error converting value(" + value + ") to reference.", e); mappedValue = toMongoObject(value, false); } } else if (mf != null && mf.hasAnnotation(Serialized.class)) { //serialized try { mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression()); } catch (IOException e) { throw new RuntimeException(e); } } else if (value instanceof DBObject) { //pass-through mappedValue = value; } else { mappedValue = toMongoObject(value, EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf)); if (mappedValue instanceof BasicDBList) { final BasicDBList list = (BasicDBList) mappedValue; if (list.size() != 0) { if (!EmbeddedMapper.shouldSaveClassName(extractFirstElement(value), list.get(0), mf)) { for (Object o : list) { if (o instanceof DBObject) { ((DBObject) o).removeField(CLASS_NAME_FIELDNAME); } } } } } else if (mappedValue instanceof DBObject && !EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf)) { ((DBObject) mappedValue).removeField(CLASS_NAME_FIELDNAME); } } return mappedValue; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public Object toMongoObject(final MappedField mf, final MappedClass mc, final Object value) { Object mappedValue = value; //convert the value to Key (DBRef) if the field is @Reference or type is Key/DBRef, or if the destination class is an @Entity if (isAssignable(mf, value) || isEntity(mc)) { try { if (value instanceof Iterable) { MappedClass mapped = getMappedClass(mf.getSubClass()); if(mapped != null && Key.class.isAssignableFrom(mapped.getClazz())) { mappedValue = getDBRefs((Iterable) value); } else { mappedValue = value; } } else { final Key<?> key = (value instanceof Key) ? (Key<?>) value : getKey(value); if (key == null) { mappedValue = toMongoObject(value, false); } else { mappedValue = keyToRef(key); if (mappedValue == value) { throw new ValidationException("cannot map to @Reference/Key<T>/DBRef field: " + value); } } } } catch (Exception e) { log.error("Error converting value(" + value + ") to reference.", e); mappedValue = toMongoObject(value, false); } } else if (mf != null && mf.hasAnnotation(Serialized.class)) { //serialized try { mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression()); } catch (IOException e) { throw new RuntimeException(e); } } else if (value instanceof DBObject) { //pass-through mappedValue = value; } else { mappedValue = toMongoObject(value, EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf)); if (mappedValue instanceof BasicDBList) { final BasicDBList list = (BasicDBList) mappedValue; if (list.size() != 0) { if (!EmbeddedMapper.shouldSaveClassName(extractFirstElement(value), list.get(0), mf)) { for (Object o : list) { if (o instanceof DBObject) { ((DBObject) o).removeField(CLASS_NAME_FIELDNAME); } } } } } else if (mappedValue instanceof DBObject && !EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf)) { ((DBObject) mappedValue).removeField(CLASS_NAME_FIELDNAME); } } return mappedValue; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> UpdateResults<T> update(T ent, UpdateOperations<T> ops) { MappedClass mc = mapr.getMappedClass(ent); Query<T> q = (Query<T>) createQuery(mc.getClazz()); q.disableValidation().filter(Mapper.ID_KEY, getId(ent)); if (mc.getFieldsAnnotatedWith(Version.class).size() > 0) { MappedField versionMF = mc.getFieldsAnnotatedWith(Version.class).get(0); Long oldVer = (Long)versionMF.getFieldValue(ent); q.filter(versionMF.getNameToStore(), oldVer); ops.set(versionMF.getNameToStore(), VersionHelper.nextValue(oldVer)); } return update(q, ops); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public <T> UpdateResults<T> update(T ent, UpdateOperations<T> ops) { if (ent instanceof Query) return update((Query<T>)ent, ops); MappedClass mc = mapr.getMappedClass(ent); Query<T> q = (Query<T>) createQuery(mc.getClazz()); q.disableValidation().filter(Mapper.ID_KEY, getId(ent)); if (mc.getFieldsAnnotatedWith(Version.class).size() > 0) { MappedField versionMF = mc.getFieldsAnnotatedWith(Version.class).get(0); Long oldVer = (Long)versionMF.getFieldValue(ent); q.filter(versionMF.getNameToStore(), oldVer); ops.set(versionMF.getNameToStore(), VersionHelper.nextValue(oldVer)); } return update(q, ops); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Key<?> exists(final Object entityOrKey) { final Object unwrapped = ProxyHelper.unwrap(entityOrKey); final Key<?> key = mapper.getKey(unwrapped); final Object id = key.getId(); if (id == null) { throw new MappingException("Could not get id for " + unwrapped.getClass().getName()); } String collName = key.getKind(); if (collName == null) { collName = getCollection(key.getKindClass()).getName(); } return find(collName, key.getKindClass()).filter(Mapper.ID_KEY, key.getId()).getKey(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public Key<?> exists(final Object entityOrKey) { final Query<?> query = buildExistsQuery(entityOrKey); return query.getKey(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> Iterable<Key<T>> insert(Iterable<T> entities, WriteConcern wc) { ArrayList<DBObject> ents = entities instanceof List ? new ArrayList<DBObject>(((List<T>)entities).size()) : new ArrayList<DBObject>(); Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>(); T lastEntity = null; for (T ent : entities) { ents.add(entityToDBObj(ent, involvedObjects)); lastEntity = ent; } DBCollection dbColl = getCollection(lastEntity); WriteResult wr = null; DBObject[] dbObjs = new DBObject[ents.size()]; dbColl.insert(ents.toArray(dbObjs), wc); throwOnError(wc, wr); ArrayList<Key<T>> savedKeys = new ArrayList<Key<T>>(); Iterator<T> entitiesIT = entities.iterator(); Iterator<DBObject> dbObjsIT = ents.iterator(); while (entitiesIT.hasNext()) { T entity = entitiesIT.next(); DBObject dbObj = dbObjsIT.next(); savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects)); } return savedKeys; } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code public <T> Iterable<Key<T>> insert(Iterable<T> entities, WriteConcern wc) { //TODO: Do this without creating another iterator DBCollection dbColl = getCollection(entities.iterator().next()); return insert(dbColl, entities, wc); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getCollectionName(Object object) { MappedClass mc = getMappedClass(object); return mc.getCollectionName(); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public String getCollectionName(Object object) { if (object == null) throw new IllegalArgumentException(); MappedClass mc = getMappedClass(object); return mc.getCollectionName(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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 88 #vulnerability type CHECKERS_PRINTF_ARGS
#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); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void load() throws ConfigurationException { Collection<PluginConfig> plugins = configuration.getPlugins(); PluginConfig plugin = null; Collection<File> jarsToLoad = new LinkedList<File>(); try { if (plugins != null) { Iterator<PluginConfig> it = plugins.iterator(); initIvy(); while (it.hasNext()) { plugin = it.next(); addArtifact(plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion()); } jarsToLoad = resolveArtifacts(); URL[] urls = new URL[jarsToLoad.size()]; int i = 0; for (File jar : jarsToLoad) { urls[i] = jar.toURI().toURL(); i++; } URLClassLoader childClassLoader = new URLClassLoader(urls, configuration.getClassLoader()); configuration.setClassLoader(childClassLoader); } } catch (ConfigurationException e) { throw e; } catch (Exception e) { if (plugin == null) { throw new ConfigurationException( "Unable to initialize ivy configuration", e); } else { throw new ConfigurationException( "Unable to resolve the plugin: " + plugin.getGroupId() + " : " + plugin.getArtifactId() + " : " + plugin.getVersion(), e); } } } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void load() throws ConfigurationException { Collection<PluginConfig> plugins = configuration.getPlugins(); PluginConfig plugin = null; Collection<File> jarsToLoad = new LinkedList<File>(); ConfigurationException ce = null; try { if (plugins != null) { Iterator<PluginConfig> it = plugins.iterator(); initIvy(); while (it.hasNext()) { plugin = it.next(); addArtifact(plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion()); } jarsToLoad = resolveArtifacts(); URL[] urls = new URL[jarsToLoad.size()]; int i = 0; for (File jar : jarsToLoad) { urls[i] = jar.toURI().toURL(); i++; } URLClassLoader childClassLoader = new URLClassLoader(urls, configuration.getClassLoader()); configuration.setClassLoader(childClassLoader); } } catch (Exception e) { if (!(e instanceof ConfigurationException)) { if (plugin == null) { ce = new ConfigurationException( "Unable to initialize ivy configuration:" + e.getMessage()); } else { ce = new ConfigurationException( "Unable to resolve the plugin: " + plugin.getGroupId() + " : " + plugin.getArtifactId() + " : " + plugin.getVersion() + ". Reason : " + e.getMessage()); } } else { ce = (ConfigurationException) e; } throw ce; } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(Object n, VisitorContext vc) throws Exception { File out = null; boolean createdEmptyFile = false; if (vc != null) { out = (File) vc.get(AbstractWalker.ORIGINAL_FILE_KEY); } if (out == null) { log.debug("Creating the target source file. This is not the original source file."); out = createOutputDirectory(n); createdEmptyFile = true; } else { log.debug("The system will overwrite the original source file."); } boolean write = true; if (out != null) { log.debug("Analyzing exclude and include rules"); String aux = FilenameUtils.normalize(out.getAbsolutePath(), true); if (excludes != null) { for (int i = 0; i < excludes.length && write; i++) { if (!excludes[i].startsWith(normalizedOutputDirectory)) { excludes[i] = normalizedOutputDirectory + "/" + excludes[i]; if (excludes[i].endsWith("\\*\\*")) { excludes[i] = excludes[i].substring(0, excludes[i].length() - 2); } } write = !(excludes[i].startsWith(aux) || FilenameUtils .wildcardMatch(aux, excludes[i])); } } if (includes != null && write) { write = false; for (int i = 0; i < includes.length && !write; i++) { if (!includes[i].startsWith(normalizedOutputDirectory)) { includes[i] = normalizedOutputDirectory + "/" + includes[i]; if (includes[i].endsWith("\\*\\*")) { includes[i] = includes[i].substring(0, includes[i].length() - 2); } } write = includes[i].startsWith(aux) || FilenameUtils.wildcardMatch(aux, includes[i]); } } if (write) { Writer writer = null; try { String content = getContent(n, vc); if (content != null && !"".equals(content)) { char endLineChar = getEndLineChar(out); writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(out), getEncoding())); if (vc.get("append") == null) { write(content, writer, endLineChar); } else { if (Boolean.TRUE.equals(vc.get("append"))) { append(content, writer, endLineChar); } else { write(content, writer, endLineChar); } } Summary.getInstance().addFile(out); log.debug(out.getPath() + " written "); } else { log.error(out.getPath() + " does not have valid content"); throw new WalkModException("blank code is returned"); } } finally { if (writer != null) { writer.close(); } } } else { if (createdEmptyFile && out != null && out.isFile()) { out.delete(); } log.debug("skipping " + out.getParent()); } } else { log.debug("There is no place where to write."); } } #location 59 #vulnerability type RESOURCE_LEAK
#fixed code public void write(Object n, VisitorContext vc) throws Exception { File out = null; boolean createdEmptyFile = false; if (vc != null) { out = (File) vc.get(AbstractWalker.ORIGINAL_FILE_KEY); } if (out == null) { log.debug("Creating the target source file. This is not the original source file."); out = createOutputDirectory(n); createdEmptyFile = true; } else { log.debug("The system will overwrite the original source file."); } boolean write = true; if (out != null) { log.debug("Analyzing exclude and include rules"); String aux = FilenameUtils.normalize(out.getAbsolutePath(), true); if (excludes != null) { for (int i = 0; i < excludes.length && write; i++) { if (!excludes[i].startsWith(normalizedOutputDirectory)) { excludes[i] = normalizedOutputDirectory + "/" + excludes[i]; if (excludes[i].endsWith("\\*\\*")) { excludes[i] = excludes[i].substring(0, excludes[i].length() - 2); } } write = !(excludes[i].startsWith(aux) || FilenameUtils .wildcardMatch(aux, excludes[i])); } } if (includes != null && write) { write = false; for (int i = 0; i < includes.length && !write; i++) { if (!includes[i].startsWith(normalizedOutputDirectory)) { includes[i] = normalizedOutputDirectory + "/" + includes[i]; if (includes[i].endsWith("\\*\\*")) { includes[i] = includes[i].substring(0, includes[i].length() - 2); } } write = includes[i].startsWith(aux) || FilenameUtils.wildcardMatch(aux, includes[i]); } } if (write) { Writer writer = null; try { vc.put("outFile", out); String content = getContent(n, vc); vc.remove("outFile"); if (content != null && !"".equals(content)) { char endLineChar = getEndLineChar(out); writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(out), getEncoding())); if (vc.get("append") == null) { write(content, writer, endLineChar); } else { if (Boolean.TRUE.equals(vc.get("append"))) { append(content, writer, endLineChar); } else { write(content, writer, endLineChar); } } Summary.getInstance().addFile(out); log.debug(out.getPath() + " written "); } else { log.error(out.getPath() + " does not have valid content"); throw new WalkModException("blank code is returned"); } } finally { if (writer != null) { writer.close(); } } } else { if (createdEmptyFile && out != null && out.isFile()) { out.delete(); } log.debug("skipping " + out.getParent()); } } else { log.debug("There is no place where to write."); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Object parseIterable(final StartElement iterableEvent, final SerIterable iterable) throws Exception { Attribute rowsAttr = iterableEvent.getAttributeByName(ROWS_QNAME); Attribute columnsAttr = iterableEvent.getAttributeByName(COLS_QNAME); if (rowsAttr != null && columnsAttr != null) { iterable.dimensions(new int[] {Integer.parseInt(rowsAttr.getValue()), Integer.parseInt(columnsAttr.getValue())}); } XMLEvent event = nextEvent(">iter "); while (event.isEndElement() == false) { if (event.isStartElement()) { StartElement start = event.asStartElement(); QName expectedType = iterable.category() == SerCategory.MAP ? ENTRY_QNAME : ITEM_QNAME; if (start.getName().equals(expectedType) == false) { throw new IllegalArgumentException("Expected '" + expectedType.getLocalPart() + "' but found '" + start.getName() + "'"); } int count = 1; Object key = null; Object column = null; Object value = null; if (iterable.category() == SerCategory.COUNTED) { Attribute countAttr = start.getAttributeByName(COUNT_QNAME); if (countAttr != null) { count = Integer.parseInt(countAttr.getValue()); } value = parseValue(iterable, start); } else if (iterable.category() == SerCategory.TABLE || iterable.category() == SerCategory.GRID) { Attribute rowAttr = start.getAttributeByName(ROW_QNAME); Attribute colAttr = start.getAttributeByName(COL_QNAME); if (rowAttr == null || colAttr == null) { throw new IllegalArgumentException("Unable to read table as row/col attribute missing"); } String rowStr = rowAttr.getValue(); if (iterable.keyType() != null) { key = settings.getConverter().convertFromString(iterable.keyType(), rowStr); } else { key = rowStr; } String colStr = colAttr.getValue(); if (iterable.columnType() != null) { column = settings.getConverter().convertFromString(iterable.columnType(), colStr); } else { column = colStr; } value = parseValue(iterable, start); } else if (iterable.category() == SerCategory.MAP) { Attribute keyAttr = start.getAttributeByName(KEY_QNAME); if (keyAttr != null) { // item is value with a key attribute String keyStr = keyAttr.getValue(); if (iterable.keyType() != null) { key = settings.getConverter().convertFromString(iterable.keyType(), keyStr); } else { key = keyStr; } value = parseValue(iterable, start); } else { // two items nested in this entry if (Bean.class.isAssignableFrom(iterable.keyType()) == false) { throw new IllegalArgumentException("Unable to read map as declared key type is neither a bean nor a simple type: " + iterable.keyType().getName()); } event = nextEvent(">>map "); int loop = 0; while (event.isEndElement() == false) { if (event.isStartElement()) { start = event.asStartElement(); if (start.getName().equals(ITEM_QNAME) == false) { throw new IllegalArgumentException("Expected 'item' but found '" + start.getName() + "'"); } if (key == null) { key = parseKey(iterable, start); } else { value = parseValue(iterable, start); } loop++; } event = nextEvent("..map "); } if (loop != 2) { throw new IllegalArgumentException("Expected 2 'item's but found " + loop); } } } else { // COLLECTION value = parseValue(iterable, start); } iterable.add(key, column, value, count); } event = nextEvent(".iter "); } return iterable.build(); } #location 61 #vulnerability type NULL_DEREFERENCE
#fixed code private Object parseIterable(final StartElement iterableEvent, final SerIterable iterable) throws Exception { Attribute rowsAttr = iterableEvent.getAttributeByName(ROWS_QNAME); Attribute columnsAttr = iterableEvent.getAttributeByName(COLS_QNAME); if (rowsAttr != null && columnsAttr != null) { iterable.dimensions(new int[] {Integer.parseInt(rowsAttr.getValue()), Integer.parseInt(columnsAttr.getValue())}); } XMLEvent event = nextEvent(">iter "); while (event.isEndElement() == false) { if (event.isStartElement()) { StartElement start = event.asStartElement(); QName expectedType = iterable.category() == SerCategory.MAP ? ENTRY_QNAME : ITEM_QNAME; if (start.getName().equals(expectedType) == false) { throw new IllegalArgumentException("Expected '" + expectedType.getLocalPart() + "' but found '" + start.getName() + "'"); } int count = 1; Object key = null; Object column = null; Object value = null; if (iterable.category() == SerCategory.COUNTED) { Attribute countAttr = start.getAttributeByName(COUNT_QNAME); if (countAttr != null) { count = Integer.parseInt(countAttr.getValue()); } value = parseValue(iterable, start); } else if (iterable.category() == SerCategory.TABLE || iterable.category() == SerCategory.GRID) { Attribute rowAttr = start.getAttributeByName(ROW_QNAME); Attribute colAttr = start.getAttributeByName(COL_QNAME); if (rowAttr == null || colAttr == null) { throw new IllegalArgumentException("Unable to read table as row/col attribute missing"); } String rowStr = rowAttr.getValue(); if (iterable.keyType() != null) { key = settings.getConverter().convertFromString(iterable.keyType(), rowStr); } else { key = rowStr; } String colStr = colAttr.getValue(); if (iterable.columnType() != null) { column = settings.getConverter().convertFromString(iterable.columnType(), colStr); } else { column = colStr; } value = parseValue(iterable, start); } else if (iterable.category() == SerCategory.MAP) { Attribute keyAttr = start.getAttributeByName(KEY_QNAME); if (keyAttr != null) { // item is value with a key attribute String keyStr = keyAttr.getValue(); if (iterable.keyType() != null) { key = settings.getConverter().convertFromString(iterable.keyType(), keyStr); } else { key = keyStr; } value = parseValue(iterable, start); } else { // two items nested in this entry event = nextEvent(">>map "); int loop = 0; while (event.isEndElement() == false) { if (event.isStartElement()) { start = event.asStartElement(); if (start.getName().equals(ITEM_QNAME) == false) { throw new IllegalArgumentException("Expected 'item' but found '" + start.getName() + "'"); } if (key == null) { key = parseKey(iterable, start); } else { value = parseValue(iterable, start); } loop++; } event = nextEvent("..map "); } if (loop != 2) { throw new IllegalArgumentException("Expected 2 'item's but found " + loop); } } } else { // COLLECTION value = parseValue(iterable, start); } iterable.add(key, column, value, count); } event = nextEvent(".iter "); } return iterable.build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static BeanCodeGen createFromArgs(String[] args) { if (args == null) { throw new IllegalArgumentException("Arguments must not be null"); } String indent = " "; String prefix = ""; boolean recurse = false; int verbosity = 1; boolean write = true; File file = null; BeanGenConfig config = null; if (args.length == 0) { throw new IllegalArgumentException("No arguments specified"); } for (int i = 0; i < args.length - 1; i++) { String arg = args[i]; if (arg == null) { throw new IllegalArgumentException("Argument must not be null: " + Arrays.toString(args)); } if (arg.startsWith("-indent=tab")) { indent = "\t"; } else if (arg.startsWith("-indent=")) { indent = " ".substring(0, Integer.parseInt(arg.substring(8))); } else if (arg.startsWith("-prefix=")) { prefix = arg.substring(8); } else if (arg.equals("-R")) { recurse = true; } else if (arg.equals("-config=")) { if (config != null) { throw new IllegalArgumentException("Argument 'config' must not be specified twice: " + Arrays.toString(args)); } config = BeanGenConfig.parse(arg.substring(8)); } else if (arg.startsWith("-verbose=")) { verbosity = Integer.parseInt(arg.substring(9)); } else if (arg.startsWith("-v=")) { System.out.println("Deprecated command line argument -v (use -verbose instead)"); verbosity = Integer.parseInt(arg.substring(3)); } else if (arg.equals("-nowrite")) { write = false; } else { throw new IllegalArgumentException("Unknown argument: " + arg); } } file = new File(args[args.length - 1]); List<File> files = findFiles(file, recurse); if (config == null) { config = BeanGenConfig.parse("guava"); } config.setIndent(indent); config.setPrefix(prefix); return new BeanCodeGen(files, config, verbosity, write); } #location 50 #vulnerability type NULL_DEREFERENCE
#fixed code public static BeanCodeGen createFromArgs(String[] args) { if (args == null) { throw new IllegalArgumentException("Arguments must not be null"); } String indent = " "; String prefix = ""; boolean recurse = false; int verbosity = 1; boolean write = true; File file = null; BeanGenConfig config = null; if (args.length == 0) { throw new IllegalArgumentException("No arguments specified"); } for (int i = 0; i < args.length - 1; i++) { String arg = args[i]; if (arg == null) { throw new IllegalArgumentException("Argument must not be null: " + Arrays.toString(args)); } if (arg.startsWith("-indent=tab")) { indent = "\t"; } else if (arg.startsWith("-indent=")) { indent = " ".substring(0, Integer.parseInt(arg.substring(8))); } else if (arg.startsWith("-prefix=")) { prefix = arg.substring(8); } else if (arg.equals("-R")) { recurse = true; } else if (arg.startsWith("-config=")) { if (config != null) { throw new IllegalArgumentException("Argument 'config' must not be specified twice: " + Arrays.toString(args)); } config = BeanGenConfig.parse(arg.substring(8)); } else if (arg.startsWith("-verbose=")) { verbosity = Integer.parseInt(arg.substring(9)); } else if (arg.startsWith("-v=")) { System.out.println("Deprecated command line argument -v (use -verbose instead)"); verbosity = Integer.parseInt(arg.substring(3)); } else if (arg.equals("-nowrite")) { write = false; } else { throw new IllegalArgumentException("Unknown argument: " + arg); } } file = new File(args[args.length - 1]); List<File> files = findFiles(file, recurse); if (config == null) { config = BeanGenConfig.parse("guava"); } config.setIndent(indent); config.setPrefix(prefix); return new BeanCodeGen(files, config, verbosity, write); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public DataReader getDataReader(InputStream inStream) throws IOException { BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB); in.mark(FOUR_KB); byte[] buf = new byte[ONE_KB * 3]; int length = in.read(buf); in.reset(); String s = new String(buf, 0, length, "ASCII"); if (s.indexOf("[memory ] ") != -1) { if ((s.indexOf("[memory ] [YC") != -1) ||(s.indexOf("[memory ] [OC") != -1)) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: JRockit 1.6"); return new DataReaderJRockit1_6_0(in); } else { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: JRockit 1.4.2"); return new DataReaderJRockit1_4_2(in); } } else if (s.indexOf("since last AF or CON>") != -1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM 1.4.2"); return new DataReaderIBM1_4_2(in); } else if (s.indexOf("GC cycle started") != -1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM 1.3.1"); return new DataReaderIBM1_3_1(in); } else if (s.indexOf("<AF") != -1) { // this should be an IBM JDK < 1.3.0 if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM <1.3.0"); return new DataReaderIBM1_3_0(in); } else if (s.indexOf("pause (young)") > 0) { // G1 logger usually starts with "<timestamp>: [GC pause (young)...]" if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.6.x G1 collector"); return new DataReaderSun1_6_0G1(in); } else if (s.indexOf("[Times:") > 0) { // all 1.6 lines end with a block like this "[Times: user=1.13 sys=0.08, real=0.95 secs]" if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.6.x"); return new DataReaderSun1_6_0(in); } else if (s.indexOf("CMS-initial-mark") != -1 || s.indexOf("PSYoungGen") != -1) { // format is 1.5, but datareader for 1_6_0 can handle it if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.5.x"); return new DataReaderSun1_6_0(in); } else if (s.indexOf(": [") != -1) { // format is 1.4, but datareader for 1_6_0 can handle it if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.4.x"); return new DataReaderSun1_6_0(in); } else if (s.indexOf("[GC") != -1 || s.indexOf("[Full GC") != -1 || s.indexOf("[Inc GC")!=-1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.3.1"); return new DataReaderSun1_3_1(in); } else if (s.indexOf("<GC: managing allocation failure: need ") != -1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.2.2"); return new DataReaderSun1_2_2(in); } else if (s.indexOf("<GC: ") == 0 && s.indexOf('>') != -1 && new StringTokenizer(s.substring(0, s.indexOf('>')+1), " ").countTokens() == 20) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: HP-UX 1.2/1.3/1.4.0"); return new DataReaderHPUX1_2(in); } else if (s.indexOf("<GC: ") == 0 && s.indexOf('>') != -1 && new StringTokenizer(s.substring(0, s.indexOf('>')+1), " ").countTokens() == 22) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: HP-UX 1.4.1/1.4.2"); return new DataReaderHPUX1_4_1(in); } else if (s.indexOf("<verbosegc version=\"") != -1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM J9 5.0"); return new DataReaderIBM_J9_5_0(in); } else if (s.indexOf("starting collection, threshold allocation reached.") != -1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM i5/OS 1.4.2"); return new DataReaderIBMi5OS1_4_2(in); } else if (LOG.isLoggable(Level.SEVERE)) LOG.severe(localStrings.getString("datareaderfactory_instantiation_failed")); throw new IOException(localStrings.getString("datareaderfactory_instantiation_failed")); } #location 62 #vulnerability type RESOURCE_LEAK
#fixed code public DataReader getDataReader(InputStream inStream) throws IOException { BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB); DataReader dataReader = null; long nextPos = 0; String chunkOfLastLine = null; int attemptCount = 0; while (attemptCount < MAX_ATTEMPT_COUNT) { in.mark(FOUR_KB + (int) nextPos); if (nextPos > 0) { long skipped = in.skip(nextPos); if (skipped != nextPos) { break; } } byte[] buf = new byte[ONE_KB * 3]; int length = in.read(buf); in.reset(); if (length <= 0) { break; } nextPos += length; String s = new String(buf, 0, length, "ASCII"); if (chunkOfLastLine != null && chunkOfLastLine.length() > 0) { s = chunkOfLastLine + s; } dataReader = getDataReaderBySample(s, in); if (dataReader != null) { break; } int index = s.lastIndexOf('\n'); if (index >= 0) { chunkOfLastLine = s.substring(index + 1, s.length()); } else { chunkOfLastLine = ""; } attemptCount++; } if (dataReader == null) { if (LOG.isLoggable(Level.SEVERE)) LOG.severe(localStrings.getString("datareaderfactory_instantiation_failed")); throw new IOException(localStrings.getString("datareaderfactory_instantiation_failed")); } return dataReader; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void setTotalAndPreUsed(GCEvent event, StartElement startEl) { long total = NumberParser.parseInt(getAttributeValue(startEl, "total")); event.setTotal(toKiloBytes(total)); event.setPreUsed(toKiloBytes(total - NumberParser.parseInt(getAttributeValue(startEl, "free")))); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code private void setTotalAndPreUsed(GCEvent event, StartElement startEl) { long total = NumberParser.parseLong(getAttributeValue(startEl, "total")); event.setTotal(toKiloBytes(total)); event.setPreUsed(toKiloBytes(total - NumberParser.parseLong(getAttributeValue(startEl, "free")))); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFullHeaderWithAfGcs() 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_full_header.txt"); DataReader reader = new DataReaderIBM_J9_R28(in); GCModel model = reader.read(); assertThat("model size", model.size(), is(3)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.042303, 0.0000001)); assertThat("total before", event.getTotal(), is(toKiloBytes(1073741824))); assertThat("free before", event.getPreUsed(), is(toKiloBytes(1073741824 - 804158480))); assertThat("free after", event.getPostUsed(), is(toKiloBytes(1073741824 - 912835672))); assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(268435456))); assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(268435456))); assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(268435456 - 108677192))); assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(805306368))); assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(805306368 - 804158480))); assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(805306368 - 804158480))); assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001)); assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.927, 0.0001)); assertThat("timestamp 3", model.get(2).getTimestamp(), closeTo(3.982, 0.0001)); assertThat("number of errors", handler.getCount(), is(1)); } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testFullHeaderWithAfGcs() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); GCResource gcResource = new GCResource("SampleIBMJ9_R27_SR1_full_header.txt"); gcResource.getLogger().addHandler(handler); DataReader reader = getDataReader(gcResource); GCModel model = reader.read(); assertThat("model size", model.size(), is(3)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.042303, 0.0000001)); assertThat("total before", event.getTotal(), is(toKiloBytes(1073741824))); assertThat("free before", event.getPreUsed(), is(toKiloBytes(1073741824 - 804158480))); assertThat("free after", event.getPostUsed(), is(toKiloBytes(1073741824 - 912835672))); assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(268435456))); assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(268435456))); assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(268435456 - 108677192))); assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(805306368))); assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(805306368 - 804158480))); assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(805306368 - 804158480))); assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001)); assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.927, 0.0001)); assertThat("timestamp 3", model.get(2).getTimestamp(), closeTo(3.982, 0.0001)); assertThat("number of errors", handler.getCount(), is(1)); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFullHeaderWithAfGcs() 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_full_header.txt"); DataReader reader = new DataReaderIBM_J9_R28(in); GCModel model = reader.read(); assertThat("model size", model.size(), is(3)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.042303, 0.0000001)); assertThat("total before", event.getTotal(), is(toKiloBytes(1073741824))); assertThat("free before", event.getPreUsed(), is(toKiloBytes(1073741824 - 804158480))); assertThat("free after", event.getPostUsed(), is(toKiloBytes(1073741824 - 912835672))); assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(268435456))); assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(268435456))); assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(268435456 - 108677192))); assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(805306368))); assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(805306368 - 804158480))); assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(805306368 - 804158480))); assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001)); assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.927, 0.0001)); assertThat("timestamp 3", model.get(2).getTimestamp(), closeTo(3.982, 0.0001)); assertThat("number of errors", handler.getCount(), is(1)); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testFullHeaderWithAfGcs() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); GCResource gcResource = new GCResource("SampleIBMJ9_R27_SR1_full_header.txt"); gcResource.getLogger().addHandler(handler); DataReader reader = getDataReader(gcResource); GCModel model = reader.read(); assertThat("model size", model.size(), is(3)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.042303, 0.0000001)); assertThat("total before", event.getTotal(), is(toKiloBytes(1073741824))); assertThat("free before", event.getPreUsed(), is(toKiloBytes(1073741824 - 804158480))); assertThat("free after", event.getPostUsed(), is(toKiloBytes(1073741824 - 912835672))); assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(268435456))); assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(268435456))); assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(268435456 - 108677192))); assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(805306368))); assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(805306368 - 804158480))); assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(805306368 - 804158480))); assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001)); assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.927, 0.0001)); assertThat("timestamp 3", model.get(2).getTimestamp(), closeTo(3.982, 0.0001)); assertThat("number of errors", handler.getCount(), is(1)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFullHeaderWithAfGcs() 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_full_header.txt"); DataReader reader = new DataReaderIBM_J9_R28(in); GCModel model = reader.read(); assertThat("model size", model.size(), is(2)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.025388, 0.0000001)); assertThat("total before", event.getTotal(), is(toKiloBytes(536870912))); assertThat("free before", event.getPreUsed(), is(toKiloBytes(536870912 - 401882552))); assertThat("free after", event.getPostUsed(), is(toKiloBytes(536870912 - 457545744))); assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(134217728))); assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(134217728))); assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(134217728 - 55663192))); assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184))); assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 401882552))); assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 401882552))); assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001)); assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.272, 0.0001)); assertThat("number of errors", handler.getCount(), is(0)); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testFullHeaderWithAfGcs() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); GCResource gcResource = new GCResource("SampleIBMJ9_R28_full_header.txt"); gcResource.getLogger().addHandler(handler); DataReader reader = getDataReader(gcResource); GCModel model = reader.read(); assertThat("model size", model.size(), is(2)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.025388, 0.0000001)); assertThat("total before", event.getTotal(), is(toKiloBytes(536870912))); assertThat("free before", event.getPreUsed(), is(toKiloBytes(536870912 - 401882552))); assertThat("free after", event.getPostUsed(), is(toKiloBytes(536870912 - 457545744))); assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(134217728))); assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(134217728))); assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(134217728 - 55663192))); assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184))); assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 401882552))); assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 401882552))); assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001)); assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.272, 0.0001)); assertThat("number of errors", handler.getCount(), is(0)); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFullHeaderWithAfGcs() 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_full_header.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.00529, 0.0000001)); assertThat("number of errors", handler.getCount(), is(1)); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testFullHeaderWithAfGcs() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); GCResource gcResource = new GCResource("SampleIBMJ9_R26_GAFP1_full_header.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.00529, 0.0000001)); assertThat("number of errors", handler.getCount(), is(1)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFullHeaderWithAfGcs() 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_full_header.txt"); DataReader reader = new DataReaderIBM_J9_R28(in); GCModel model = reader.read(); assertThat("model size", model.size(), is(2)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.025388, 0.0000001)); assertThat("total before", event.getTotal(), is(toKiloBytes(536870912))); assertThat("free before", event.getPreUsed(), is(toKiloBytes(536870912 - 401882552))); assertThat("free after", event.getPostUsed(), is(toKiloBytes(536870912 - 457545744))); assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(134217728))); assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(134217728))); assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(134217728 - 55663192))); assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184))); assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 401882552))); assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 401882552))); assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001)); assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.272, 0.0001)); assertThat("number of errors", handler.getCount(), is(0)); } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testFullHeaderWithAfGcs() throws Exception { TestLogHandler handler = new TestLogHandler(); handler.setLevel(Level.WARNING); GCResource gcResource = new GCResource("SampleIBMJ9_R28_full_header.txt"); gcResource.getLogger().addHandler(handler); DataReader reader = getDataReader(gcResource); GCModel model = reader.read(); assertThat("model size", model.size(), is(2)); GCEvent event = (GCEvent) model.get(0); assertThat("pause", event.getPause(), closeTo(0.025388, 0.0000001)); assertThat("total before", event.getTotal(), is(toKiloBytes(536870912))); assertThat("free before", event.getPreUsed(), is(toKiloBytes(536870912 - 401882552))); assertThat("free after", event.getPostUsed(), is(toKiloBytes(536870912 - 457545744))); assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(134217728))); assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(134217728))); assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(134217728 - 55663192))); assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184))); assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 401882552))); assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 401882552))); assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001)); assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.272, 0.0001)); assertThat("number of errors", handler.getCount(), is(0)); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void setPostUsed(GCEvent event, StartElement startEl) { long total = NumberParser.parseInt(getAttributeValue(startEl, "total")); event.setPostUsed(toKiloBytes(total - NumberParser.parseInt(getAttributeValue(startEl, "free")))); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code private void setPostUsed(GCEvent event, StartElement startEl) { long total = NumberParser.parseLong(getAttributeValue(startEl, "total")); event.setPostUsed(toKiloBytes(total - NumberParser.parseLong(getAttributeValue(startEl, "free")))); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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)); }
Below is the vulnerable code, please generate the patch based on the following information.
#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 10 #vulnerability type RESOURCE_LEAK
#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)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public DataReader getDataReader(InputStream inStream) throws IOException { BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB); in.mark(FOUR_KB); byte[] buf = new byte[ONE_KB * 3]; int length = in.read(buf); in.reset(); String s = new String(buf, 0, length, "ASCII"); if (s.indexOf("[memory ] ") != -1) { if ((s.indexOf("[memory ] [YC") != -1) ||(s.indexOf("[memory ] [OC") != -1)) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: JRockit 1.6"); return new DataReaderJRockit1_6_0(in); } else { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: JRockit 1.4.2"); return new DataReaderJRockit1_4_2(in); } } else if (s.indexOf("since last AF or CON>") != -1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM 1.4.2"); return new DataReaderIBM1_4_2(in); } else if (s.indexOf("GC cycle started") != -1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM 1.3.1"); return new DataReaderIBM1_3_1(in); } else if (s.indexOf("<AF") != -1) { // this should be an IBM JDK < 1.3.0 if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM <1.3.0"); return new DataReaderIBM1_3_0(in); } else if (s.indexOf("pause (young)") > 0) { // G1 logger usually starts with "<timestamp>: [GC pause (young)...]" if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.6.x G1 collector"); return new DataReaderSun1_6_0G1(in); } else if (s.indexOf("[Times:") > 0) { // all 1.6 lines end with a block like this "[Times: user=1.13 sys=0.08, real=0.95 secs]" if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.6.x"); return new DataReaderSun1_6_0(in); } else if (s.indexOf("CMS-initial-mark") != -1 || s.indexOf("PSYoungGen") != -1) { // format is 1.5, but datareader for 1_6_0 can handle it if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.5.x"); return new DataReaderSun1_6_0(in); } else if (s.indexOf(": [") != -1) { // format is 1.4, but datareader for 1_6_0 can handle it if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.4.x"); return new DataReaderSun1_6_0(in); } else if (s.indexOf("[GC") != -1 || s.indexOf("[Full GC") != -1 || s.indexOf("[Inc GC")!=-1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.3.1"); return new DataReaderSun1_3_1(in); } else if (s.indexOf("<GC: managing allocation failure: need ") != -1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.2.2"); return new DataReaderSun1_2_2(in); } else if (s.indexOf("<GC: ") == 0 && s.indexOf('>') != -1 && new StringTokenizer(s.substring(0, s.indexOf('>')+1), " ").countTokens() == 20) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: HP-UX 1.2/1.3/1.4.0"); return new DataReaderHPUX1_2(in); } else if (s.indexOf("<GC: ") == 0 && s.indexOf('>') != -1 && new StringTokenizer(s.substring(0, s.indexOf('>')+1), " ").countTokens() == 22) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: HP-UX 1.4.1/1.4.2"); return new DataReaderHPUX1_4_1(in); } else if (s.indexOf("<verbosegc version=\"") != -1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM J9 5.0"); return new DataReaderIBM_J9_5_0(in); } else if (s.indexOf("starting collection, threshold allocation reached.") != -1) { if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM i5/OS 1.4.2"); return new DataReaderIBMi5OS1_4_2(in); } else if (LOG.isLoggable(Level.SEVERE)) LOG.severe(localStrings.getString("datareaderfactory_instantiation_failed")); throw new IOException(localStrings.getString("datareaderfactory_instantiation_failed")); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code public DataReader getDataReader(InputStream inStream) throws IOException { BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB); DataReader dataReader = null; long nextPos = 0; String chunkOfLastLine = null; int attemptCount = 0; while (attemptCount < MAX_ATTEMPT_COUNT) { in.mark(FOUR_KB + (int) nextPos); if (nextPos > 0) { long skipped = in.skip(nextPos); if (skipped != nextPos) { break; } } byte[] buf = new byte[ONE_KB * 3]; int length = in.read(buf); in.reset(); if (length <= 0) { break; } nextPos += length; String s = new String(buf, 0, length, "ASCII"); if (chunkOfLastLine != null && chunkOfLastLine.length() > 0) { s = chunkOfLastLine + s; } dataReader = getDataReaderBySample(s, in); if (dataReader != null) { break; } int index = s.lastIndexOf('\n'); if (index >= 0) { chunkOfLastLine = s.substring(index + 1, s.length()); } else { chunkOfLastLine = ""; } attemptCount++; } if (dataReader == null) { if (LOG.isLoggable(Level.SEVERE)) LOG.severe(localStrings.getString("datareaderfactory_instantiation_failed")); throw new IOException(localStrings.getString("datareaderfactory_instantiation_failed")); } return dataReader; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code @SuppressWarnings("unused") public ListBoxModel doFillCredentialsIdItems(@QueryParameter String credentialsId) { return createListBoxModel(credentialsId); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static SonarQubeWebHook get() { return Jenkins.getInstance().getExtensionList(RootAction.class).get(SonarQubeWebHook.class); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public static SonarQubeWebHook get() { return Jenkins.get().getExtensionList(RootAction.class).get(SonarQubeWebHook.class); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean performInternal(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { if (!SonarInstallation.isValid(getInstallationName(), listener)) { return false; } ArgumentListBuilder args = new ArgumentListBuilder(); EnvVars env = run.getEnvironment(listener); if (run instanceof AbstractBuild) { env.overrideAll(((AbstractBuild<?, ?>) run).getBuildVariables()); } SonarRunnerInstallation sri = getSonarRunnerInstallation(); if (sri == null) { args.add(launcher.isUnix() ? "sonar-runner" : "sonar-runner.bat"); } else { sri = sri.forNode(getComputer(workspace).getNode(), listener); sri = sri.forEnvironment(env); String exe = sri.getExecutable(launcher); if (exe == null) { Logger.printFailureMessage(listener); listener.fatalError(Messages.SonarRunner_ExecutableNotFound(sri.getName())); return false; } args.add(exe); env.put("SONAR_RUNNER_HOME", sri.getHome()); } SonarInstallation sonarInst = getSonarInstallation(); addTaskArgument(args); addAdditionalArguments(args, sonarInst); ExtendedArgumentListBuilder argsBuilder = new ExtendedArgumentListBuilder(args, launcher.isUnix()); if (!populateConfiguration(argsBuilder, run, workspace, listener, env, sonarInst)) { return false; } // Java computeJdkToUse(run, workspace, listener, env); // Java options env.put("SONAR_RUNNER_OPTS", getJavaOpts()); long startTime = System.currentTimeMillis(); int r; try { r = executeSonarRunner(run, workspace, launcher, listener, args, env); } catch (IOException e) { handleErrors(run, listener, sri, startTime, e); r = -1; } return r == 0; } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean performInternal(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { if (!SonarInstallation.isValid(getInstallationName(), listener)) { return false; } ArgumentListBuilder args = new ArgumentListBuilder(); EnvVars env = BuilderUtils.getEnvAndBuildVars(run, listener); SonarRunnerInstallation sri = getSonarRunnerInstallation(); if (sri == null) { args.add(launcher.isUnix() ? "sonar-runner" : "sonar-runner.bat"); } else { sri = BuilderUtils.getBuildTool(sri, env, listener); String exe = sri.getExecutable(launcher); if (exe == null) { Logger.printFailureMessage(listener); listener.fatalError(Messages.SonarRunner_ExecutableNotFound(sri.getName())); return false; } args.add(exe); env.put("SONAR_RUNNER_HOME", sri.getHome()); } SonarInstallation sonarInst = getSonarInstallation(); addTaskArgument(args); addAdditionalArguments(args, sonarInst); ExtendedArgumentListBuilder argsBuilder = new ExtendedArgumentListBuilder(args, launcher.isUnix()); if (!populateConfiguration(argsBuilder, run, workspace, listener, env, sonarInst)) { return false; } // Java computeJdkToUse(run, workspace, listener, env); // Java options env.put("SONAR_RUNNER_OPTS", getJavaOpts()); long startTime = System.currentTimeMillis(); int r; try { r = executeSonarRunner(run, workspace, launcher, listener, args, env); } catch (IOException e) { handleErrors(run, listener, sri, startTime, e); r = -1; } return r == 0; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unused") public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) { if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) { return new StandardListBoxModel().includeCurrentValue(webhookSecretId); } return new StandardListBoxModel() .includeEmptyValue() .includeMatchingAs( ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class, Collections.emptyList(), CredentialsMatchers.always() ); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @SuppressWarnings("unused") public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) { return createListBoxModel(webhookSecretId); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code @Override public String getIconFileName() { PluginWrapper wrapper = Jenkins.getInstanceOrNull().getPluginManager() .getPlugin(SonarPlugin.class); return "/plugin/" + wrapper.getShortName() + "/images/waves_48x48.png"; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void getQualityGate(WsClient client, ProjectInformation proj, String projectKey, float version) throws Exception { ProjectQualityGate qg; if (version < 5.2f) { qg = client.getQualityGateBefore52(projectKey); } else { qg = client.getQualityGate52(projectKey); } proj.setStatus(qg.getStatus()); if (qg.getProjectName() != null) { proj.setName(qg.getProjectName()); } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code private static void getQualityGate(WsClient client, ProjectInformation proj, String projectKey, float version) throws Exception { ProjectQualityGate qg; if (version < 5.2f) { qg = client.getQualityGateBefore52(projectKey); } else { qg = client.getQualityGate52(projectKey); } // happens in LTS if project is not assigned to a QG and there is no default QG if (qg == null) { return; } proj.setStatus(qg.getStatus()); if (qg.getProjectName() != null) { proj.setName(qg.getProjectName()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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 (); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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 (); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void execute (final ButtonEvent event) { if (event != ButtonEvent.DOWN) return; final ViewManager viewManager = this.surface.getViewManager (); final AbstractTrackBankProxy tb = this.model.getCurrentTrackBank (); final TrackData sel = tb.getSelectedTrack (); if (sel == null) { viewManager.setActiveView (Views.VIEW_SESSION); return; } Integer viewID; if (Views.isNoteView (viewManager.getActiveViewId ())) { if (this.surface.isShiftPressed ()) viewID = viewManager.isActiveView (Views.VIEW_SEQUENCER) ? Views.VIEW_RAINDROPS : Views.VIEW_SEQUENCER; else viewID = viewManager.isActiveView (Views.VIEW_PLAY) ? Views.VIEW_DRUM : Views.VIEW_PLAY; } else { viewID = viewManager.getPreferredView (sel.getPosition ()); if (viewID == null) viewID = this.surface.isShiftPressed () ? Views.VIEW_SEQUENCER : Views.VIEW_PLAY; } viewManager.setActiveView (viewID); viewManager.setPreferredView (sel.getPosition (), viewID); } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void execute (final ButtonEvent event) { if (event != ButtonEvent.DOWN) return; final ViewManager viewManager = this.surface.getViewManager (); final AbstractTrackBankProxy tb = this.model.getCurrentTrackBank (); final TrackData sel = tb.getSelectedTrack (); if (sel == null) { viewManager.setActiveView (Views.VIEW_SESSION); return; } if (Views.isNoteView (viewManager.getActiveViewId ())) { if (this.surface.isShiftPressed ()) this.seqSelect.executeNormal (event); else this.playSelect.executeNormal (event); } else { final Integer viewID = viewManager.getPreferredView (sel.getPosition ()); if (viewID == null) this.seqSelect.executeNormal (event); else viewManager.setActiveView (viewID); } viewManager.setPreferredView (sel.getPosition (), viewManager.getActiveViewId ()); this.surface.getDisplay ().notify (viewManager.getActiveView ().getName ()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onGridNote (final int note, final int velocity) { if (velocity == 0) return; final ICursorDevice cursorDevice = this.model.getCursorDevice (); switch (this.surface.getPadGrid ().translateToController (note)) { // Flip views case 56: this.switchToView (Views.VIEW_SESSION); break; case 57: this.switchToView (Views.VIEW_PLAY); break; case 58: this.switchToView (Views.VIEW_DRUM); break; case 59: this.switchToView (Views.VIEW_SEQUENCER); break; case 60: this.switchToView (Views.VIEW_RAINDROPS); break; // Last row transport case 63: this.playCommand.executeNormal (ButtonEvent.DOWN); this.surface.getDisplay ().notify ("Start/Stop"); break; case 55: this.model.getTransport ().record (); this.surface.getDisplay ().notify ("Record"); break; case 47: this.model.getTransport ().toggleLoop (); this.surface.getDisplay ().notify ("Toggle Loop"); break; case 39: this.model.getTransport ().toggleMetronome (); this.surface.getDisplay ().notify ("Toggle Click"); break; // Navigation case 62: this.onNew (); this.surface.getDisplay ().notify ("New clip"); break; case 54: this.model.getTransport ().toggleLauncherOverdub (); this.surface.getDisplay ().notify ("Toggle Launcher Overdub"); break; case 46: this.model.getCursorClip ().quantize (this.surface.getConfiguration ().getQuantizeAmount () / 100.0); this.surface.getDisplay ().notify ("Quantize"); break; case 38: this.model.getApplication ().undo (); this.surface.getDisplay ().notify ("Undo"); break; // Device Parameters up/down case 24: if (cursorDevice.hasPreviousParameterPage ()) { cursorDevice.previousParameterPage (); this.surface.getDisplay ().notify ("Bank: " + cursorDevice.getSelectedParameterPageName ()); } break; case 25: if (cursorDevice.hasNextParameterPage ()) { cursorDevice.nextParameterPage (); this.surface.getDisplay ().notify ("Bank: " + cursorDevice.getSelectedParameterPageName ()); } break; // Device up/down case 32: if (cursorDevice.canSelectPreviousFX ()) { cursorDevice.selectPrevious (); this.surface.getDisplay ().notify ("Device: " + cursorDevice.getName ()); } break; case 33: if (cursorDevice.canSelectNextFX ()) { cursorDevice.selectNext (); this.surface.getDisplay ().notify ("Device: " + cursorDevice.getName ()); } break; // Change the scale case 35: this.scales.prevScale (); final String name = this.scales.getScale ().getName (); this.surface.getConfiguration ().setScale (name); this.surface.getDisplay ().notify (name); break; case 36: this.scales.nextScale (); final String name2 = this.scales.getScale ().getName (); this.surface.getConfiguration ().setScale (name2); this.surface.getDisplay ().notify (name2); break; case 27: this.scales.toggleChromatic (); this.surface.getDisplay ().notify (this.scales.isChromatic () ? "Chromatc" : "In Key"); break; // Scale Base note selection default: if (note > 15) return; final int pos = TRANSLATE[note]; if (pos == -1) return; this.scales.setScaleOffset (pos); this.surface.getConfiguration ().setScaleBase (Scales.BASES[pos]); this.surface.getDisplay ().notify (Scales.BASES[pos]); this.surface.getViewManager ().getActiveView ().updateNoteMapping (); break; } } #location 123 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onGridNote (final int note, final int velocity) { if (velocity == 0) return; final ICursorDevice cursorDevice = this.model.getCursorDevice (); final int n = this.surface.getPadGrid ().translateToController (note); switch (n) { // Flip views case 56: this.switchToView (Views.VIEW_SESSION); break; case 57: this.switchToView (Views.VIEW_PLAY); break; case 58: this.switchToView (Views.VIEW_DRUM); break; case 59: this.switchToView (Views.VIEW_SEQUENCER); break; case 60: this.switchToView (Views.VIEW_RAINDROPS); break; // Last row transport case 63: this.playCommand.executeNormal (ButtonEvent.DOWN); this.surface.getDisplay ().notify ("Start/Stop"); break; case 55: this.model.getTransport ().record (); this.surface.getDisplay ().notify ("Record"); break; case 47: this.model.getTransport ().toggleLoop (); this.surface.getDisplay ().notify ("Toggle Loop"); break; case 39: this.model.getTransport ().toggleMetronome (); this.surface.getDisplay ().notify ("Toggle Click"); break; // Navigation case 62: this.onNew (); this.surface.getDisplay ().notify ("New clip"); break; case 54: this.model.getTransport ().toggleLauncherOverdub (); this.surface.getDisplay ().notify ("Toggle Launcher Overdub"); break; case 46: this.model.getCursorClip ().quantize (this.surface.getConfiguration ().getQuantizeAmount () / 100.0); this.surface.getDisplay ().notify ("Quantize"); break; case 38: this.model.getApplication ().undo (); this.surface.getDisplay ().notify ("Undo"); break; // Device Parameters up/down case 24: if (cursorDevice.hasPreviousParameterPage ()) { cursorDevice.previousParameterPage (); this.surface.getDisplay ().notify ("Bank: " + cursorDevice.getSelectedParameterPageName ()); } break; case 25: if (cursorDevice.hasNextParameterPage ()) { cursorDevice.nextParameterPage (); this.surface.getDisplay ().notify ("Bank: " + cursorDevice.getSelectedParameterPageName ()); } break; // Device up/down case 32: if (cursorDevice.canSelectPreviousFX ()) { cursorDevice.selectPrevious (); this.surface.getDisplay ().notify ("Device: " + cursorDevice.getName ()); } break; case 33: if (cursorDevice.canSelectNextFX ()) { cursorDevice.selectNext (); this.surface.getDisplay ().notify ("Device: " + cursorDevice.getName ()); } break; // Change the scale case 35: this.scales.prevScale (); final String name = this.scales.getScale ().getName (); this.surface.getConfiguration ().setScale (name); this.surface.getDisplay ().notify (name); break; case 36: this.scales.nextScale (); final String name2 = this.scales.getScale ().getName (); this.surface.getConfiguration ().setScale (name2); this.surface.getDisplay ().notify (name2); break; case 27: this.scales.toggleChromatic (); this.surface.getDisplay ().notify (this.scales.isChromatic () ? "Chromatc" : "In Key"); break; // Scale Base note selection default: if (n > 15) return; final int pos = TRANSLATE[n]; if (pos == -1) return; this.scales.setScaleOffset (pos); this.surface.getConfiguration ().setScaleBase (Scales.BASES[pos]); this.surface.getDisplay ().notify (Scales.BASES[pos]); this.surface.getViewManager ().getActiveView ().updateNoteMapping (); break; } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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 (); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Artifact chooseBinaryBits() throws MojoExecutionException { String plat; String os = System.getProperty("os.name"); getLog().debug("OS = " + os); // See here for possible values of os.name: // http://lopica.sourceforge.net/os.html if (os.startsWith("Windows")) { plat = "win32"; } else if ("Linux".equals(os)) { plat = "linux"; } else if ("Solaris".equals(os) || "SunOS".equals(os)) { plat = "solaris"; } else if ("Mac OS X".equals(os) || "Darwin".equals(os)) { plat = (isBelow10_8(System.getProperty("os.version"))) ? "mac" : "osx"; } else { throw new MojoExecutionException("Sorry, Launch4j doesn't support the '" + os + "' OS."); } return factory.createArtifactWithClassifier(LAUNCH4J_GROUP_ID, LAUNCH4J_ARTIFACT_ID, getLaunch4jVersion(), "jar", "workdir-" + plat); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code private Artifact chooseBinaryBits() throws MojoExecutionException { String plat; String os = System.getProperty("os.name"); getLog().debug("OS = " + os); // See here for possible values of os.name: // http://lopica.sourceforge.net/os.html if (os.startsWith("Windows")) { plat = "win32"; } else if ("Linux".equals(os)) { plat = "linux"; } else if ("Solaris".equals(os) || "SunOS".equals(os)) { plat = "solaris"; } else if ("Mac OS X".equals(os) || "Darwin".equals(os)) { plat = isBelowMacOSX_10_8() ? "mac" : "osx"; } else { throw new MojoExecutionException("Sorry, Launch4j doesn't support the '" + os + "' OS."); } return factory.createArtifactWithClassifier(LAUNCH4J_GROUP_ID, LAUNCH4J_ARTIFACT_ID, getLaunch4jVersion(), "jar", "workdir-" + plat); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Set<Annotation> parameterAnnotations(Member member) { Set<Annotation> result = new HashSet<>(); Annotation[][] annotations = member instanceof Method ? ((Method) member).getParameterAnnotations() : member instanceof Constructor ? ((Constructor) member).getParameterAnnotations() : null; for (Annotation[] annotation : annotations) Collections.addAll(result, annotation); return result; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private static Set<Annotation> parameterAnnotations(Member member) { Annotation[][] annotations = member instanceof Method ? ((Method) member).getParameterAnnotations() : member instanceof Constructor ? ((Constructor) member).getParameterAnnotations() : null; return Arrays.stream(annotations).flatMap(Arrays::stream).collect(Collectors.toSet()); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long getDownloaded() { return this.downloaded; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public long getDownloaded() { return myTorrentStatistic.getDownloadedBytes(); }
Below is the vulnerable code, please generate the patch based on the following information.