output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code public void destroy() { //kill running threads scheduler.shutdownNow(); }
#vulnerable code public void destroy() { //kill running threads executorService.shutdownNow(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; try { // add request, response & servletContext to thread local Context.set(Context.webContext(request, response, filterConfig)); IOUtils.write("\nBefore chain!\n", response.getOutputStream()); final ByteArrayOutputStream os = new ByteArrayOutputStream(); System.out.println(response.getOutputStream()); final HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response); chain.doFilter(request, wrappedResponse); final Reader reader = new StringReader(new String(os.toByteArray(), Context.get().getConfig().getEncoding())); doProcess(reader, new OutputStreamWriter(os)); IOUtils.write(os.toByteArray(), response.getOutputStream()); response.flushBuffer(); response.getOutputStream().close(); } catch (final RuntimeException e) { onRuntimeException(e, response, chain); } finally { Context.unset(); } }
#vulnerable code public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; try { // add request, response & servletContext to thread local Context.set(Context.webContext(request, response, filterConfig)); final ByteArrayOutputStream os = new ByteArrayOutputStream(); HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response); chain.doFilter(req, wrappedResponse); final Reader reader = new StringReader(new String(os.toByteArray(), Context.get().getConfig().getEncoding())); doProcess(reader, response.getWriter()); response.flushBuffer(); } catch (final RuntimeException e) { onRuntimeException(e, response, chain); } finally { Context.unset(); } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNoProcessorWroManagerFactory() throws IOException { final WroManagerFactory factory = new ServletContextAwareWroManagerFactory(); manager = factory.getInstance(); manager.setModelFactory(getValidModelFactory()); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Context.get().getResponse(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(out)); Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); manager.process(request, response); //compare written bytes to output stream with the content from specified css. WroTestUtils.compare(getInputStream("classpath:ro/isdc/wro/manager/noProcessorsResult.css"), new ByteArrayInputStream(out.toByteArray())); }
#vulnerable code @Test public void testNoProcessorWroManagerFactory() throws IOException { final WroManagerFactory factory = new ServletContextAwareWroManagerFactory(); manager = factory.getInstance(); manager.setModelFactory(getValidModelFactory()); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final OutputStream os = System.out; final HttpServletResponse response = Context.get().getResponse(); final InputStream actualStream = WroTestUtils.convertToInputStream(os); Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(os)); Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); manager.process(request, response); WroTestUtils.compare(getInputStream("classpath:ro/isdc/wro/manager/noProcessorsResult.css"), actualStream); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, final FilterChain chain) { LOG.debug("RuntimeException occured", e); try { LOG.debug("Cannot process. Proceeding with chain execution."); chain.doFilter(Context.get().getRequest(), response); } catch (final Exception ex) { // should never happen LOG.error("Error while chaining the request: " + HttpServletResponse.SC_NOT_FOUND); } }
#vulnerable code protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, final FilterChain chain) { LOG.debug("RuntimeException occured", e); try { LOG.debug("Cannot process. Proceeding with chain execution."); final OutputStream os = new ByteArrayOutputStream(); HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response); chain.doFilter(Context.get().getRequest(), wrappedResponse); } catch (final Exception ex) { // should never happen LOG.error("Error while chaining the request: " + HttpServletResponse.SC_NOT_FOUND); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private InputStream locateStreamFromJar(final String uri, final File jarPath) throws IOException { LOG.debug("\t\tLocating stream from jar"); String classPath = FilenameUtils.getPath(uri); final String wildcard = FilenameUtils.getName(uri); if (classPath.startsWith(ClasspathUriLocator.PREFIX)) { classPath = StringUtils.substringAfter(classPath, ClasspathUriLocator.PREFIX); } final JarFile file = open(jarPath); final List<JarEntry> jarEntryList = Collections.list(file.entries()); final List<JarEntry> filteredJarEntryList = new ArrayList<JarEntry>(); for (final JarEntry entry : jarEntryList) { final boolean isSupportedEntry = entry.getName().startsWith(classPath) && accept(entry, wildcard); if (isSupportedEntry) { filteredJarEntryList.add(entry); } } final ByteArrayOutputStream out = new ByteArrayOutputStream(); for (final JarEntry entry : filteredJarEntryList) { final InputStream is = file.getInputStream(entry); IOUtils.copy(is, out); is.close(); } return new BufferedInputStream(new ByteArrayInputStream(out.toByteArray())); }
#vulnerable code private InputStream locateStreamFromJar(final String uri, final File jarPath) throws IOException { LOG.debug("\t\tLocating stream from jar"); String classPath = FilenameUtils.getPath(uri); final String wildcard = FilenameUtils.getName(uri); if (classPath.startsWith(ClasspathUriLocator.PREFIX)) { classPath = StringUtils.substringAfter(classPath, ClasspathUriLocator.PREFIX); } final JarFile file = open(jarPath); List<JarEntry> jarEntryList = Collections.list(file.entries()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); for (JarEntry entry : jarEntryList) { if (entry.getName().startsWith(classPath) && accept(entry, wildcard)) { final InputStream is = file.getInputStream(entry); IOUtils.copy(is, out); is.close(); } } return new BufferedInputStream(new ByteArrayInputStream(out.toByteArray())); } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, final FilterChain chain) { LOG.debug("RuntimeException occured", e); try { LOG.debug("Cannot process. Proceeding with chain execution."); chain.doFilter(Context.get().getRequest(), response); } catch (final Exception ex) { // should never happen LOG.error("Error while chaining the request: " + HttpServletResponse.SC_NOT_FOUND); } }
#vulnerable code protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, final FilterChain chain) { LOG.debug("RuntimeException occured", e); try { LOG.debug("Cannot process. Proceeding with chain execution."); final OutputStream os = new ByteArrayOutputStream(); HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response); chain.doFilter(Context.get().getRequest(), wrappedResponse); } catch (final Exception ex) { // should never happen LOG.error("Error while chaining the request: " + HttpServletResponse.SC_NOT_FOUND); } } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void process(final Reader reader, final Writer writer) throws IOException { final StopWatch watch = new StopWatch(); watch.start("pack"); final String content = IOUtils.toString(reader); try { final JavaScriptCompressor compressor = new JavaScriptCompressor(new StringReader(content), new YUIErrorReporter()); compressor.compress(writer, linebreakpos, munge, verbose, preserveAllSemiColons, disableOptimizations); } catch (final RuntimeException e) { LOG.error("Problem while applying YUI compressor", e); //keep js unchanged if it contains errors -> this should be configurable LOG.debug("Leave resource unchanged..."); IOUtils.copy(new StringReader(content), writer); //throw new WroRuntimeException("Problem while applying YUI compressor", e); } finally { reader.close(); writer.close(); watch.stop(); LOG.debug(watch.prettyPrint()); } }
#vulnerable code public void process(final Reader reader, final Writer writer) throws IOException { final StopWatch watch = new StopWatch(); watch.start("pack"); final InputStream is = new ByteArrayInputStream(IOUtils.toByteArray(reader)); try { final JavaScriptCompressor compressor = new JavaScriptCompressor(new InputStreamReader(is), new YUIErrorReporter()); compressor.compress(writer, linebreakpos, munge, verbose, preserveAllSemiColons, disableOptimizations); } catch (final RuntimeException e) { LOG.error("Problem while applying YUI compressor", e); //keep js unchanged if it contains errors -> this should be configurable LOG.debug("Leave resource unchanged..."); is.reset(); IOUtils.copy(is, writer); //throw new WroRuntimeException("Problem while applying YUI compressor", e); } finally { is.close(); reader.close(); writer.close(); watch.stop(); LOG.debug(watch.prettyPrint()); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void onModelPeriodChanged() { //force scheduler to reload model = null; }
#vulnerable code public void onModelPeriodChanged() { //force scheduler to reload initScheduler(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getScalarValue(String key) throws ConfiguratorException { return remove(key).asScalar().getValue(); }
#vulnerable code public String getScalarValue(String key) throws ConfiguratorException { return get(key).asScalar().getValue(); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object configure(Object c) throws Exception { final ExtensionList list = Jenkins.getInstance().getExtensionList(target); if (list.size() != 1) { throw new IllegalStateException(); } final Object o = list.get(0); if (c instanceof Map) { Map config = (Map) c; final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); if (config.containsKey(name)) { final Class k = attribute.getType(); final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+ k); final Object value = configurator.configure(config.get(name)); attribute.setValue(o, value); } } } return o; }
#vulnerable code @Override public Object configure(Object c) throws Exception { final ExtensionList list = Jenkins.getInstance().getExtensionList(target); if (list.size() != 1) { throw new IllegalStateException(); } final Object o = list.get(0); if (c instanceof Map) { Map config = (Map) c; final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); if (config.containsKey(name)) { final Object value = Configurator.lookup(attribute.getType()).configure(config.get(name)); attribute.setValue(o, value); } } } return o; } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object configure(Object c) throws Exception { Map config = c instanceof Map ? (Map) c : Collections.EMPTY_MAP; final Constructor constructor = getDataBoundConstructor(target); if (constructor == null) { throw new IllegalStateException(target.getName() + " is missing a @DataBoundConstructor"); } final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); Object[] args = new Object[names.length]; if (parameters.length > 0) { // Many jenkins components haven't been migrated to @DataBoundSetter vs @NotNull constructor parameters // as a result it might be valid to reference a describable without parameters for (int i = 0; i < names.length; i++) { final Object value = config.remove(names[i]); if (value == null && parameters[i].getAnnotation(Nonnull.class) != null) { throw new IllegalArgumentException(names[i] + " is required to configure " + target); } final Class t = parameters[i].getType(); if (value != null) { if (Collection.class.isAssignableFrom(t)) { if (!(value instanceof List)) { throw new IllegalArgumentException(names[i] + " should be a list"); } final Type pt = parameters[i].getParameterizedType(); final Configurator lookup = Configurator.lookup(pt); final ArrayList<Object> list = new ArrayList<>(); for (Object o : (List) value) { list.add(lookup.configure(o)); } args[i] = list; } else { final Type pt = parameters[i].getParameterizedType(); final Type k = pt != null ? pt : t; final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+k); args[i] = configurator.configure(value); } System.out.println("Setting " + target + "." + names[i] + " = " + value); } else if (t.isPrimitive()) { args[i] = Defaults.defaultValue(t); } } } final Object object; try { object = constructor.newInstance(args); } catch (IllegalArgumentException ex) { List<String> argumentTypes = new ArrayList<>(args.length); for (Object arg : args) { argumentTypes.add(arg != null ? arg.getClass().getName() : "null"); } throw new IOException("Failed to construct instance of " + target + ". Constructor: " + constructor.toString() + ". Arguments: " + argumentTypes, ex); } final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Configurator lookup = Configurator.lookup(attribute.getType()); if (config.containsKey(name)) { final Object yaml = config.get(name); Object value; if (attribute.isMultiple()) { List l = new ArrayList<>(); for (Object o : (List) yaml) { l.add(lookup.configure(o)); } value = l; } else { value = lookup.configure(config.get(name)); } attribute.setValue(object, value); } } for (Method method : target.getMethods()) { if (method.getParameterCount() == 0 && method.getAnnotation(PostConstruct.class) != null) { method.invoke(object, null); } } return object; }
#vulnerable code @Override public Object configure(Object c) throws Exception { Map config = c instanceof Map ? (Map) c : Collections.EMPTY_MAP; final Constructor constructor = getDataBoundConstructor(target); if (constructor == null) { throw new IllegalStateException(target.getName() + " is missing a @DataBoundConstructor"); } final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); Object[] args = new Object[names.length]; if (parameters.length > 0) { // Many jenkins components haven't been migrated to @DataBoundSetter vs @NotNull constructor parameters // as a result it might be valid to reference a describable without parameters for (int i = 0; i < names.length; i++) { final Object value = config.remove(names[i]); if (value == null && parameters[i].getAnnotation(Nonnull.class) != null) { throw new IllegalArgumentException(names[i] + " is required to configure " + target); } final Class t = parameters[i].getType(); if (value != null) { if (Collection.class.isAssignableFrom(t)) { if (!(value instanceof List)) { throw new IllegalArgumentException(names[i] + " should be a list"); } final Type pt = parameters[i].getParameterizedType(); final Configurator lookup = Configurator.lookup(pt); final ArrayList<Object> list = new ArrayList<>(); for (Object o : (List) value) { list.add(lookup.configure(o)); } args[i] = list; } else { final Type pt = parameters[i].getParameterizedType(); final Type k = pt != null ? pt : t; final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+k); args[i] = configurator.configure(value); } System.out.println("Setting " + target + "." + names[i] + " = " + value); } else if (t.isPrimitive()) { args[i] = Defaults.defaultValue(t); } } } final Object object; try { object = constructor.newInstance(args); } catch (IllegalArgumentException ex) { List<String> argumentTypes = new ArrayList<>(args.length); for (Object arg : args) { argumentTypes.add(arg != null ? arg.getClass().getName() : "null"); } throw new IOException("Failed to construct instance of " + target + ". Constructor: " + constructor.toString() + ". Arguments: " + argumentTypes, ex); } final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Configurator lookup = Configurator.lookup(attribute.getType()); if (config.containsKey(name)) { final Object yaml = config.get(name); Object value; if (attribute.isMultiple()) { List l = new ArrayList<>(); for (Object o : (List) yaml) { l.add(lookup.configure(o)); } value = l; } else { value = lookup.configure(config.get(name)); } attribute.setValue(object, value); } } return object; } #location 81 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void configure(Map config, T instance) throws Exception { final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Object sub = removeIgnoreCase(config, name); if (sub != null) { final Class k = attribute.getType(); final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+k); if (attribute.isMultiple()) { List values = new ArrayList<>(); for (Object o : (List) sub) { Object value = configurator.configure(o); values.add(value); } attribute.setValue(instance, values); } else { Object value = configurator.configure(sub); attribute.setValue(instance, value); } } } if (!config.isEmpty()) { final String invalid = StringUtils.join(config.keySet(), ','); throw new IllegalArgumentException("Invalid configuration elements for type " + instance.getClass() + " : " + invalid); } }
#vulnerable code protected void configure(Map config, T instance) throws Exception { final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Object sub = removeIgnoreCase(config, name); if (sub != null) { if (attribute.isMultiple()) { List values = new ArrayList<>(); for (Object o : (List) sub) { Object value = Configurator.lookup(attribute.getType()).configure(o); values.add(value); } attribute.setValue(instance, values); } else { Object value = Configurator.lookup(attribute.getType()).configure(sub); attribute.setValue(instance, value); } } } if (!config.isEmpty()) { final String invalid = StringUtils.join(config.keySet(), ','); throw new IllegalArgumentException("Invalid configuration elements for type " + instance.getClass() + " : " + invalid); } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Nonnull private static RoleMap retrieveRoleMap(@Nonnull CNode config, @Nonnull String name, Configurator<RoleDefinition> configurator) throws ConfiguratorException { Mapping map = config.asMapping(); final CNode c = map.get(name); TreeMap<Role, Set<String>> resMap = new TreeMap<>(); if (c == null || c.asSequence() == null) { // we cannot return emptyMap here due to the Role Strategy code return new RoleMap(resMap); } for (CNode entry : c.asSequence()) { RoleDefinition definition = configurator.configure(entry); resMap.put(definition.getRole(), definition.getAssignments()); } return new RoleMap(resMap); }
#vulnerable code @Nonnull private static RoleMap retrieveRoleMap(@Nonnull CNode config, @Nonnull String name, Configurator<RoleDefinition> configurator) throws ConfiguratorException { Mapping map = config.asMapping(); final Sequence c = map.get(name).asSequence(); TreeMap<Role, Set<String>> resMap = new TreeMap<>(); if (c == null) { // we cannot return emptyMap here due to the Role Strategy code return new RoleMap(resMap); } for (CNode entry : c) { RoleDefinition definition = configurator.configure(entry); resMap.put(definition.getRole(), definition.getAssignments()); } return new RoleMap(resMap); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @CheckForNull @Override public CNode describe(T instance) throws Exception { // Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor // and all others using DataBoundSetters. So constructor parameters for sure are part of the description, others // need to be compared with default values. // Build same object with only constructor parameters final Constructor constructor = getDataBoundConstructor(); final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); final Attribute[] attributes = new Attribute[parameters.length]; final Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { final Parameter p = parameters[i]; final Attribute a = detectActualType(names[i], p.getParameterizedType()); args[i] = a.getValue(instance); attributes[i] = a; } T ref = (T) constructor.newInstance(args); // compare instance with this "default" object Mapping mapping = compare(instance, ref); // add constructor parameters for (int i = 0; i < parameters.length; i++) { final Configurator c = Configurator.lookup(attributes[i].getType()); if (args[i] == null) continue; mapping.put(names[i], attributes[i].describe(args[i])); } return mapping; }
#vulnerable code @CheckForNull @Override public CNode describe(T instance) throws Exception { // Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor // and all others using DataBoundSetters. So constructor parameters for sure are part of the description, others // need to be compared with default values. // Build same object with only constructor parameters final Constructor constructor = getDataBoundConstructor(target); final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); final Attribute[] attributes = new Attribute[parameters.length]; final Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { final Parameter p = parameters[i]; final Attribute a = detectActualType(names[i], p.getParameterizedType()); args[i] = a.getValue(instance); attributes[i] = a; } T ref = (T) constructor.newInstance(args); // compare instance with this "default" object Mapping mapping = compare(instance, ref); // add constructor parameters for (int i = 0; i < parameters.length; i++) { final Configurator c = Configurator.lookup(attributes[i].getType()); if (args[i] == null) continue; mapping.put(names[i], attributes[i].describe(args[i])); } return mapping; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Nonnull @Override public T configure(CNode c, ConfigurationContext context) throws ConfiguratorException { final Mapping mapping = (c != null ? c.asMapping() : Mapping.EMPTY); final T instance = instance(mapping, context); if (instance instanceof Saveable) { try (BulkChange bc = new BulkChange((Saveable) instance) ){ configure(mapping, instance, false, context); bc.commit(); } catch (IOException e) { throw new ConfiguratorException("Failed to save "+instance, e); } } else { configure(mapping, instance, false, context); } return instance; }
#vulnerable code @Nonnull @Override public T configure(CNode c, ConfigurationContext context) throws ConfiguratorException { final Mapping mapping = (c != null ? c.asMapping() : Mapping.EMPTY); final T instance = instance(mapping, context); if (instance instanceof Saveable) { BulkChange bc = new BulkChange((Saveable) instance); configure(mapping, instance, false, context); try { bc.commit(); } catch (IOException e) { throw new ConfiguratorException("Failed to save "+instance, e); } } else { configure(mapping, instance, false, context); } return instance; } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public ProjectMatrixAuthorizationStrategy configure(Object config) throws ConfiguratorException { Map map = (Map) config; Collection o = (Collection<?>)map.get("grantedPermissions"); Configurator<GroupPermissionDefinition> permissionConfigurator = Configurator.lookupOrFail(GroupPermissionDefinition.class); Map<Permission,Set<String>> grantedPermissions = new HashMap<>(); for(Object entry : o) { GroupPermissionDefinition gpd = permissionConfigurator.configureNonNull(entry); //We transform the linear list to a matrix (Where permission is the key instead) gpd.grantPermission(grantedPermissions); } ProjectMatrixAuthorizationStrategy gms = new ProjectMatrixAuthorizationStrategy(); for(Map.Entry<Permission,Set<String>> permission : grantedPermissions.entrySet()) { for(String sid : permission.getValue()) { gms.add(permission.getKey(), sid); } } return gms; }
#vulnerable code @Override public ProjectMatrixAuthorizationStrategy configure(Object config) throws Exception { Map map = (Map) config; Collection o = (Collection<?>)map.get("grantedPermissions"); Configurator<GroupPermissionDefinition> permissionConfigurator = Configurator.lookup(GroupPermissionDefinition.class); Map<Permission,Set<String>> grantedPermissions = new HashMap<>(); for(Object entry : o) { GroupPermissionDefinition gpd = permissionConfigurator.configure(entry); //We transform the linear list to a matrix (Where permission is the key instead) gpd.grantPermission(grantedPermissions); } ProjectMatrixAuthorizationStrategy gms = new ProjectMatrixAuthorizationStrategy(); for(Map.Entry<Permission,Set<String>> permission : grantedPermissions.entrySet()) { for(String sid : permission.getValue()) { gms.add(permission.getKey(), sid); } } return gms; } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @POST public FormValidation doCheckNewSource(@QueryParameter String newSource) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); String normalizedSource = Util.fixEmptyAndTrim(newSource); File file = new File(Util.fixNull(normalizedSource)); if (normalizedSource == null) { return FormValidation.ok(); // empty, do nothing } if (!file.exists() && !ConfigurationAsCode.isSupportedURI(normalizedSource)) { return FormValidation.error("Configuration cannot be applied. File or URL cannot be parsed or do not exist."); } List<YamlSource> yamlSources = Collections.emptyList(); try { List<String> sources = Collections.singletonList(normalizedSource); yamlSources = getConfigFromSources(sources); final Map<Source, String> issues = checkWith(yamlSources); final JSONArray errors = collectProblems(issues, "error"); if (!errors.isEmpty()) { return FormValidation.error(errors.toString()); } final JSONArray warnings = collectProblems(issues, "warning"); if (!warnings.isEmpty()) { return FormValidation.warning(warnings.toString()); } return FormValidation.okWithMarkup("The configuration can be applied"); } catch (ConfiguratorException | IllegalArgumentException e) { return FormValidation.error(e, e.getCause() == null ? e.getMessage() : e.getCause().getMessage()); } finally { closeSources(yamlSources); } }
#vulnerable code @POST public FormValidation doCheckNewSource(@QueryParameter String newSource) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); String normalizedSource = Util.fixEmptyAndTrim(newSource); File file = new File(Util.fixNull(normalizedSource)); if (normalizedSource == null) { return FormValidation.ok(); // empty, do nothing } if (!file.exists() && !ConfigurationAsCode.isSupportedURI(normalizedSource)) { return FormValidation.error("Configuration cannot be applied. File or URL cannot be parsed or do not exist."); } try { final Map<Source, String> issues = collectIssues(normalizedSource); final JSONArray errors = collectProblems(issues, "error"); if (!errors.isEmpty()) { return FormValidation.error(errors.toString()); } final JSONArray warnings = collectProblems(issues, "warning"); if (!warnings.isEmpty()) { return FormValidation.warning(warnings.toString()); } return FormValidation.okWithMarkup("The configuration can be applied"); } catch (ConfiguratorException | IllegalArgumentException e) { return FormValidation.error(e, e.getCause() == null ? e.getMessage() : e.getCause().getMessage()); } } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean equals(O o1, O o2) throws Exception { final Object v1 = getValue(o1); final Object v2 = getValue(o2); if (v1 == null && v2 == null) return true; return (v1 != null && v1.equals(v2)); }
#vulnerable code public boolean equals(O o1, O o2) throws Exception { final Object v1 = getValue(o1); final Object v2 = getValue(o2); if (v1 == null && v2 == null) return true; return (v1.equals(v2)); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public GlobalMatrixAuthorizationStrategy configure(Object config) throws ConfiguratorException { Map map = (Map) config; Collection o = (Collection<?>)map.get("grantedPermissions"); Configurator<GroupPermissionDefinition> permissionConfigurator = Configurator.lookupOrFail(GroupPermissionDefinition.class); Map<Permission,Set<String>> grantedPermissions = new HashMap<>(); for(Object entry : o) { GroupPermissionDefinition gpd = permissionConfigurator.configureNonNull(entry); //We transform the linear list to a matrix (Where permission is the key instead) gpd.grantPermission(grantedPermissions); } //TODO: Once change is in place for GlobalMatrixAuthentication. Switch away from reflection GlobalMatrixAuthorizationStrategy gms = new GlobalMatrixAuthorizationStrategy(); try { Field f = gms.getClass().getDeclaredField("grantedPermissions"); f.setAccessible(true); f.set(gms, grantedPermissions); } catch (NoSuchFieldException | IllegalAccessException ex) { throw new ConfiguratorException(this, "Cannot set GlobalMatrixAuthorizationStrategy#grantedPermissions via reflection", ex); } return gms; }
#vulnerable code @Override public GlobalMatrixAuthorizationStrategy configure(Object config) throws Exception { Map map = (Map) config; Collection o = (Collection<?>)map.get("grantedPermissions"); Configurator<GroupPermissionDefinition> permissionConfigurator = Configurator.lookup(GroupPermissionDefinition.class); Map<Permission,Set<String>> grantedPermissions = new HashMap<>(); for(Object entry : o) { GroupPermissionDefinition gpd = permissionConfigurator.configure(entry); //We transform the linear list to a matrix (Where permission is the key instead) gpd.grantPermission(grantedPermissions); } //TODO: Once change is in place for GlobalMatrixAuthentication. Switch away from reflection GlobalMatrixAuthorizationStrategy gms = new GlobalMatrixAuthorizationStrategy(); Field f = gms.getClass().getDeclaredField("grantedPermissions"); f.setAccessible(true); f.set(gms, grantedPermissions); return gms; } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @CheckForNull @Override public CNode describe(T instance) throws Exception { // Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor // and all others using DataBoundSetters. So constructor parameters for sure are part of the description, others // need to be compared with default values. // Build same object with only constructor parameters final Constructor constructor = getDataBoundConstructor(target); final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); final Attribute[] attributes = new Attribute[parameters.length]; final Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { final Parameter p = parameters[i]; final Attribute a = detectActualType(names[i], p.getParameterizedType()); args[i] = a.getValue(instance); attributes[i] = a; } T ref = (T) constructor.newInstance(args); // compare instance with this "default" object Mapping mapping = compare(instance, ref); // add constructor parameters for (int i = 0; i < parameters.length; i++) { final Configurator c = Configurator.lookup(attributes[i].getType()); if (args[i] == null) continue; mapping.put(names[i], attributes[i].describe(args[i])); } return mapping; }
#vulnerable code @CheckForNull @Override public CNode describe(T instance) throws Exception { // Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor // and all others using DataBoundSetters. So constructor parameters for sure are part of the description, others // need to be compared with default values. // Build same object with only constructor parameters final Constructor constructor = getDataBoundConstructor(target); final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); final Attribute[] attributes = new Attribute[parameters.length]; final Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { final Parameter p = parameters[i]; final Attribute a = detectActualType(names[i], p.getParameterizedType()); args[i] = a.getValue(instance); attributes[i] = a; } T ref = (T) constructor.newInstance(args); // compare instance with this "default" object Mapping mapping = compare(instance, ref); // add constructor parameters for (int i = 0; i < parameters.length; i++) { final Configurator c = Configurator.lookup(attributes[i].getType()); mapping.put(names[i], c.describe(args[i])); } return mapping; } #location 31 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void configure(Map config, T instance) throws Exception { final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Object sub = removeIgnoreCase(config, name); if (sub != null) { final Class k = attribute.getType(); final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+k); if (attribute.isMultiple()) { List values = new ArrayList<>(); for (Object o : (List) sub) { Object value = configurator.configure(o); values.add(value); } attribute.setValue(instance, values); } else { Object value = configurator.configure(sub); attribute.setValue(instance, value); } } } if (!config.isEmpty()) { final String invalid = StringUtils.join(config.keySet(), ','); throw new IllegalArgumentException("Invalid configuration elements for type " + instance.getClass() + " : " + invalid); } }
#vulnerable code protected void configure(Map config, T instance) throws Exception { final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Object sub = removeIgnoreCase(config, name); if (sub != null) { if (attribute.isMultiple()) { List values = new ArrayList<>(); for (Object o : (List) sub) { Object value = Configurator.lookup(attribute.getType()).configure(o); values.add(value); } attribute.setValue(instance, values); } else { Object value = Configurator.lookup(attribute.getType()).configure(sub); attribute.setValue(instance, value); } } } if (!config.isEmpty()) { final String invalid = StringUtils.join(config.keySet(), ','); throw new IllegalArgumentException("Invalid configuration elements for type " + instance.getClass() + " : " + invalid); } } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public DLegerEntry get(Long index) { PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLeaderId()); SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE); PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); indexSbr.getByteBuffer().getInt(); //magic long pos = indexSbr.getByteBuffer().getLong(); int size = indexSbr.getByteBuffer().getInt(); indexSbr.release(); SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size); PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer()); dataSbr.release(); return dLegerEntry; }
#vulnerable code @Override public DLegerEntry get(Long index) { PreConditions.check(index <= legerEndIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should < %d", index, legerEndIndex), memberState.getLeaderId()); SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE); PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); indexSbr.getByteBuffer().getInt(); //magic long pos = indexSbr.getByteBuffer().getLong(); int size = indexSbr.getByteBuffer().getInt(); indexSbr.release(); SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size); PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer()); dataSbr.release(); return dLegerEntry; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); reviseLegerBeginIndex(); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; }
#vulnerable code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); //get leger begin index ByteBuffer tmpBuffer = dataFileQueue.getFirstMappedFile().sliceByteBuffer(); tmpBuffer.getInt(); //magic tmpBuffer.getInt(); //size legerBeginIndex = byteBuffer.getLong(); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; } #location 140 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void changeRoleToCandidate(long term) { logger.info("[{}][ChangeRoleToCandidate] from term: {} and currterm: {}", memberState.getSelfId(), term, memberState.currTerm()); memberState.changeToCandidate(term); }
#vulnerable code public void changeRoleToCandidate(long term) { logger.info("[{}][ChangeRoleToCandidate] from term: {} and currterm: {}", memberState.getSelfId(), term, memberState.currTerm()); memberState.changeToCandidate(term); nextTimeToRequestVote = -1; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); reviseLegerBeginIndex(); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; }
#vulnerable code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); //get leger begin index ByteBuffer tmpBuffer = dataFileQueue.getFirstMappedFile().sliceByteBuffer(); tmpBuffer.getInt(); //magic tmpBuffer.getInt(); //size legerBeginIndex = byteBuffer.getLong(); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; } #location 133 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long append(byte[] data, int pos, int len, boolean useBlank) { if (preAppend(len, useBlank) == -1) { return -1; } MmapFile mappedFile = getLastMappedFile(); long currPosition = mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); if (!mappedFile.appendMessage(data, pos, len)) { logger.error("Append error for {}", storePath); return -1; } return currPosition; }
#vulnerable code public long append(byte[] data, int pos, int len, boolean useBlank) { MmapFile mappedFile = getLastMappedFile(); if (null == mappedFile || mappedFile.isFull()) { mappedFile = getLastMappedFile(0); } if (null == mappedFile) { logger.error("Create mapped file for {}", storePath); return -1; } int blank = useBlank ? MIN_BLANK_LEN : 0; if (len + blank > mappedFile.getFileSize() - mappedFile.getWrotePosition()) { if (blank < MIN_BLANK_LEN) { logger.error("Blank {} should ge {}", blank, MIN_BLANK_LEN); return -1; } else { ByteBuffer byteBuffer = ByteBuffer.allocate(mappedFile.getFileSize() - mappedFile.getWrotePosition()); byteBuffer.putInt(BLANK_MAGIC_CODE); byteBuffer.putInt(mappedFile.getFileSize() - mappedFile.getWrotePosition()); if (mappedFile.appendMessage(byteBuffer.array())) { //need to set the wrote position mappedFile.setWrotePosition(mappedFile.getFileSize()); } else { logger.error("Append blank error for {}", storePath); return -1; } mappedFile = getLastMappedFile(0); if (null == mappedFile) { logger.error("Create mapped file for {}", storePath); return -1; } } } long currPosition = mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); if (!mappedFile.appendMessage(data, pos, len)) { logger.error("Append error for {}", storePath); return -1; } return currPosition; } #location 34 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public CompletableFuture<HeartBeatResponse> handleHeartBeat(HeartBeatRequest request) throws Exception { if (request.getTerm() < memberState.currTerm()) { return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().term(memberState.currTerm()).code(DLegerResponseCode.EXPIRED_TERM.getCode())); } else if (request.getTerm() == memberState.currTerm()) { if (request.getLeaderId().equals(memberState.getLeaderId())) { lastLeaderHeartBeatTime = System.currentTimeMillis(); return CompletableFuture.completedFuture(new HeartBeatResponse()); } } //abnormal case //hold the lock to get the latest term and leaderId synchronized (memberState) { if (request.getTerm() < memberState.currTerm()) { return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().term(memberState.currTerm()).code(DLegerResponseCode.EXPIRED_TERM.getCode())); } else if (request.getTerm() == memberState.currTerm()) { if (memberState.getLeaderId() == null) { changeRoleToFollower(request.getTerm(), request.getLeaderId()); return CompletableFuture.completedFuture(new HeartBeatResponse()); } else if (request.getLeaderId().equals(memberState.getLeaderId())) { lastLeaderHeartBeatTime = System.currentTimeMillis(); return CompletableFuture.completedFuture(new HeartBeatResponse()); } else { //this should not happen, but if happened logger.error("[{}][BUG] currterm {} has leader {}, but received leader {}", memberState.getSelfId(), memberState.currTerm(), memberState.getLeaderId(), request.getLeaderId()); return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().code(DLegerResponseCode.INCONSISTENT_LEADER.getCode())); } } else { //To make it simple, for larger term, do not change to follower immediately //first change to candidate, and notify the state-maintainer thread changeRoleToCandidate(request.getTerm()); //TOOD notify return CompletableFuture.completedFuture(new HeartBeatResponse()); } } }
#vulnerable code public CompletableFuture<HeartBeatResponse> handleHeartBeat(HeartBeatRequest request) throws Exception { if (request.getTerm() < memberState.currTerm()) { return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().term(memberState.currTerm()).code(DLegerResponseCode.EXPIRED_TERM.getCode())); } else if (request.getTerm() == memberState.currTerm()) { if (request.getLeaderId().equals(memberState.getLeaderId())) { lastLeaderHeartBeatTime = System.currentTimeMillis(); return CompletableFuture.completedFuture(new HeartBeatResponse()); } } //abnormal case //hold the lock to get the latest term and leaderId synchronized (memberState) { if (request.getTerm() < memberState.currTerm()) { return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().term(memberState.currTerm()).code(DLegerResponseCode.EXPIRED_TERM.getCode())); } else if (request.getTerm() == memberState.currTerm()) { if (memberState.getLeaderId() == null) { changeRoleToFollower(request.getTerm(), request.getLeaderId()); return CompletableFuture.completedFuture(new HeartBeatResponse()); } else if (request.getLeaderId().equals(memberState.getLeaderId())) { lastLeaderHeartBeatTime = System.currentTimeMillis(); return CompletableFuture.completedFuture(new HeartBeatResponse()); } else { //this should not happen, but if happened logger.error("[{}][BUG] currterm {} has leader {}, but received leader {}", memberState.getSelfId(), memberState.currTerm(), memberState.getLeaderId(), request.getLeaderId()); return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().code(DLegerResponseCode.INTERNAL_ERROR.getCode())); } } else { //To make it simple, for larger term, do not change to follower immediately //first change to candidate, and notify the state-maintainer thread changeRoleToCandidate(request.getTerm()); //TOOD notify return CompletableFuture.completedFuture(new HeartBeatResponse()); } } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long append(byte[] data, int pos, int len, boolean useBlank) { if (preAppend(len, useBlank) == -1) { return -1; } MmapFile mappedFile = getLastMappedFile(); long currPosition = mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); if (!mappedFile.appendMessage(data, pos, len)) { logger.error("Append error for {}", storePath); return -1; } return currPosition; }
#vulnerable code public long append(byte[] data, int pos, int len, boolean useBlank) { MmapFile mappedFile = getLastMappedFile(); if (null == mappedFile || mappedFile.isFull()) { mappedFile = getLastMappedFile(0); } if (null == mappedFile) { logger.error("Create mapped file for {}", storePath); return -1; } int blank = useBlank ? MIN_BLANK_LEN : 0; if (len + blank > mappedFile.getFileSize() - mappedFile.getWrotePosition()) { if (blank < MIN_BLANK_LEN) { logger.error("Blank {} should ge {}", blank, MIN_BLANK_LEN); return -1; } else { ByteBuffer byteBuffer = ByteBuffer.allocate(mappedFile.getFileSize() - mappedFile.getWrotePosition()); byteBuffer.putInt(BLANK_MAGIC_CODE); byteBuffer.putInt(mappedFile.getFileSize() - mappedFile.getWrotePosition()); if (mappedFile.appendMessage(byteBuffer.array())) { //need to set the wrote position mappedFile.setWrotePosition(mappedFile.getFileSize()); } else { logger.error("Append blank error for {}", storePath); return -1; } mappedFile = getLastMappedFile(0); if (null == mappedFile) { logger.error("Create mapped file for {}", storePath); return -1; } } } long currPosition = mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); if (!mappedFile.appendMessage(data, pos, len)) { logger.error("Append error for {}", storePath); return -1; } return currPosition; } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public DLegerEntry get(Long index) { PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLeaderId()); SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE); PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); indexSbr.getByteBuffer().getInt(); //magic long pos = indexSbr.getByteBuffer().getLong(); int size = indexSbr.getByteBuffer().getInt(); indexSbr.release(); SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size); PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer()); dLegerEntry.setPos(pos); dataSbr.release(); return dLegerEntry; }
#vulnerable code @Override public DLegerEntry get(Long index) { PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLeaderId()); SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE); PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); indexSbr.getByteBuffer().getInt(); //magic long pos = indexSbr.getByteBuffer().getLong(); int size = indexSbr.getByteBuffer().getInt(); indexSbr.release(); SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size); PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer()); dataSbr.release(); return dLegerEntry; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); //get leger begin index ByteBuffer tmpBuffer = dataFileQueue.getFirstMappedFile().sliceByteBuffer(); tmpBuffer.getInt(); //magic tmpBuffer.getInt(); //size legerBeginIndex = byteBuffer.getLong(); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; }
#vulnerable code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; } #location 133 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private InputStream buildWrappedInputStream(InputStream downloadInputStream) throws TransformerException, IOException { // Pass the download input stream through a Transformer that removes the XML // declaration. Create a new TransformerFactory and Transformer on each invocation // since these objects are <em>not</em> thread safe. Transformer omitXmlDeclarationTransformer = TransformerFactory.newInstance().newTransformer(); omitXmlDeclarationTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); omitXmlDeclarationTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); omitXmlDeclarationTransformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", INDENT_AMOUNT); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); StreamResult streamResult = new StreamResult(outputStream); Source xmlSource = new StreamSource(downloadInputStream); omitXmlDeclarationTransformer.transform(xmlSource, streamResult); return ByteSource.concat( ByteSource.wrap(SOAP_START_BODY.getBytes()), ByteSource.wrap(outputStream.toByteArray()), ByteSource.wrap(SOAP_END_BODY.getBytes())).openStream(); }
#vulnerable code private InputStream buildWrappedInputStream(InputStream downloadInputStream) throws TransformerException, IOException { // Pass the download input stream through a transformer that removes the XML // declaration. Transformer omitXmlDeclarationTransformer = getTransformer(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); StreamResult streamResult = new StreamResult(outputStream); Source xmlSource = new StreamSource(downloadInputStream); omitXmlDeclarationTransformer.transform(xmlSource, streamResult); return ByteSource.concat( ByteSource.wrap(SOAP_START_BODY.getBytes()), ByteSource.wrap(outputStream.toByteArray()), ByteSource.wrap(SOAP_END_BODY.getBytes())).openStream(); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMarkNotSupported() throws Exception { byte[] plaintext = getRandomBytes(1); final String password = "Testing1234"; JNCryptor cryptor = new AES256JNCryptor(); byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( data), password.toCharArray()); assertFalse(in.markSupported()); in.close(); }
#vulnerable code @Test public void testMarkNotSupported() throws Exception { byte[] plaintext = getRandomBytes(1); final String password = "Testing1234"; JNCryptor cryptor = new AES256JNCryptor(); byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( data), password.toCharArray()); assertFalse(in.markSupported()); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static String getLine(File file, int line) throws IOException { BufferedReader reader = Files.newBufferedReader(file.toPath(), Options.encoding); String msg = ""; for (int i = 0; i <= line; i++) msg = reader.readLine(); reader.close(); return msg; }
#vulnerable code private static String getLine(File file, int line) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String msg = ""; for (int i = 0; i <= line; i++) msg = reader.readLine(); reader.close(); return msg; } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected static ClassInfo guessPackageAndClass(File lexFile) throws FileNotFoundException, IOException { assert lexFile.isAbsolute() : lexFile; LineNumberReader reader = new LineNumberReader(new FileReader(lexFile)); try { ClassInfo classInfo = new ClassInfo(); while (classInfo.className == null || classInfo.packageName == null) { String line = reader.readLine(); if (line == null) break; if (classInfo.packageName == null) { int index = line.indexOf("package"); if (index >= 0) { index += 7; int end = line.indexOf(';', index); if (end >= index) { classInfo.packageName = line.substring(index, end); classInfo.packageName = classInfo.packageName.trim(); } } } if (classInfo.className == null) { int index = line.indexOf("%class"); if (index >= 0) { index += 6; classInfo.className = line.substring(index); classInfo.className = classInfo.className.trim(); } } } if (classInfo.className == null) { classInfo.className = DEFAULT_NAME; } return classInfo; } finally { reader.close(); } }
#vulnerable code protected static ClassInfo guessPackageAndClass(File lexFile) throws FileNotFoundException, IOException { assert lexFile.isAbsolute() : lexFile; LineNumberReader reader = new LineNumberReader(new FileReader(lexFile)); ClassInfo classInfo = new ClassInfo(); while (classInfo.className == null || classInfo.packageName == null) { String line = reader.readLine(); if (line == null) break; if (classInfo.packageName == null) { int index = line.indexOf("package"); if (index >= 0) { index += 7; int end = line.indexOf(';', index); if (end >= index) { classInfo.packageName = line.substring(index, end); classInfo.packageName = classInfo.packageName.trim(); } } } if (classInfo.className == null) { int index = line.indexOf("%class"); if (index >= 0) { index += 6; classInfo.className = line.substring(index); classInfo.className = classInfo.className.trim(); } } } if (classInfo.className == null) { classInfo.className = DEFAULT_NAME; } return classInfo; } #location 38 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String getPageContent(URL url) throws IOException { try(InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8")) { StringBuilder builder = new StringBuilder(); char[] buf = new char[BUF_SIZE]; int charsRead; while ((charsRead = reader.read(buf)) > 0) { builder.append(buf, 0, charsRead); } return builder.toString(); } }
#vulnerable code private String getPageContent(URL url) throws IOException { InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8"); StringBuilder builder = new StringBuilder(); char[] buf = new char[BUF_SIZE]; int charsRead; while ((charsRead = reader.read(buf)) > 0) { builder.append(buf, 0, charsRead); } return builder.toString(); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void runNext() throws TestFailException, UnsupportedEncodingException { // Get first file and remove it from vector InputOutput current = inputOutput.remove(0); // Create List with only first input in List<String> param = new ArrayList<String>(); param.add(current.getName() + ".input"); // Excute Main on that input classExecResult = Exec.execClass (className, testPath.toString(), new ArrayList<String>(), param, Main.jflexTestVersion, outputFileEncoding); if (Main.verbose) { System.out.println("Running scanner on [" + current.getName() + "]"); } // check for output conformance File expected = new File(current.getName() + ".output"); if (expected.exists()) { DiffStream check = new DiffStream(); String diff; try { diff = check.diff(jflexDiff, new StringReader(classExecResult.getOutput()), new InputStreamReader(new FileInputStream(expected), outputFileEncoding)); } catch (FileNotFoundException e) { System.out.println("Error opening file " + expected); throw new TestFailException(); } catch (UnsupportedEncodingException e) { System.out.println("Unsupported encoding '" + outputFileEncoding + "'"); throw new TestFailException(); } if (diff != null) { System.out.println("Test failed, unexpected output: " + diff); System.out.println("Test output: " + classExecResult.getOutput()); throw new TestFailException(); } } else { System.out.println("Warning: no file for expected output [" + expected + "]"); } // System.out.println(classExecResult); }
#vulnerable code public void runNext() throws TestFailException { // Get first file and remove it from vector InputOutput current = inputOutput.remove(0); // Create List with only first input in List<String> param = new ArrayList<String>(); param.add(current.getName() + ".input"); // Excute Main on that input classExecResult = Exec.execClass (className, testPath.toString(), new ArrayList<String>(), param, Main.jflexTestVersion); if (Main.verbose) { System.out.println("Running scanner on [" + current.getName() + "]"); } // check for output conformance File expected = new File(current.getName() + ".output"); if (expected.exists()) { DiffStream check = new DiffStream(); String diff; try { diff = check.diff(jflexDiff, new StringReader(classExecResult.getOutput()), new FileReader(expected)); } catch (FileNotFoundException e) { System.out.println("Error opening file " + expected); throw new TestFailException(); } if (diff != null) { System.out.println("Test failed, unexpected output: " + diff); System.out.println("Test output: " + classExecResult.getOutput()); throw new TestFailException(); } } else { System.out.println("Warning: no file for expected output [" + expected + "]"); } // System.out.println(classExecResult); } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private byte[] loadJarData(String path, String fileName) { ZipFile zipFile; ZipEntry entry; int size; try { zipFile = new ZipFile(new File(path)); entry = zipFile.getEntry(fileName); if (entry == null) { zipFile.close(); return null; } size = (int) entry.getSize(); } catch (IOException io) { return null; } InputStream stream = null; try { stream = zipFile.getInputStream(entry); if (stream == null) { zipFile.close(); return null; } byte[] data = new byte[size]; int pos = 0; while (pos < size) { int n = stream.read(data, pos, data.length - pos); pos += n; } zipFile.close(); return data; } catch (IOException e) { } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return null; }
#vulnerable code private byte[] loadJarData(String path, String fileName) { ZipFile zipFile; ZipEntry entry; int size; try { zipFile = new ZipFile(new File(path)); entry = zipFile.getEntry(fileName); if (entry == null) return null; size = (int) entry.getSize(); } catch (IOException io) { return null; } InputStream stream = null; try { stream = zipFile.getInputStream(entry); if (stream == null) return null; byte[] data = new byte[size]; int pos = 0; while (pos < size) { int n = stream.read(data, pos, data.length - pos); pos += n; } zipFile.close(); return data; } catch (IOException e) { } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return null; } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void findPackageAndClass() throws IOException { // find name of the package and class in jflex source file packageName = null; className = null; LineNumberReader reader = new LineNumberReader(new FileReader(inputFile)); try { while (className == null || packageName == null) { String line = reader.readLine(); if (line == null) break; if (packageName == null) { Matcher matcher = PACKAGE_PATTERN.matcher(line); if (matcher.find()) { packageName = matcher.group(1); } } if (className == null) { Matcher matcher = CLASS_PATTERN.matcher(line); if (matcher.find()) { className = matcher.group(1); } } } // package name may be null, but class name not if (className == null) { className = "Yylex"; } } finally { reader.close(); } }
#vulnerable code public void findPackageAndClass() throws IOException { // find name of the package and class in jflex source file packageName = null; className = null; LineNumberReader reader = new LineNumberReader(new FileReader(inputFile)); while (className == null || packageName == null) { String line = reader.readLine(); if (line == null) break; if (packageName == null) { Matcher matcher = PACKAGE_PATTERN.matcher(line); if (matcher.find()) { packageName = matcher.group(1); } } if (className == null) { Matcher matcher = CLASS_PATTERN.matcher(line); if (matcher.find()) { className = matcher.group(1); } } } // package name may be null, but class name not if (className == null) className = "Yylex"; } #location 28 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private byte[] loadJarData(String path, String fileName) { ZipFile zipFile; ZipEntry entry; int size; try { zipFile = new ZipFile(new File(path)); entry = zipFile.getEntry(fileName); if (entry == null) { zipFile.close(); return null; } size = (int) entry.getSize(); } catch (IOException io) { return null; } InputStream stream = null; try { stream = zipFile.getInputStream(entry); if (stream == null) { zipFile.close(); return null; } byte[] data = new byte[size]; int pos = 0; while (pos < size) { int n = stream.read(data, pos, data.length - pos); pos += n; } zipFile.close(); return data; } catch (IOException e) { } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return null; }
#vulnerable code private byte[] loadJarData(String path, String fileName) { ZipFile zipFile; ZipEntry entry; int size; try { zipFile = new ZipFile(new File(path)); entry = zipFile.getEntry(fileName); if (entry == null) return null; size = (int) entry.getSize(); } catch (IOException io) { return null; } InputStream stream = null; try { stream = zipFile.getInputStream(entry); if (stream == null) return null; byte[] data = new byte[size]; int pos = 0; while (pos < size) { int n = stream.read(data, pos, data.length - pos); pos += n; } zipFile.close(); return data; } catch (IOException e) { } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return null; } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void read(String skeletonFilename) throws Exception { ClassLoader loader = UnicodePropertiesSkeleton.class.getClassLoader(); URL url = loader.getResource(skeletonFilename); if (null == url) { throw new Exception("Cannot locate '" + skeletonFilename + "' - aborting."); } String line; StringBuilder section = new StringBuilder(); try (BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream(), "UTF-8"))) { while (null != (line = reader.readLine())) { if (line.startsWith("---")) { sections.add(section.toString()); section.setLength(0); } else { section.append(line); section.append(NL); } } if (section.length() > 0) { sections.add(section.toString()); } if (sections.size() != size) { throw new Exception("Skeleton file '" + skeletonFilename + "' has " + sections.size() + " static sections, but " + size + " were expected."); } } }
#vulnerable code public void read(String skeletonFilename) throws Exception { ClassLoader loader = UnicodePropertiesSkeleton.class.getClassLoader(); URL url = loader.getResource(skeletonFilename); if (null == url) { throw new Exception("Cannot locate '" + skeletonFilename + "' - aborting."); } String line; StringBuilder section = new StringBuilder(); BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream(), "UTF-8")); while (null != (line = reader.readLine())) { if (line.startsWith("---")) { sections.add(section.toString()); section.setLength(0); } else { section.append(line); section.append(NL); } } if (section.length() > 0) { sections.add(section.toString()); } if (sections.size() != size) { throw new Exception("Skeleton file '" + skeletonFilename + "' has " + sections.size() + " static sections, but " + size + " were expected."); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private InputStream getZipEntryStream(String file, String entryName) { try (ZipFile zip = new ZipFile(new File(file))) { ZipEntry entry = zip.getEntry(entryName); if (entry == null) return null; return zip.getInputStream(entry); } catch (IOException e) { return null; } }
#vulnerable code private InputStream getZipEntryStream(String file, String entryName) { try { ZipFile zip = new ZipFile(new File(file)); ZipEntry entry = zip.getEntry(entryName); if (entry == null) return null; return zip.getInputStream(entry); } catch (IOException e) { return null; } } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String getPageContent(URL url) throws IOException { try(InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8")) { StringBuilder builder = new StringBuilder(); char[] buf = new char[BUF_SIZE]; int charsRead; while ((charsRead = reader.read(buf)) > 0) { builder.append(buf, 0, charsRead); } return builder.toString(); } }
#vulnerable code private String getPageContent(URL url) throws IOException { InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8"); StringBuilder builder = new StringBuilder(); char[] buf = new char[BUF_SIZE]; int charsRead; while ((charsRead = reader.read(buf)) > 0) { builder.append(buf, 0, charsRead); } return builder.toString(); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private InputStream getZipEntryStream(String file, String entryName) { try (ZipFile zip = new ZipFile(new File(file))) { ZipEntry entry = zip.getEntry(entryName); if (entry == null) return null; return zip.getInputStream(entry); } catch (IOException e) { return null; } }
#vulnerable code private InputStream getZipEntryStream(String file, String entryName) { try { ZipFile zip = new ZipFile(new File(file)); ZipEntry entry = zip.getEntry(entryName); if (entry == null) return null; return zip.getInputStream(entry); } catch (IOException e) { return null; } } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void copyTo(Wire wire) { while (bytes.remaining() > 0) { int code = bytes.readUnsignedByte(); switch (code >> 4) { case NUM0: case NUM1: case NUM2: case NUM3: case NUM4: case NUM5: case NUM6: case NUM7: wire.writeValue().uint8(code); break; case CONTROL: break; case FLOAT: double d = readFloat(code); wire.writeValue().float64(d); break; case INT: long l = readInt(code); wire.writeValue().int64(l); break; case SPECIAL: copySpecial(wire, code); break; case FIELD0: case FIELD1: bytes.skip(-1); StringBuilder fsb = readField(code, Wires.acquireStringBuilder()); wire.write(fsb, null); break; case STR0: case STR1: bytes.skip(-1); StringBuilder sb = readText(code, Wires.acquireStringBuilder()); wire.writeValue().text(sb); break; } } }
#vulnerable code @Override public void copyTo(Wire wire) { while (bytes.remaining() > 0) { int code = bytes.readUnsignedByte(); switch (code >> 4) { case NUM0: case NUM1: case NUM2: case NUM3: case NUM4: case NUM5: case NUM6: case NUM7: writeValue.uint8(code); break; case CONTROL: break; case FLOAT: double d = readFloat(code); writeValue.float64(d); break; case INT: long l = readInt(code); writeValue.int64(l); break; case SPECIAL: copySpecial(code); break; case FIELD0: case FIELD1: StringBuilder fsb = readField(code, Wires.acquireStringBuilder()); writeField(fsb); break; case STR0: case STR1: StringBuilder sb = readText(code, Wires.acquireStringBuilder()); writeValue.text(sb); break; } } } #location 37 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean readOne() { try (DocumentContext context = in.readingDocument()) { if (!context.isPresent()) return false; if (context.isMetaData()) return readOneMetaData(context); assert context.isData(); messageHistory.reset(context.sourceId(), context.index()); wireParser.accept(context.wire()); } return true; }
#vulnerable code public boolean readOne() { for (; ; ) { try (DocumentContext context = in.readingDocument()) { if (!context.isPresent()) return false; if (context.isMetaData()) { StringBuilder sb = Wires.acquireStringBuilder(); long r = context.wire().bytes().readPosition(); try { context.wire().readEventName(sb); for (String s : metaIgnoreList) { // we wish to ignore our system meta data field if (s.contentEquals(sb)) return false; } } finally { // roll back position to where is was before we read the SB context.wire().bytes().readPosition(r); } wireParser.accept(context.wire()); return true; } if (!context.isData()) continue; MessageHistory history = messageHistory; history.reset(context.sourceId(), context.index()); wireParser.accept(context.wire()); } return true; } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void setupOrTeardown(DbUnitTestContext testContext, boolean isSetup, Collection<AnnotationAttributes> annotations) throws Exception { IDatabaseConnection connection = testContext.getConnection(); for (AnnotationAttributes annotation : annotations) { List<IDataSet> datasets = loadDataSets(testContext, annotation); DatabaseOperation operation = annotation.getType(); org.dbunit.operation.DatabaseOperation dbUnitOperation = getDbUnitDatabaseOperation(testContext, operation); if (!datasets.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("Executing " + (isSetup ? "Setup" : "Teardown") + " of @DatabaseTest using " + operation + " on " + datasets.toString()); } IDataSet dataSet = new CompositeDataSet(datasets.toArray(new IDataSet[datasets.size()])); dbUnitOperation.execute(connection, dataSet); } } }
#vulnerable code private void setupOrTeardown(DbUnitTestContext testContext, boolean isSetup, Collection<AnnotationAttributes> annotations) throws Exception { IDatabaseConnection connection = testContext.getConnection(); DatabaseOperation lastOperation = null; for (AnnotationAttributes annotation : annotations) { for (String dataSetLocation : annotation.getValue()) { DatabaseOperation operation = annotation.getType(); org.dbunit.operation.DatabaseOperation dbUnitDatabaseOperation = getDbUnitDatabaseOperation( testContext, operation, lastOperation); IDataSet dataSet = loadDataset(testContext, dataSetLocation); if (dataSet != null) { if (logger.isDebugEnabled()) { logger.debug("Executing " + (isSetup ? "Setup" : "Teardown") + " of @DatabaseTest using " + operation + " on " + dataSetLocation); } dbUnitDatabaseOperation.execute(connection, dataSet); lastOperation = operation; } } } } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public ListenableFuture<IBigQueue> queueReadyForDequeue() { initializeFutureIfNecessary(); return dequeueFuture; }
#vulnerable code @Override public ListenableFuture<IBigQueue> queueReadyForDequeue() { futureLock.lock(); if (dequeueFuture == null || dequeueFuture.isDone() || dequeueFuture.isCancelled()) { dequeueFuture = SettableFuture.create(); } futureLock.unlock(); return dequeueFuture; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void close() throws IOException { if (this.queueFrontIndexPageFactory != null) { this.queueFrontIndexPageFactory.releaseCachedPages(); } synchronized (futureLock) { /* Cancel the future but don't interrupt running tasks because they might perform further work not refering to the queue */ if (peekFuture != null) { peekFuture.cancel(false); } if (dequeueFuture != null) { dequeueFuture.cancel(false); } } this.innerArray.close(); }
#vulnerable code @Override public void close() throws IOException { if (this.queueFrontIndexPageFactory != null) { this.queueFrontIndexPageFactory.releaseCachedPages(); } if (dequeueFuture != null) { /* Cancel the future but don't interrupt running tasks because they might perform further work not refering to the queue */ dequeueFuture.cancel(false); } this.innerArray.close(); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConstructor5() { ClassCastInputCSVException e = new ClassCastInputCSVException(Integer.valueOf(23), String.class, ANONYMOUS_CSVCONTEXT, PROCESSOR); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(PROCESSOR, e.getOffendingProcessor()); e.printStackTrace(); // test with null received value e = new ClassCastInputCSVException(null, String.class, ANONYMOUS_CSVCONTEXT, PROCESSOR); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(PROCESSOR, e.getOffendingProcessor()); e.printStackTrace(); // test with null received, expected, context and processor try { e = new ClassCastInputCSVException(null, null, (CSVContext) null, (CellProcessor) null); fail("should have thrown NullPointerException"); } catch(NullPointerException npe) {} }
#vulnerable code @Test public void testConstructor5(){ ClassCastInputCSVException e = new ClassCastInputCSVException(Integer.valueOf(23), String.class, ANONYMOUS_CSVCONTEXT, PROCESSOR); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(PROCESSOR, e.getOffendingProcessor()); e.printStackTrace(); // test with null received value e = new ClassCastInputCSVException(null, String.class, ANONYMOUS_CSVCONTEXT, PROCESSOR); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(PROCESSOR, e.getOffendingProcessor()); e.printStackTrace(); // test with null received, expected, context and processor e = new ClassCastInputCSVException(null, null, (CSVContext) null, (CellProcessor) null); assertNull(e.getMessage()); assertNull(e.getCsvContext()); assertNull(e.getOffendingProcessor()); e.printStackTrace(); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConstructor3() { NullInputException e = new NullInputException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); assertEquals(MSG, e.getMessage()); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg, context and throwable e = new NullInputException(null, (CSVContext) null, (Throwable) null); assertNull(e.getMessage()); assertNull(e.getCsvContext()); assertNull(e.getCause()); e.printStackTrace(); }
#vulnerable code @Test public void testConstructor3() { NullInputException e = new NullInputException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); assertEquals(CONCATENATED_MSG, e.getMessage()); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg, context and throwable e = new NullInputException(null, (CSVContext) null, (Throwable) null); assertNull(e.getMessage()); assertNull(e.getCsvContext()); assertNull(e.getCause()); e.printStackTrace(); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testProcesssedRead() throws Exception { UserBean user; final String[] header = inFile.getCSVHeader(true); assertThat(header[2], is("date")); user = inFile.read(UserBean.class, header, processors); Assert.assertEquals("read elem ", "Klaus", user.getUsername()); Assert.assertEquals("read elem ", "qwexyKiks", user.getPassword()); final Date cal = new Date(2007 - 1900, 10 - 1, 1); Assert.assertEquals(cal, user.getDate()); Assert.assertEquals("read elem ", 4328, user.getZip()); Assert.assertEquals("read elem ", "New York", user.getTown()); }
#vulnerable code @Test public void testProcesssedRead() throws Exception { UserBean user; final String[] header = inFile.getCSVHeader(true); user = inFile.read(UserBean.class, header, processors); Assert.assertEquals("read elem ", "Klaus", user.getUsername()); Assert.assertEquals("read elem ", "qwexyKiks", user.getPassword()); final Date cal = new Date(2007 - 1900, 10 - 1, 1); Assert.assertEquals(cal, user.getDate()); Assert.assertEquals("read elem ", 4328, user.getZip()); Assert.assertEquals("read elem ", "New York", user.getTown()); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetHeaderNoCheck() throws IOException { assertEquals(4, abstractReader.getHeader(false).length); assertEquals(4, abstractReader.getHeader(false).length); assertEquals(4, abstractReader.getHeader(false).length); assertNull(abstractReader.getHeader(false)); // should be EOF }
#vulnerable code @Test public void testGetHeaderNoCheck() throws IOException { assertEquals(4, abstractReader.getCsvHeader(false).length); assertEquals(4, abstractReader.getCsvHeader(false).length); assertEquals(4, abstractReader.getCsvHeader(false).length); assertNull(abstractReader.getCsvHeader(false)); // should be EOF } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConstructor2() { NullInputException e = new NullInputException(MSG, PROCESSOR, THROWABLE); assertEquals(MSG, e.getMessage()); assertEquals(PROCESSOR, e.getOffendingProcessor()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg, processor and throwable e = new NullInputException(null, (CellProcessor) null, (Throwable) null); assertNull(e.getMessage()); assertNull(e.getOffendingProcessor()); assertNull(e.getCause()); e.printStackTrace(); }
#vulnerable code @Test public void testConstructor2() { NullInputException e = new NullInputException(MSG, PROCESSOR, THROWABLE); assertEquals(CONCATENATED_MSG, e.getMessage()); assertEquals(PROCESSOR, e.getOffendingProcessor()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg, processor and throwable e = new NullInputException(null, (CellProcessor) null, (Throwable) null); assertNull(e.getMessage()); assertNull(e.getOffendingProcessor()); assertNull(e.getCause()); e.printStackTrace(); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void should_escape() { final MockWriter absWriter = new MockWriter(new StringWriter(), CsvPreference.EXCEL_PREFERENCE); assertThat(columnsToWrite.length, is(expectedReadResultsFromColumnToWrite.length)); for( int i = 0; i < columnsToWrite.length; i++ ) { Assert.assertEquals(expectedReadResultsFromColumnToWrite[i], absWriter.escapeString(columnsToWrite[i])); // assertThat(absWriter.escapeString(columnsToWrite[i]), is(expectedOutput[i])); } }
#vulnerable code @Test public void should_escape() { final TestClass absWriter = new TestClass(new StringWriter(), CsvPreference.EXCEL_PREFERENCE); assertThat(columnsToWrite.length, is(expectedReadResultsFromColumnToWrite.length)); for( int i = 0; i < columnsToWrite.length; i++ ) { Assert.assertEquals(expectedReadResultsFromColumnToWrite[i], absWriter.escapeString(columnsToWrite[i])); // assertThat(absWriter.escapeString(columnsToWrite[i]), is(expectedOutput[i])); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConstuctor5(){ SuperCSVException e = new SuperCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); assertEquals(MSG, e.getMessage()); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg, context and throwable e = new SuperCSVException(null, (CSVContext) null, (Throwable) null); assertNull(e.getMessage()); assertNull(e.getCsvContext()); assertNull(e.getCause()); e.printStackTrace(); }
#vulnerable code @Test public void testConstuctor5(){ SuperCSVException e = new SuperCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); assertEquals(CONCATENATED_MSG, e.getMessage()); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg, context and throwable e = new SuperCSVException(null, (CSVContext) null, (Throwable) null); assertNull(e.getMessage()); assertNull(e.getCsvContext()); assertNull(e.getCause()); e.printStackTrace(); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConstructor2(){ SuperCSVReflectionException e = new SuperCSVReflectionException(MSG, THROWABLE); assertEquals(MSG, e.getMessage()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg e = new SuperCSVReflectionException(null, null); assertNull(e.getMessage()); assertNull(e.getCause()); e.printStackTrace(); }
#vulnerable code @Test public void testConstructor2(){ SuperCSVReflectionException e = new SuperCSVReflectionException(MSG, THROWABLE); assertEquals(CONCATENATED_MSG, e.getMessage()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg e = new SuperCSVReflectionException(null, null); assertNull(e.getMessage()); assertNull(e.getCause()); e.printStackTrace(); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConstuctor3(){ SuperCSVException e = new SuperCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); assertEquals(MSG, e.getMessage()); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg, context and throwable e = new SuperCSVException(null, (CSVContext) null, (Throwable) null); assertNull(e.getMessage()); assertNull(e.getCsvContext()); assertNull(e.getCause()); e.printStackTrace(); }
#vulnerable code @Test public void testConstuctor3(){ SuperCSVException e = new SuperCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); assertEquals(CONCATENATED_MSG, e.getMessage()); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg, context and throwable e = new SuperCSVException(null, (CSVContext) null, (Throwable) null); assertNull(e.getMessage()); assertNull(e.getCsvContext()); assertNull(e.getCause()); e.printStackTrace(); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConstructor1() { ClassCastInputCSVException e = new ClassCastInputCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); assertEquals(MSG, e.getMessage()); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg, context and throwable e = new ClassCastInputCSVException(null, (CSVContext) null, (Throwable) null); assertNull(e.getMessage()); assertNull(e.getCsvContext()); assertNull(e.getCause()); e.printStackTrace(); }
#vulnerable code @Test public void testConstructor1(){ ClassCastInputCSVException e = new ClassCastInputCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); assertEquals(CONCATENATED_MSG, e.getMessage()); assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // test with null msg, context and throwable e = new ClassCastInputCSVException(null, (CSVContext) null, (Throwable) null); assertNull(e.getMessage()); assertNull(e.getCsvContext()); assertNull(e.getCause()); e.printStackTrace(); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String getConversationId() { return null; }
#vulnerable code @Override public String getConversationId() { return getViewCache().getCurrentConversationId(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void moduleThrowingInitExceptionShouldBeMarkedForReinitializationOnlyTheFirstTime() throws InterruptedException { final TxDrivenModule mockModule = createMockModule(); when(mockModule.getConfiguration()).thenReturn(NullTxDrivenModuleConfiguration.getInstance()); doThrow(new NeedsInitializationException()).when(mockModule).beforeCommit(any(ImprovedTransactionData.class)); GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database); runtime.registerModule(mockModule); runtime.start(); try (Transaction tx = database.beginTx()) { database.createNode(); tx.success(); } long firstFailureTimestamp; try (Transaction tx = database.beginTx()) { firstFailureTimestamp = repository.getModuleMetadata(mockModule).timestamp(); } Thread.sleep(1); try (Transaction tx = database.beginTx()) { database.createNode(); tx.success(); } long secondFailureTimestamp; try (Transaction tx = database.beginTx()) { secondFailureTimestamp = repository.getModuleMetadata(mockModule).timestamp(); } assertEquals(firstFailureTimestamp, secondFailureTimestamp); }
#vulnerable code @Test public void moduleThrowingInitExceptionShouldBeMarkedForReinitializationOnlyTheFirstTime() throws InterruptedException { final TxDrivenModule mockModule = createMockModule(); when(mockModule.getConfiguration()).thenReturn(NullTxDrivenModuleConfiguration.getInstance()); doThrow(new NeedsInitializationException()).when(mockModule).beforeCommit(any(ImprovedTransactionData.class)); GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database); runtime.registerModule(mockModule); runtime.start(); try (Transaction tx = database.beginTx()) { database.createNode(); tx.success(); } long firstFailureTimestamp; try (Transaction tx = database.beginTx()) { firstFailureTimestamp = Long.valueOf(getRuntimeRoot().getProperty(GA_PREFIX + RUNTIME + "_" + MOCK).toString().replaceFirst(FORCE_INITIALIZATION, "")); } Thread.sleep(1); try (Transaction tx = database.beginTx()) { database.createNode(); tx.success(); } long secondFailureTimestamp; try (Transaction tx = database.beginTx()) { secondFailureTimestamp = Long.valueOf(getRuntimeRoot().getProperty(GA_PREFIX + RUNTIME + "_" + MOCK).toString().replaceFirst(FORCE_INITIALIZATION, "")); } assertEquals(firstFailureTimestamp, secondFailureTimestamp); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void startJetty() { rootContext = createRootApplicationContext(); HandlerList handlerList = findHandlerList(); SessionManager sessionManager = findSessionManager(handlerList); addHandlers(handlerList, sessionManager, rootContext); addFilters(); super.startJetty(); }
#vulnerable code @Override protected void startJetty() { ApplicationContext rootContext = createRootApplicationContext(); HandlerList handlerList = findHandlerList(); SessionManager sessionManager = findSessionManager(handlerList); addHandlers(handlerList, sessionManager, rootContext); addFilters(); super.startJetty(); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static <K, V> V getSingleValue(Map<K, V> map) { return getSingleOrNull(map.entrySet()).getValue(); }
#vulnerable code private static <K, V> V getSingleValue(Map<K, V> map) { return getSingle(map.entrySet()).getValue(); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void verifyRandomWalkerModuleCorrectlyGeneratesReasonablePageRankMeasurements() throws InterruptedException { // firstly, generate a graph final int numberOfNodes = 50; GraphGenerator graphGenerator = new Neo4jGraphGenerator(database); LOG.info("Generating Barabasi-Albert social network graph with {} nodes...", numberOfNodes); graphGenerator.generateGraph(new BasicGeneratorConfiguration(numberOfNodes, new BarabasiAlbertGraphRelationshipGenerator( new BarabasiAlbertConfig(numberOfNodes, 2)), SocialNetworkNodeCreator.getInstance(), SocialNetworkRelationshipCreator .getInstance())); LOG.info("Computing adjacency matrix for graph..."); // secondly, compute the adjacency matrix for this graph NetworkMatrixFactory networkMatrixFactory = new NetworkMatrixFactory(database); try (Transaction tx = database.beginTx()) { LOG.info("Computing page rank based on adjacency matrix..."); // thirdly, compute the page rank of this graph based on the adjacency matrix PageRank pageRank = new PageRank(); NetworkMatrix transitionMatrix = networkMatrixFactory.getTransitionMatrix(); List<RankNodePair> pageRankResult = pageRank.getPageRankPairs(transitionMatrix, 0.85); // Sergei's & Larry's suggestion is to use .85 to become rich;) //LOG.info(pageRankResult.toString()); LOG.info("Applying random graph walker module to page rank graph"); // fourthly, run the rage rank module to compute the random walker's page rank GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database); runtime.registerModule(pageRankModule); runtime.start(); LOG.info("Waiting for module walker to do its work"); TimeUnit.SECONDS.sleep(30); // finally, compare both page rank metrics and verify the module is producing what it should // List<Node> indexMap = networkMatrixFactory.getIndexMap(); LOG.info("The highest PageRank in the network is: " + pageRankResult.get(0).node().getProperty("name").toString()); //LOG.info("Top of the rank map is: {}", indexMap.get(0).getProperty("name")); ArrayList<RankNodePair> neoRank = new ArrayList<>(); for (RankNodePair pair : pageRankResult) { Node node = pair.node(); int rank = (int) pair.node().getProperty(RandomWalkerPageRankModule.PAGE_RANK_PROPERTY_KEY); //System.out.printf("%s\t%s\t%s\n", node.getProperty("name"), // "NeoRank: " + rank, "PageRank: " + pair.rank()); neoRank.add(new RankNodePair(rank, node)); } sort(neoRank, new RankNodePairComparator()); LOG.info("The highest NeoRank in the network is: " + neoRank.get(0).node().getProperty("name").toString()); // Perform an analysis of the results: LOG.info("Analysing results:"); analyseResults(RankNodePair.convertToRankedNodeList(pageRankResult), RankNodePair.convertToRankedNodeList(neoRank)); } }
#vulnerable code @Test public void verifyRandomWalkerModuleCorrectlyGeneratesReasonablePageRankMeasurements() throws InterruptedException { // firstly, generate a graph final int numberOfNodes = 10; GraphGenerator graphGenerator = new Neo4jGraphGenerator(database); LOG.info("Generating Barabasi-Albert social network graph with {} nodes...", numberOfNodes); graphGenerator.generateGraph(new BasicGeneratorConfiguration(numberOfNodes, new BarabasiAlbertGraphRelationshipGenerator( new BarabasiAlbertConfig(numberOfNodes, 5)), SocialNetworkNodeCreator.getInstance(), SocialNetworkRelationshipCreator .getInstance())); LOG.info("Computing adjacency matrix for graph..."); // secondly, compute the adjacency matrix for this graph NetworkMatrixFactory networkMatrixFactory = new NetworkMatrixFactory(database); try (Transaction tx = database.beginTx()) { LOG.info("Computing page rank based on adjacency matrix..."); // thirdly, compute the page rank of this graph based on the adjacency matrix PageRank pageRank = new PageRank(); NetworkMatrix transitionMatrix = networkMatrixFactory.getTransitionMatrix(); List<RankNodePair> pageRankResult = pageRank.getPageRankPairs(transitionMatrix, 0.85); // Sergei's & Larry's suggestion is to use .85 to become rich;) LOG.info(pageRankResult.toString()); LOG.info("Applying random graph walker module to page rank graph"); // fourthly, run the rage rank module to compute the random walker's page rank GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database); runtime.registerModule(pageRankModule); runtime.start(); LOG.info("Waiting for module walker to do its work"); TimeUnit.SECONDS.sleep(30); // finally, compare both page rank metrics and verify the module is producing what it should // XXX: I understand this is WIP, but why does this return a list if it's called get..Map? // YYY: I call it a Map, since it is effectivelly the inverse of the Node, Integer hashMap from the NetworkMatrixFactory // and it is used only to map the indices from of the pagerank values back to the Nodes. Quite clumsy, on todo list ;) // List<Node> indexMap = networkMatrixFactory.getIndexMap(); LOG.info("The highest PageRank in the network is: " + pageRankResult.get(0).node().getProperty("name").toString()); //LOG.info("Top of the rank map is: {}", indexMap.get(0).getProperty("name")); int topRank = 0; Node topNode = null; for (RankNodePair pair : pageRankResult) { System.out.printf("%s\t%s\t%s\n", pair.node().getProperty("name"), "NeoRank: " + pair.node().getProperty(RandomWalkerPageRankModule.PAGE_RANK_PROPERTY_KEY).toString(), "PageRank: " + pair.rank()); int rank = (int) pair.node().getProperty(RandomWalkerPageRankModule.PAGE_RANK_PROPERTY_KEY); if (rank > topRank) { topRank = rank; topNode = pair.node(); } } LOG.info("The highest NeoRank in the network is: " + topNode.getProperty("name").toString()); } } #location 61 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void startJetty() { rootContext = createRootApplicationContext(); HandlerList handlerList = findHandlerList(); SessionManager sessionManager = findSessionManager(handlerList); addHandlers(handlerList, sessionManager, rootContext); addFilters(); super.startJetty(); }
#vulnerable code @Override protected void startJetty() { ApplicationContext rootContext = createRootApplicationContext(); HandlerList handlerList = findHandlerList(); SessionManager sessionManager = findSessionManager(handlerList); addHandlers(handlerList, sessionManager, rootContext); addFilters(); super.startJetty(); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void moduleThrowingInitExceptionShouldBeMarkedForReinitialization() { final TxDrivenModule mockModule = createMockModule(); when(mockModule.getConfiguration()).thenReturn(NullTxDrivenModuleConfiguration.getInstance()); Mockito.doThrow(new NeedsInitializationException()).when(mockModule).beforeCommit(any(ImprovedTransactionData.class)); GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database); runtime.registerModule(mockModule); runtime.start(); try (Transaction tx = database.beginTx()) { TxDrivenModuleMetadata moduleMetadata = repository.getModuleMetadata(mockModule); assertEquals(NullTxDrivenModuleConfiguration.getInstance(), moduleMetadata.getConfig()); assertFalse(moduleMetadata.needsInitialization()); assertEquals(-1, moduleMetadata.timestamp()); } try (Transaction tx = database.beginTx()) { database.createNode(); tx.success(); } try (Transaction tx = database.beginTx()) { TxDrivenModuleMetadata moduleMetadata = repository.getModuleMetadata(mockModule); assertEquals(NullTxDrivenModuleConfiguration.getInstance(), moduleMetadata.getConfig()); assertTrue(moduleMetadata.needsInitialization()); assertTrue(moduleMetadata.timestamp() > System.currentTimeMillis() - 1000); } }
#vulnerable code @Test public void moduleThrowingInitExceptionShouldBeMarkedForReinitialization() { final TxDrivenModule mockModule = createMockModule(); when(mockModule.getConfiguration()).thenReturn(NullTxDrivenModuleConfiguration.getInstance()); Mockito.doThrow(new NeedsInitializationException()).when(mockModule).beforeCommit(any(ImprovedTransactionData.class)); GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database); runtime.registerModule(mockModule); runtime.start(); try (Transaction tx = database.beginTx()) { assertTrue(getRuntimeRoot().getProperty(GA_PREFIX + RUNTIME + "_" + MOCK).toString().startsWith(CONFIG)); tx.success(); } try (Transaction tx = database.beginTx()) { database.createNode(); tx.success(); } try (Transaction tx = database.beginTx()) { assertTrue(getRuntimeRoot().getProperty(GA_PREFIX + RUNTIME + "_" + MOCK).toString().startsWith(FORCE_INITIALIZATION)); tx.success(); } } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void load(InputStream input) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); for (;;) { String line = reader.readLine(); if (line == null) { break; } line = line.trim(); if (line.isEmpty()) { continue; } putFromLine(line); } }
#vulnerable code public void load(InputStream input) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(input)); for (;;) { String line = reader.readLine(); if (line == null) { break; } line = line.trim(); if (line.isEmpty()) { continue; } putFromLine(line); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void javaUtilLogging() { String tainted = req.getParameter("test"); String safe = "safe"; Logger logger = Logger.getLogger(Logging.class.getName()); logger.setLevel(Level.ALL); ConsoleHandler handler = new ConsoleHandler(); handler.setLevel(Level.ALL); logger.addHandler(handler); logger.config(tainted); logger.entering(tainted, safe); logger.entering("safe", safe, tainted); logger.entering(safe, "safe", new String[]{tainted}); logger.exiting(safe, tainted); logger.exiting(safe, "safe", tainted); logger.fine(tainted); logger.finer(tainted.trim()); logger.finest(tainted); logger.info(tainted); logger.log(Level.INFO, tainted); logger.log(Level.INFO, tainted, safe); logger.log(Level.INFO, "safe", new String[]{tainted}); logger.log(Level.INFO, tainted, new Exception()); logger.logp(Level.INFO, tainted, safe, "safe"); logger.logp(Level.INFO, safe, "safe", tainted, safe); logger.logp(Level.INFO, "safe", safe.toLowerCase(), safe, new String[]{tainted}); logger.logp(Level.INFO, tainted, safe, safe, new Exception()); logger.logp(Level.INFO, tainted, "safe", (Supplier<String>) null); logger.logp(Level.INFO, "safe", tainted, new Exception(), (Supplier<String>) null); logger.logrb(Level.INFO, safe, safe, (ResourceBundle) null, "safe", tainted); logger.logrb(Level.INFO, tainted, safe, (ResourceBundle) null, safe, new Exception()); logger.logrb(Level.INFO, tainted, safe, "bundle", safe); logger.logrb(Level.INFO, safe, tainted, "bundle", safe, safe); logger.logrb(Level.INFO, tainted, "safe", "bundle", safe, new String[]{safe}); logger.logrb(Level.INFO, safe, safe, "bundle", tainted, new Exception()); logger.severe(tainted + "safe" + safe); logger.throwing("safe", tainted, new Exception()); logger.warning(tainted); // these should not be reported logger.fine(safe); logger.log(Level.INFO, "safe".toUpperCase(), safe + safe); logger.logp(Level.INFO, safe, safe, safe, new String[]{safe}); logger.logrb(Level.INFO, safe, safe, tainted + "bundle", safe); // bundle name can be tainted logger.throwing(safe, safe, new Exception()); }
#vulnerable code public void javaUtilLogging() { String tainted = System.getProperty(""); String safe = "safe"; Logger logger = Logger.getLogger(Logging.class.getName()); logger.setLevel(Level.ALL); ConsoleHandler handler = new ConsoleHandler(); handler.setLevel(Level.ALL); logger.addHandler(handler); logger.config(tainted); logger.entering(tainted, safe); logger.entering("safe", safe, tainted); logger.entering(safe, "safe", new String[]{tainted}); logger.exiting(safe, tainted); logger.exiting(safe, "safe", tainted); logger.fine(tainted); logger.finer(tainted.trim()); logger.finest(tainted); logger.info(tainted); logger.log(Level.INFO, tainted); logger.log(Level.INFO, tainted, safe); logger.log(Level.INFO, "safe", new String[]{tainted}); logger.log(Level.INFO, tainted, new Exception()); logger.logp(Level.INFO, tainted, safe, "safe"); logger.logp(Level.INFO, safe, "safe", tainted, safe); logger.logp(Level.INFO, "safe", safe.toLowerCase(), safe, new String[]{tainted}); logger.logp(Level.INFO, tainted, safe, safe, new Exception()); logger.logp(Level.INFO, tainted, "safe", (Supplier<String>) null); logger.logp(Level.INFO, "safe", tainted, new Exception(), (Supplier<String>) null); logger.logrb(Level.INFO, safe, safe, (ResourceBundle) null, "safe", tainted); logger.logrb(Level.INFO, tainted, safe, (ResourceBundle) null, safe, new Exception()); logger.logrb(Level.INFO, tainted, safe, "bundle", safe); logger.logrb(Level.INFO, safe, tainted, "bundle", safe, safe); logger.logrb(Level.INFO, tainted, "safe", "bundle", safe, new String[]{safe}); logger.logrb(Level.INFO, safe, safe, "bundle", tainted, new Exception()); logger.severe(tainted + "safe" + safe); logger.throwing("safe", tainted, new Exception()); logger.warning(tainted); // these should not be reported logger.fine(safe); logger.log(Level.INFO, "safe".toUpperCase(), safe + safe); logger.logp(Level.INFO, safe, safe, safe, new String[]{safe}); logger.logrb(Level.INFO, safe, safe, tainted + "bundle", safe); // bundle name can be tainted logger.throwing(safe, safe, new Exception()); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private byte[] buildFakePluginJar() throws IOException, URISyntaxException { ClassLoader cl = getClass().getClassLoader(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); JarOutputStream jar = new JarOutputStream(buffer); final URL metadata = cl.getResource("metadata"); if (metadata != null) { final File dir = new File(metadata.toURI()); //Add files to the jar stream addFilesToStream(cl, jar, dir, ""); } jar.finish(); jar.close(); return buffer.toByteArray(); }
#vulnerable code private byte[] buildFakePluginJar() throws IOException { ClassLoader cl = getClass().getClassLoader(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); JarOutputStream jar = new JarOutputStream(buffer); //Add files to the jar stream for (String resource : Arrays.asList("findbugs.xml", "messages.xml", "META-INF/MANIFEST.MF")) { jar.putNextEntry(new ZipEntry(resource)); jar.write(IOUtils.toByteArray(cl.getResourceAsStream("metadata/" + resource))); } jar.finish(); return buffer.toByteArray(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void visitInvoke(InvokeInstruction obj) { assert obj != null; TaintMethodSummary methodSummary = getMethodSummary(obj); Taint taint = getMethodTaint(methodSummary); assert taint != null; if (taint.isUnknown()) { taint.addLocation(getTaintLocation(), false); } taintMutableArguments(methodSummary, obj); transferTaintToMutables(methodSummary, taint); // adds variable index to taint too modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), new Taint(taint)); }
#vulnerable code private void visitInvoke(InvokeInstruction obj) { assert obj != null; TaintMethodSummary methodSummary = getMethodSummary(obj); Taint taint = getMethodTaint(methodSummary); assert taint != null; if (taint.isUnknown()) { taint.addTaintLocation(getTaintLocation(), false); } taintMutableArguments(methodSummary, obj); transferTaintToMutables(methodSummary, taint); // adds variable index to taint too modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), new Taint(taint)); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void visitInvoke(InvokeInstruction obj) { assert obj != null; try { TaintMethodConfig methodConfig = getMethodConfig(obj); Taint taint = getMethodTaint(methodConfig); assert taint != null; if (FindSecBugsGlobalConfig.getInstance().isDebugTaintState()) { taint.setDebugInfo(obj.getMethodName(cpg) + "()"); //TODO: Deprecated debug info } taint.addSource(new UnknownSource(UnknownSourceType.RETURN,taint.getState()).setSignatureMethod(obj.getClassName(cpg).replace(".","/")+"."+obj.getMethodName(cpg)+obj.getSignature(cpg))); if (taint.isUnknown()) { taint.addLocation(getTaintLocation(), false); } taintMutableArguments(methodConfig, obj); transferTaintToMutables(methodConfig, taint); // adds variable index to taint too Taint taintCopy = new Taint(taint); // return type is not always the instance type taintCopy.setRealInstanceClass(methodConfig != null && methodConfig.getOutputTaint() != null ? methodConfig.getOutputTaint().getRealInstanceClass() : null); TaintFrame tf = getFrame(); int stackDepth = tf.getStackDepth(); int nbParam = getNumWordsConsumed(obj); List<Taint> parameters = new ArrayList<>(nbParam); for(int i=0;i<Math.min(stackDepth,nbParam);i++) { parameters.add(new Taint(tf.getStackValue(i))); } modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), taintCopy); for(TaintFrameAdditionalVisitor visitor : visitors) { try { visitor.visitInvoke(obj, methodGen, getFrame() , parameters, cpg); } catch (Throwable e) { LOG.log(Level.SEVERE,"Error while executing "+visitor.getClass().getName(),e); } } } catch (Exception e) { String className = ClassName.toSlashedClassName(obj.getReferenceType(cpg).toString()); String methodName = obj.getMethodName(cpg); String signature = obj.getSignature(cpg); throw new RuntimeException("Unable to call " + className + '.' + methodName + signature, e); } }
#vulnerable code private void visitInvoke(InvokeInstruction obj) { assert obj != null; try { TaintMethodConfig methodConfig = getMethodConfig(obj); ObjectType realInstanceClass = (methodConfig == null) ? null : methodConfig.getOutputTaint().getRealInstanceClass(); Taint taint = getMethodTaint(methodConfig); assert taint != null; if (FindSecBugsGlobalConfig.getInstance().isDebugTaintState()) { taint.setDebugInfo(obj.getMethodName(cpg) + "()"); //TODO: Deprecated debug info } taint.addSource(new UnknownSource(UnknownSourceType.RETURN,taint.getState()).setSignatureMethod(obj.getClassName(cpg).replace(".","/")+"."+obj.getMethodName(cpg)+obj.getSignature(cpg))); if (taint.isUnknown()) { taint.addLocation(getTaintLocation(), false); } taintMutableArguments(methodConfig, obj); transferTaintToMutables(methodConfig, taint); // adds variable index to taint too Taint taintCopy = new Taint(taint); // return type is not always the instance type taintCopy.setRealInstanceClass(realInstanceClass); TaintFrame tf = getFrame(); int stackDepth = tf.getStackDepth(); int nbParam = getNumWordsConsumed(obj); List<Taint> parameters = new ArrayList<>(nbParam); for(int i=0;i<Math.min(stackDepth,nbParam);i++) { parameters.add(new Taint(tf.getStackValue(i))); } modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), taintCopy); for(TaintFrameAdditionalVisitor visitor : visitors) { try { visitor.visitInvoke(obj, methodGen, getFrame() , parameters, cpg); } catch (Throwable e) { LOG.log(Level.SEVERE,"Error while executing "+visitor.getClass().getName(),e); } } } catch (Exception e) { String className = ClassName.toSlashedClassName(obj.getReferenceType(cpg).toString()); String methodName = obj.getMethodName(cpg); String signature = obj.getSignature(cpg); throw new RuntimeException("Unable to call " + className + '.' + methodName + signature, e); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static List<String> loadFileContent(String path) { BufferedReader stream = null; try { InputStream in = TaintAnalysis.class.getClassLoader().getResourceAsStream(path); stream = new BufferedReader(new InputStreamReader(in, "utf-8")); String line; List<String> content = new ArrayList<String>(); while ((line = stream.readLine()) != null) { content.add(line.trim()); } return content; } catch (IOException ex) { assert false : ex.getMessage(); } finally { IO.close(stream); } return new ArrayList<String>(); }
#vulnerable code private static List<String> loadFileContent(String path) { try { InputStream in = TaintAnalysis.class.getClassLoader().getResourceAsStream(path); BufferedReader stream = new BufferedReader(new InputStreamReader(in)); String line; List<String> content = new ArrayList<String>(); while ((line = stream.readLine()) != null) { content.add(line.trim()); } stream.close(); return content; } catch (IOException e) { LOG.log(Level.SEVERE, "Unable to load data from {0}", path); } return new ArrayList<String>(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static List<String> loadFileContent(String path) { try (InputStream in = TaintAnalysis.class.getClassLoader().getResourceAsStream(path); BufferedReader stream = new BufferedReader(new InputStreamReader(in, "utf-8"))) { String line; List<String> content = new ArrayList<String>(); while ((line = stream.readLine()) != null) { content.add(line.trim()); } return content; } catch (IOException ex) { assert false : ex.getMessage(); } return new ArrayList<String>(); }
#vulnerable code private static List<String> loadFileContent(String path) { BufferedReader stream = null; try { InputStream in = TaintAnalysis.class.getClassLoader().getResourceAsStream(path); stream = new BufferedReader(new InputStreamReader(in, "utf-8")); String line; List<String> content = new ArrayList<String>(); while ((line = stream.readLine()) != null) { content.add(line.trim()); } return content; } catch (IOException ex) { assert false : ex.getMessage(); } finally { IO.close(stream); } return new ArrayList<String>(); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private byte[] buildFakePluginJar() throws IOException, URISyntaxException { ClassLoader cl = getClass().getClassLoader(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); JarOutputStream jar = new JarOutputStream(buffer); final URL metadata = cl.getResource("metadata"); if (metadata != null) { final File dir = new File(metadata.toURI()); //Add files to the jar stream addFilesToStream(cl, jar, dir, ""); } jar.finish(); jar.close(); return buffer.toByteArray(); }
#vulnerable code private byte[] buildFakePluginJar() throws IOException { ClassLoader cl = getClass().getClassLoader(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); JarOutputStream jar = new JarOutputStream(buffer); //Add files to the jar stream for (String resource : Arrays.asList("findbugs.xml", "messages.xml", "META-INF/MANIFEST.MF")) { jar.putNextEntry(new ZipEntry(resource)); jar.write(IOUtils.toByteArray(cl.getResourceAsStream("metadata/" + resource))); } jar.finish(); return buffer.toByteArray(); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws IOException { Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() { @Nullable @Override public Integer apply(@Nullable LookupResult input) { return input.weight(); } }; DnsSrvResolver resolver = DnsSrvResolvers.newBuilder() .cachingLookups(true) .retainingDataOnFailures(true) .dnsLookupTimeoutMillis(1000) .build(); DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver) .polling(1, TimeUnit.SECONDS) .build(); boolean quit = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (!quit) { System.out.print("Enter a SRV name (empty to quit): "); String line = in.readLine(); if (line == null || line.isEmpty()) { quit = true; } else { try { ChangeNotifier<LookupResult> notifier = watcher.watch(line); notifier.setListener(new ChangeListener(line), false); } catch (DnsException e) { e.printStackTrace(System.out); } } } }
#vulnerable code public static void main(String[] args) throws IOException { Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() { @Nullable @Override public Integer apply(@Nullable LookupResult input) { return input.weight(); } }; DnsSrvResolver resolver = DnsSrvResolvers.newBuilder() .cachingLookups(true) .retainingDataOnFailures(true) .dnsLookupTimeoutMillis(1000) .build(); DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver) .polling(1, TimeUnit.SECONDS) .build(); boolean quit = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (!quit) { System.out.print("Enter a SRV name (empty to quit): "); String line = in.readLine(); if (line == null || line.isEmpty()) { quit = true; } else { try { ChangeNotifier<LookupResult> notifier = watcher.watch(line); notifier.setListener(new ChangeListener(line), false); } catch (DnsException e) { e.printStackTrace(System.out); } } } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Set<T> current() { return records; }
#vulnerable code @Override public Set<T> current() { ImmutableSet.Builder<T> records = ImmutableSet.builder(); for (final ChangeNotifier<T> changeNotifier : changeNotifiers) { records.addAll(changeNotifier.current()); } return records.build(); } #location 2 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { DnsSrvResolver resolver = DnsSrvResolvers.newBuilder() .cachingLookups(true) .retainingDataOnFailures(true) .metered(REPORTER) .dnsLookupTimeoutMillis(1000) .build(); boolean quit = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (!quit) { System.out.print("Enter a SRV name: "); String line = in.readLine(); if (line == null || line.isEmpty()) { quit = true; } else { try { List<HostAndPort> nodes = resolver.resolve(line); for (HostAndPort node : nodes) { System.out.println(node); } } catch (DnsException e) { e.printStackTrace(System.out); } } } }
#vulnerable code public static void main(String[] args) throws ExecutionException, InterruptedException, IOException { DnsSrvResolver resolver = DnsSrvResolvers.newBuilder() .cachingLookups(true) .retainingDataOnFailures(true) .metered(REPORTER) .dnsLookupTimeoutMillis(1000) .build(); boolean quit = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (!quit) { System.out.print("Enter a SRV name: "); String line = in.readLine(); if (line == null) { quit = true; } else { try { List<HostAndPort> nodes = resolver.resolve(line); for (HostAndPort node : nodes) { System.out.println(node); } } catch (DnsException e) { e.printStackTrace(System.out); } } } } #location 24 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws IOException { Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() { @Nullable @Override public Integer apply(@Nullable LookupResult input) { return input.weight(); } }; DnsSrvResolver resolver = DnsSrvResolvers.newBuilder() .cachingLookups(true) .retainingDataOnFailures(true) .dnsLookupTimeoutMillis(1000) .build(); DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver) .polling(1, TimeUnit.SECONDS) .build(); boolean quit = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (!quit) { System.out.print("Enter a SRV name (empty to quit): "); String line = in.readLine(); if (line == null || line.isEmpty()) { quit = true; } else { try { ChangeNotifier<LookupResult> notifier = watcher.watch(line); notifier.setListener(new ChangeListener(line), false); } catch (DnsException e) { e.printStackTrace(System.out); } } } }
#vulnerable code public static void main(String[] args) throws IOException { Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() { @Nullable @Override public Integer apply(@Nullable LookupResult input) { return input.weight(); } }; DnsSrvResolver resolver = DnsSrvResolvers.newBuilder() .cachingLookups(true) .retainingDataOnFailures(true) .dnsLookupTimeoutMillis(1000) .build(); DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver) .polling(1, TimeUnit.SECONDS) .build(); boolean quit = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (!quit) { System.out.print("Enter a SRV name (empty to quit): "); String line = in.readLine(); if (line == null || line.isEmpty()) { quit = true; } else { try { ChangeNotifier<LookupResult> notifier = watcher.watch(line); notifier.setListener(new ChangeListener(line), false); } catch (DnsException e) { e.printStackTrace(System.out); } } } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Set<T> aggregateSet() { if (areAllInitial(changeNotifiers)) { return ChangeNotifiers.initialEmptyDataInstance(); } ImmutableSet.Builder<T> records = ImmutableSet.builder(); for (final ChangeNotifier<T> changeNotifier : changeNotifiers) { records.addAll(changeNotifier.current()); } return records.build(); }
#vulnerable code private Set<T> aggregateSet() { ImmutableSet.Builder<T> records = ImmutableSet.builder(); for (final ChangeNotifier<T> changeNotifier : changeNotifiers) { records.addAll(changeNotifier.current()); } return records.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws IOException { Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() { @Nullable @Override public Integer apply(@Nullable LookupResult input) { return input.weight(); } }; DnsSrvResolver resolver = DnsSrvResolvers.newBuilder() .cachingLookups(true) .retainingDataOnFailures(true) .dnsLookupTimeoutMillis(1000) .build(); DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver) .polling(1, TimeUnit.SECONDS) .build(); boolean quit = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (!quit) { System.out.print("Enter a SRV name (empty to quit): "); String line = in.readLine(); if (line == null || line.isEmpty()) { quit = true; } else { try { ChangeNotifier<LookupResult> notifier = watcher.watch(line); notifier.setListener(new ChangeListener(line), false); } catch (DnsException e) { e.printStackTrace(System.out); } } } }
#vulnerable code public static void main(String[] args) throws IOException { DnsSrvResolver resolver = DnsSrvResolvers.newBuilder() .cachingLookups(true) .retainingDataOnFailures(true) .dnsLookupTimeoutMillis(1000) .build(); PollingDnsSrvResolver<String> poller = DnsSrvResolvers.pollingResolver(resolver, new Function<LookupResult, String>() { @Nullable @Override public String apply(@Nullable LookupResult input) { return input.toString() + System.currentTimeMillis() / 5000; } } ); boolean quit = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (!quit) { System.out.print("Enter a SRV name (empty to quit): "); String line = in.readLine(); if (line == null || line.isEmpty()) { quit = true; } else { try { poller.poll(line, 1, TimeUnit.SECONDS) .setListener(new EndpointListener(line), false); } catch (DnsException e) { e.printStackTrace(System.out); } } } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean putConfig(String dataId, String content, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUT, timeoutMills); etcdConfigExecutor.execute(() -> complete(getClient().getKVClient().put(ByteSequence.from(dataId, UTF_8), ByteSequence.from(content, UTF_8)), configFuture)); return (Boolean) configFuture.get(); }
#vulnerable code @Override public boolean putConfig(String dataId, String content, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUT, timeoutMills); etcdConfigExecutor.execute(() -> { complete(getClient().getKVClient().put(ByteSequence.from(dataId, UTF_8), ByteSequence.from(content, UTF_8)), configFuture); }); return (Boolean) configFuture.get(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public BranchStatus branchRollback(BranchType branchType, String xid, long branchId, String resourceId, String applicationData) throws TransactionException { TCCResource tccResource = (TCCResource) tccResourceCache.get(resourceId); if (tccResource == null) { throw new ShouldNeverHappenException("TCC resource is not exist, resourceId:" + resourceId); } Object targetTCCBean = tccResource.getTargetBean(); Method rollbackMethod = tccResource.getRollbackMethod(); if (targetTCCBean == null || rollbackMethod == null) { throw new ShouldNeverHappenException("TCC resource is not available, resourceId:" + resourceId); } try { boolean result = false; //BusinessActionContext BusinessActionContext businessActionContext = getBusinessActionContext(xid, branchId, resourceId, applicationData); Object ret = rollbackMethod.invoke(targetTCCBean, businessActionContext); LOGGER.info("TCC resource rollback result :" + ret + ", xid:" + xid + ", branchId:" + branchId + ", resourceId:" + resourceId); if (ret != null) { if (ret instanceof TwoPhaseResult) { result = ((TwoPhaseResult) ret).isSuccess(); } else { result = (boolean) ret; } } return result ? BranchStatus.PhaseTwo_Rollbacked : BranchStatus.PhaseTwo_RollbackFailed_Retryable; } catch (Throwable t) { String msg = String.format("rollback TCC resource error, resourceId: %s, xid: %s.", resourceId, xid); LOGGER.error(msg, t); throw new FrameworkException(t, msg); } }
#vulnerable code @Override public BranchStatus branchRollback(BranchType branchType, String xid, long branchId, String resourceId, String applicationData) throws TransactionException { TCCResource tccResource = (TCCResource) tccResourceCache.get(resourceId); if (tccResource == null) { throw new ShouldNeverHappenException("TCC resource is not exist, resourceId:" + resourceId); } Object targetTCCBean = tccResource.getTargetBean(); Method rollbackMethod = tccResource.getRollbackMethod(); if (targetTCCBean == null || rollbackMethod == null) { throw new ShouldNeverHappenException("TCC resource is not available, resourceId:" + resourceId); } try { boolean result = false; //BusinessActionContext BusinessActionContext businessActionContext = getBusinessActionContext(xid, branchId, resourceId, applicationData); Object ret = rollbackMethod.invoke(targetTCCBean, businessActionContext); LOGGER.info("TCC resource rollback result :" + ret + ", xid:" + xid + ", branchId:" + branchId + ", resourceId:" + resourceId); if (ret != null && ret instanceof TwoPhaseResult) { result = ((TwoPhaseResult) ret).isSuccess(); } else { result = (boolean) ret; } return result ? BranchStatus.PhaseTwo_Rollbacked : BranchStatus.PhaseTwo_RollbackFailed_Retryable; } catch (Throwable t) { String msg = String.format("rollback TCC resource error, resourceId: %s, xid: %s.", resourceId, xid); LOGGER.error(msg, t); throw new FrameworkException(t, msg); } } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static RegistryService getInstance() { RegistryType registryType = null; try { registryType = RegistryType.getType( ConfigurationFactory.FILE_INSTANCE.getConfig( ConfigurationKeys.FILE_ROOT_REGISTRY + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR + ConfigurationKeys.FILE_ROOT_TYPE)); } catch (Exception exx) { LOGGER.error(exx.getMessage()); } RegistryService registryService; switch (registryType) { case Nacos: registryService = NacosRegistryServiceImpl.getInstance(); break; case File: registryService = FileRegistryServiceImpl.getInstance(); break; default: throw new NotSupportYetException("not support register type:" + registryType); } return registryService; }
#vulnerable code public static RegistryService getInstance() { ConfigType configType = null; try { configType = ConfigType.getType( ConfigurationFactory.FILE_INSTANCE.getConfig( ConfigurationKeys.FILE_ROOT_REGISTRY + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR + ConfigurationKeys.FILE_ROOT_TYPE)); } catch (Exception exx) { LOGGER.error(exx.getMessage()); } RegistryService registryService; switch (configType) { case Nacos: registryService = NacosRegistryServiceImpl.getInstance(); break; case File: registryService = FileRegistryServiceImpl.getInstance(); break; default: throw new NotSupportYetException("not support register type:" + configType); } return registryService; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean removeConfig(String dataId, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigOperation.REMOVE, timeoutMills); configOperateExecutor.submit(new ConfigOperateRunnable(configFuture)); return (Boolean)configFuture.get(); }
#vulnerable code @Override public boolean removeConfig(String dataId, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigOperation.REMOVE, timeoutMills); configOperateExecutor.submit(new ConfigOperateRunnable(configFuture)); return (Boolean)configFuture.get(timeoutMills, TimeUnit.MILLISECONDS); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static <T, S extends Statement> T execute(SQLRecognizer sqlRecognizer, StatementProxy<S> statementProxy, StatementCallback<T, S> statementCallback, Object... args) throws SQLException { if (!RootContext.inGlobalTransaction()) { // Just work as original statement return statementCallback.execute(statementProxy.getTargetStatement(), args); } if (sqlRecognizer == null) { sqlRecognizer = SQLVisitorFactory.get( statementProxy.getTargetSQL(), statementProxy.getConnectionProxy().getDbType()); } Executor<T> executor = null; if (sqlRecognizer == null) { executor = new PlainExecutor<T, S>(statementProxy, statementCallback); } else { switch (sqlRecognizer.getSQLType()) { case INSERT: executor = new InsertExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer); break; case UPDATE: executor = new UpdateExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer); break; case DELETE: executor = new DeleteExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer); break; case SELECT_FOR_UPDATE: executor = new SelectForUpdateExecutor(statementProxy, statementCallback, sqlRecognizer); break; default: executor = new PlainExecutor<T, S>(statementProxy, statementCallback); break; } } T rs = null; try { rs = executor.execute(args); } catch (Throwable ex) { if (ex instanceof SQLException) { throw (SQLException) ex; } else { // Turn everything into SQLException new SQLException(ex); } } return rs; }
#vulnerable code public static <T, S extends Statement> T execute(SQLRecognizer sqlRecognizer, StatementProxy<S> statementProxy, StatementCallback<T, S> statementCallback, Object... args) throws SQLException { if (!RootContext.inGlobalTransaction()) { // Just work as original statement return statementCallback.execute(statementProxy.getTargetStatement(), args); } if (sqlRecognizer == null) { sqlRecognizer = SQLVisitorFactory.get( statementProxy.getTargetSQL(), statementProxy.getConnectionProxy().getDbType()); } Executor<T> executor = null; switch (sqlRecognizer.getSQLType()) { case INSERT: executor = new InsertExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer); break; case UPDATE: executor = new UpdateExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer); break; case DELETE: executor = new DeleteExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer); break; case SELECT_FOR_UPDATE: executor = new SelectForUpdateExecutor(statementProxy, statementCallback, sqlRecognizer); break; default: executor = new PlainExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer); break; } T rs = null; try { rs = executor.execute(args); } catch (Throwable ex) { if (ex instanceof SQLException) { throw (SQLException) ex; } else { // Turn everything into SQLException new SQLException(ex); } } return rs; } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public BranchStatus branchCommit(BranchType branchType, String xid, long branchId, String resourceId, String applicationData) throws TransactionException { TCCResource tccResource = (TCCResource) tccResourceCache.get(resourceId); if(tccResource == null){ throw new ShouldNeverHappenException("TCC resource is not exist, resourceId:" + resourceId); } Object targetTCCBean = tccResource.getTargetBean(); Method commitMethod = tccResource.getCommitMethod(); if(targetTCCBean == null || commitMethod == null){ throw new ShouldNeverHappenException("TCC resource is not available, resourceId:" + resourceId); } try { boolean result = false; //BusinessActionContext BusinessActionContext businessActionContext = getBusinessActionContext(xid, branchId, resourceId, applicationData); Object ret = commitMethod.invoke(targetTCCBean, businessActionContext); LOGGER.info("TCC resource commit result :" + ret + ", xid:" + xid + ", branchId:" + branchId + ", resourceId:" + resourceId); if (ret != null) { if (ret instanceof TwoPhaseResult) { result = ((TwoPhaseResult) ret).isSuccess(); } else { result = (boolean) ret; } } return result ? BranchStatus.PhaseTwo_Committed:BranchStatus.PhaseTwo_CommitFailed_Retryable; }catch (Throwable t){ String msg = String.format("commit TCC resource error, resourceId: %s, xid: %s.", resourceId, xid); LOGGER.error(msg , t); throw new FrameworkException(t, msg); } }
#vulnerable code @Override public BranchStatus branchCommit(BranchType branchType, String xid, long branchId, String resourceId, String applicationData) throws TransactionException { TCCResource tccResource = (TCCResource) tccResourceCache.get(resourceId); if(tccResource == null){ throw new ShouldNeverHappenException("TCC resource is not exist, resourceId:" + resourceId); } Object targetTCCBean = tccResource.getTargetBean(); Method commitMethod = tccResource.getCommitMethod(); if(targetTCCBean == null || commitMethod == null){ throw new ShouldNeverHappenException("TCC resource is not available, resourceId:" + resourceId); } try { boolean result = false; //BusinessActionContext BusinessActionContext businessActionContext = getBusinessActionContext(xid, branchId, resourceId, applicationData); Object ret = commitMethod.invoke(targetTCCBean, businessActionContext); LOGGER.info("TCC resource commit result :" + ret + ", xid:" + xid + ", branchId:" + branchId + ", resourceId:" + resourceId); if(ret != null && ret instanceof TwoPhaseResult){ result = ((TwoPhaseResult)ret).isSuccess(); }else { result = (boolean) ret; } return result ? BranchStatus.PhaseTwo_Committed:BranchStatus.PhaseTwo_CommitFailed_Retryable; }catch (Throwable t){ String msg = String.format("commit TCC resource error, resourceId: %s, xid: %s.", resourceId, xid); LOGGER.error(msg , t); throw new FrameworkException(t, msg); } } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static long generateUUID() { long id = UUID.incrementAndGet(); if (id >= getMaxUUID()) { synchronized (UUID) { if (UUID.get() >= id) { id -= UUID_INTERNAL; UUID.set(id); } } } return id; }
#vulnerable code public static long generateUUID() { long id = UUID.incrementAndGet(); if (id >= UUID_INTERNAL * (serverNodeId + 1)) { synchronized (UUID) { if (UUID.get() >= id) { id -= UUID_INTERNAL; UUID.set(id); } } } return id; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public DataSource generateDataSource() { DruidDataSource ds = new DruidDataSource(); ds.setDriverClassName(getDriverClassName()); ds.setDriverClassLoader(getDriverClassLoader()); ds.setUrl(getUrl()); ds.setUsername(getUser()); ds.setPassword(getPassword()); ds.setInitialSize(getMinConn()); ds.setMaxActive(getMaxConn()); ds.setMinIdle(getMinConn()); ds.setMaxWait(5000); ds.setTimeBetweenEvictionRunsMillis(120000); ds.setMinEvictableIdleTimeMillis(300000); ds.setTestWhileIdle(true); ds.setTestOnBorrow(true); ds.setPoolPreparedStatements(true); ds.setMaxPoolPreparedStatementPerConnectionSize(20); ds.setValidationQuery(getValidationQuery(getDBType())); ds.setDefaultAutoCommit(true); return ds; }
#vulnerable code @Override public DataSource generateDataSource() { DruidDataSource ds = new DruidDataSource(); ds.setDriverClassName(getDriverClassName()); ds.setUrl(getUrl()); ds.setUsername(getUser()); ds.setPassword(getPassword()); ds.setInitialSize(getMinConn()); ds.setMaxActive(getMaxConn()); ds.setMinIdle(getMinConn()); ds.setMaxWait(5000); ds.setTimeBetweenEvictionRunsMillis(120000); ds.setMinEvictableIdleTimeMillis(300000); ds.setTestWhileIdle(true); ds.setTestOnBorrow(true); ds.setPoolPreparedStatements(true); ds.setMaxPoolPreparedStatementPerConnectionSize(20); ds.setValidationQuery(getValidationQuery(getDBType())); ds.setDefaultAutoCommit(true); return ds; } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Configuration getInstance() { ConfigType configType = null; String configTypeName = null; try { configTypeName = FILE_INSTANCE.getConfig(ConfigurationKeys.FILE_ROOT_CONFIG + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR + ConfigurationKeys.FILE_ROOT_TYPE); configType = ConfigType.getType(configTypeName); } catch (Exception exx) { throw new NotSupportYetException("not support register type: " + configTypeName); } Configuration configuration; switch (configType) { case Nacos: try { configuration = new NacosConfiguration(); } catch (NacosException e) { throw new RuntimeException(e); } break; case Apollo: try { configuration = ApolloConfiguration.getInstance(); } catch (ApolloConfigException e) { throw new RuntimeException(e); } break; case File: String pathDataId = ConfigurationKeys.FILE_ROOT_CONFIG + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR + FILE_TYPE + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR + NAME_KEY; String name = FILE_INSTANCE.getConfig(pathDataId); configuration = new FileConfiguration(name); break; default: throw new NotSupportYetException("not support register type:" + configType); } return configuration; }
#vulnerable code public static Configuration getInstance() { ConfigType configType = null; try { configType = ConfigType.getType( FILE_INSTANCE.getConfig(ConfigurationKeys.FILE_ROOT_CONFIG + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR + ConfigurationKeys.FILE_ROOT_TYPE)); } catch (Exception exx) { LOGGER.error(exx.getMessage()); } Configuration configuration; switch (configType) { case Nacos: try { configuration = new NacosConfiguration(); } catch (NacosException e) { throw new RuntimeException(e); } break; case Apollo: try { configuration = ApolloConfiguration.getInstance(); } catch (ApolloConfigException e) { throw new RuntimeException(e); } break; case File: String pathDataId = ConfigurationKeys.FILE_ROOT_CONFIG + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR + FILE_TYPE + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR + NAME_KEY; String name = FILE_INSTANCE.getConfig(pathDataId); configuration = new FileConfiguration(name); break; default: throw new NotSupportYetException("not support register type:" + configType); } return configuration; } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRestoredFromFileRollbackRetry() throws Exception { SessionHolder.init("file"); GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000); globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager()); globalSession.begin(); BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID, "ta:1", "xxx"); branchSession1.lock(); globalSession.addBranch(branchSession1); LockManager lockManager = LockManagerFactory.get(); Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1")); globalSession.changeStatus(GlobalStatus.Rollbacking); globalSession.changeBranchStatus(branchSession1, BranchStatus.PhaseTwo_RollbackFailed_Retryable); globalSession.changeStatus(GlobalStatus.RollbackRetrying); lockManager.cleanAllLocks(); Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1")); // Re-init SessionHolder: restore sessions from file SessionHolder.init("file"); long tid = globalSession.getTransactionId(); GlobalSession reloadSession = SessionHolder.findGlobalSession(tid); Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.RollbackRetrying); GlobalSession sessionInRetryRollbackingQueue = SessionHolder.getRetryRollbackingSessionManager() .findGlobalSession(tid); Assert.assertTrue(reloadSession == sessionInRetryRollbackingQueue); BranchSession reloadBranchSession = reloadSession.getBranch(branchSession1.getBranchId()); Assert.assertEquals(reloadBranchSession.getStatus(), BranchStatus.PhaseTwo_RollbackFailed_Retryable); // Lock is held by session in RollbackRetrying status Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1")); //clear reloadSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager()); reloadSession.end(); }
#vulnerable code @Test public void testRestoredFromFileRollbackRetry() throws Exception { SessionHolder.init("."); GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000); globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager()); globalSession.begin(); BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID, "ta:1", "xxx"); branchSession1.lock(); globalSession.addBranch(branchSession1); LockManager lockManager = LockManagerFactory.get(); Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1")); globalSession.changeStatus(GlobalStatus.Rollbacking); globalSession.changeBranchStatus(branchSession1, BranchStatus.PhaseTwo_RollbackFailed_Retryable); globalSession.changeStatus(GlobalStatus.RollbackRetrying); lockManager.cleanAllLocks(); Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1")); // Re-init SessionHolder: restore sessions from file SessionHolder.init("."); long tid = globalSession.getTransactionId(); GlobalSession reloadSession = SessionHolder.findGlobalSession(tid); Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.RollbackRetrying); GlobalSession sessionInRetryRollbackingQueue = SessionHolder.getRetryRollbackingSessionManager() .findGlobalSession(tid); Assert.assertTrue(reloadSession == sessionInRetryRollbackingQueue); BranchSession reloadBranchSession = reloadSession.getBranch(branchSession1.getBranchId()); Assert.assertEquals(reloadBranchSession.getStatus(), BranchStatus.PhaseTwo_RollbackFailed_Retryable); // Lock is held by session in RollbackRetrying status Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1")); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void addConfigListener(String dataId, ConfigChangeListener listener) { configListenersMap.putIfAbsent(dataId, new ArrayList<>()); configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>()); ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener); configChangeNotifiersMap.get(dataId).add(configChangeNotifier); if (null != listener.getExecutor()) { listener.getExecutor().submit(configChangeNotifier); } else { consulNotifierExecutor.submit(configChangeNotifier); } }
#vulnerable code @Override public void addConfigListener(String dataId, ConfigChangeListener listener) { configListenersMap.putIfAbsent(dataId, new ArrayList<>()); configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>()); ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener); configChangeNotifiersMap.get(dataId).add(configChangeNotifier); if (null != listener.getExecutor()) { listener.getExecutor().submit(configChangeNotifier); } else { consulConfigExecutor.submit(configChangeNotifier); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBigDataWrite() throws Exception { File seataFile = Files.newTemporaryFile(); FileTransactionStoreManager fileTransactionStoreManager = null; try { fileTransactionStoreManager = new FileTransactionStoreManager(seataFile.getAbsolutePath(), null); BranchSession branchSessionA = Mockito.mock(BranchSession.class); GlobalSession global = new GlobalSession(); Mockito.when(branchSessionA.encode()) .thenReturn(createBigBranchSessionData(global, (byte) 'A')); Mockito.when(branchSessionA.getApplicationData()) .thenReturn(new String(createBigApplicationData((byte) 'A'))); BranchSession branchSessionB = Mockito.mock(BranchSession.class); Mockito.when(branchSessionB.encode()) .thenReturn(createBigBranchSessionData(global, (byte) 'B')); Mockito.when(branchSessionB.getApplicationData()) .thenReturn(new String(createBigApplicationData((byte) 'B'))); Assertions.assertTrue(fileTransactionStoreManager.writeSession(TransactionStoreManager.LogOperation.BRANCH_ADD, branchSessionA)); Assertions.assertTrue(fileTransactionStoreManager.writeSession(TransactionStoreManager.LogOperation.BRANCH_ADD, branchSessionB)); List<TransactionWriteStore> list = fileTransactionStoreManager.readWriteStore(2000, false); Assertions.assertNotNull(list); Assertions.assertEquals(2, list.size()); BranchSession loadedBranchSessionA = (BranchSession) list.get(0).getSessionRequest(); Assertions.assertEquals(branchSessionA.getApplicationData(), loadedBranchSessionA.getApplicationData()); BranchSession loadedBranchSessionB = (BranchSession) list.get(1).getSessionRequest(); Assertions.assertEquals(branchSessionB.getApplicationData(), loadedBranchSessionB.getApplicationData()); } finally { if (null != fileTransactionStoreManager) { fileTransactionStoreManager.shutdown(); } Assertions.assertTrue(seataFile.delete()); } }
#vulnerable code @Test public void testBigDataWrite() throws Exception { File seataFile = Files.newTemporaryFile(); try { FileTransactionStoreManager fileTransactionStoreManager = new FileTransactionStoreManager(seataFile.getAbsolutePath(), null); BranchSession branchSessionA = Mockito.mock(BranchSession.class); GlobalSession global = new GlobalSession(); Mockito.when(branchSessionA.encode()) .thenReturn(createBigBranchSessionData(global, (byte) 'A')); Mockito.when(branchSessionA.getApplicationData()) .thenReturn(new String(createBigApplicationData((byte) 'A'))); BranchSession branchSessionB = Mockito.mock(BranchSession.class); Mockito.when(branchSessionB.encode()) .thenReturn(createBigBranchSessionData(global, (byte) 'B')); Mockito.when(branchSessionB.getApplicationData()) .thenReturn(new String(createBigApplicationData((byte) 'B'))); Assertions.assertTrue(fileTransactionStoreManager.writeSession(TransactionStoreManager.LogOperation.BRANCH_ADD, branchSessionA)); Assertions.assertTrue(fileTransactionStoreManager.writeSession(TransactionStoreManager.LogOperation.BRANCH_ADD, branchSessionB)); List<TransactionWriteStore> list = fileTransactionStoreManager.readWriteStore(2000, false); Assertions.assertNotNull(list); Assertions.assertEquals(2, list.size()); BranchSession loadedBranchSessionA = (BranchSession) list.get(0).getSessionRequest(); Assertions.assertEquals(branchSessionA.getApplicationData(), loadedBranchSessionA.getApplicationData()); BranchSession loadedBranchSessionB = (BranchSession) list.get(1).getSessionRequest(); Assertions.assertEquals(branchSessionB.getApplicationData(), loadedBranchSessionB.getApplicationData()); } finally { Assertions.assertTrue(seataFile.delete()); } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static long generateUUID() { return IdWorker.getInstance().nextId(); }
#vulnerable code public static long generateUUID() { long id = UUID.incrementAndGet(); if (id >= getMaxUUID()) { synchronized (UUID) { if (UUID.get() >= id) { id -= UUID_INTERNAL; UUID.set(id); } } } return id; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) { ProtocolV1Client client = new ProtocolV1Client(); client.connect("127.0.0.1", 8811, 500); Map<String, String> head = new HashMap<>(); head.put("tracerId", "xxadadadada"); head.put("token", "adadadad"); BranchCommitRequest body = new BranchCommitRequest(); body.setBranchId(12345L); body.setApplicationData("application"); body.setBranchType(BranchType.AT); body.setResourceId("resource-1234"); body.setXid("xid-1234"); final int threads = 50; final AtomicLong cnt = new AtomicLong(0); final ThreadPoolExecutor service1 = new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory("client-", false));// 无队列 for (int i = 0; i < threads; i++) { service1.execute(() -> { while (true) { try { Future future = client.sendRpc(head, body); RpcMessage resp = (RpcMessage) future.get(200, TimeUnit.MILLISECONDS); if (resp != null) { cnt.incrementAndGet(); } } catch (Exception e) { // ignore } } }); } Thread thread = new Thread(new Runnable() { private long last = 0; @Override public void run() { while (true) { long count = cnt.get(); long tps = count - last; LOGGER.error("last 1s invoke: {}, queue: {}", tps, service1.getQueue().size()); last = count; try { Thread.sleep(1000); } catch (InterruptedException e) { } } } }, "Print-tps-THREAD"); thread.start(); }
#vulnerable code public static void main(String[] args) throws InterruptedException, TimeoutException, ExecutionException { ProtocolV1Client client = new ProtocolV1Client(); client.connect("127.0.0.1", 8811, 500); Map<String, String> head = new HashMap<>(); head.put("tracerId", "xxadadadada"); head.put("token", "adadadad"); BranchCommitRequest body = new BranchCommitRequest(); body.setBranchId(12345L); body.setApplicationData("application"); body.setBranchType(BranchType.AT); body.setResourceId("resource-1234"); body.setXid("xid-1234"); RpcMessage rpcMessage = new RpcMessage(); rpcMessage.setId(client.idGenerator.incrementAndGet()); rpcMessage.setCodec(CodecType.SEATA.getCode()); rpcMessage.setCompressor(ProtocolConstants.CONFIGURED_COMPRESSOR); rpcMessage.setHeadMap(head); rpcMessage.setBody(body); rpcMessage.setMessageType(ProtocolConstants.MSGTYPE_RESQUEST); Future future = client.send(rpcMessage.getId(), rpcMessage); RpcMessage resp = (RpcMessage) future.get(200, TimeUnit.SECONDS); System.out.println(resp.getId() + " " + resp.getBody()); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void subscribe(String cluster, Watch.Listener listener) throws Exception { listenerMap.putIfAbsent(cluster, new HashSet<>()); listenerMap.get(cluster).add(listener); EtcdWatcher watcher = watcherMap.computeIfAbsent(cluster, w -> new EtcdWatcher(listener)); executorService.submit(watcher); }
#vulnerable code @Override public void subscribe(String cluster, Watch.Listener listener) throws Exception { listenerMap.putIfAbsent(cluster, new HashSet<>()); listenerMap.get(cluster).add(listener); EtcdWatcher watcher = watcherMap.computeIfAbsent(cluster, w -> new EtcdWatcher(listener)); EXECUTOR_SERVICE.submit(watcher); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean putConfigIfAbsent(String dataId, String content, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUTIFABSENT, timeoutMills); consulNotifierExecutor.execute(() -> { PutParams putParams = new PutParams(); //Setting CAS to 0 means that this is an atomic operation, created when key does not exist. putParams.setCas(CAS); complete(getConsulClient().setKVValue(dataId, content, putParams), configFuture); }); return (Boolean) configFuture.get(); }
#vulnerable code @Override public boolean putConfigIfAbsent(String dataId, String content, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUTIFABSENT, timeoutMills); consulConfigExecutor.execute(() -> { PutParams putParams = new PutParams(); //Setting CAS to 0 means that this is an atomic operation, created when key does not exist. putParams.setCas(CAS); complete(getConsulClient().setKVValue(dataId, content, putParams), configFuture); }); return (Boolean) configFuture.get(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testRestoredFromFile2() throws Exception { SessionHolder.init("file"); GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000); globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager()); globalSession.begin(); // Re-init SessionHolder: restore sessions from file SessionHolder.init("file"); }
#vulnerable code public void testRestoredFromFile2() throws Exception { SessionHolder.init("."); GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000); globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager()); globalSession.begin(); // Re-init SessionHolder: restore sessions from file SessionHolder.init("."); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static TableMeta resultSetMetaToSchema(ResultSetMetaData rsmd, DatabaseMetaData dbmd, String tableName) throws SQLException { String schemaName = rsmd.getSchemaName(1); String catalogName = rsmd.getCatalogName(1); TableMeta tm = new TableMeta(); tm.setTableName(tableName); ResultSet rsColumns = dbmd.getColumns(catalogName, schemaName, tableName, "%"); ResultSet rsIndex = dbmd.getIndexInfo(catalogName, schemaName, tableName, false, true); try { while (rsColumns.next()) { ColumnMeta col = new ColumnMeta(); col.setTableCat(rsColumns.getString("TABLE_CAT")); col.setTableSchemaName(rsColumns.getString("TABLE_SCHEM")); col.setTableName(rsColumns.getString("TABLE_NAME")); col.setColumnName(rsColumns.getString("COLUMN_NAME")); col.setDataType(rsColumns.getInt("DATA_TYPE")); col.setDataTypeName(rsColumns.getString("TYPE_NAME")); col.setColumnSize(rsColumns.getInt("COLUMN_SIZE")); col.setDecimalDigits(rsColumns.getInt("DECIMAL_DIGITS")); col.setNumPrecRadix(rsColumns.getInt("NUM_PREC_RADIX")); col.setNullAble(rsColumns.getInt("NULLABLE")); col.setRemarks(rsColumns.getString("REMARKS")); col.setColumnDef(rsColumns.getString("COLUMN_DEF")); col.setSqlDataType(rsColumns.getInt("SQL_DATA_TYPE")); col.setSqlDatetimeSub(rsColumns.getInt("SQL_DATETIME_SUB")); col.setCharOctetLength(rsColumns.getInt("CHAR_OCTET_LENGTH")); col.setOrdinalPosition(rsColumns.getInt("ORDINAL_POSITION")); col.setIsNullAble(rsColumns.getString("IS_NULLABLE")); col.setIsAutoincrement(rsColumns.getString("IS_AUTOINCREMENT")); tm.getAllColumns().put(col.getColumnName(), col); } while (rsIndex.next()) { String indexName = rsIndex.getString("INDEX_NAME"); String colName = rsIndex.getString("COLUMN_NAME"); ColumnMeta col = tm.getAllColumns().get(colName); if (tm.getAllIndexes().containsKey(indexName)) { IndexMeta index = tm.getAllIndexes().get(indexName); index.getValues().add(col); } else { IndexMeta index = new IndexMeta(); index.setIndexName(indexName); index.setNonUnique(rsIndex.getBoolean("NON_UNIQUE")); index.setIndexQualifier(rsIndex.getString("INDEX_QUALIFIER")); index.setIndexName(rsIndex.getString("INDEX_NAME")); index.setType(rsIndex.getShort("TYPE")); index.setOrdinalPosition(rsIndex.getShort("ORDINAL_POSITION")); index.setAscOrDesc(rsIndex.getString("ASC_OR_DESC")); index.setCardinality(rsIndex.getInt("CARDINALITY")); index.getValues().add(col); if ("PRIMARY".equalsIgnoreCase(indexName)) { index.setIndextype(IndexType.PRIMARY); } else if (!index.isNonUnique()) { index.setIndextype(IndexType.Unique); } else { index.setIndextype(IndexType.Normal); } tm.getAllIndexes().put(indexName, index); } } if (tm.getAllIndexes().isEmpty()) { throw new ShouldNeverHappenException("Could not found any index in the table: " + tableName); } } finally { if (rsColumns != null) { rsColumns.close(); } if (rsIndex != null) { rsIndex.close(); } } return tm; }
#vulnerable code private static TableMeta resultSetMetaToSchema(ResultSetMetaData rsmd, DatabaseMetaData dbmd, String tableName) throws SQLException { String schemaName = rsmd.getSchemaName(1); String catalogName = rsmd.getCatalogName(1); TableMeta tm = new TableMeta(); tm.setTableName(tableName); ResultSet rs1 = dbmd.getColumns(catalogName, schemaName, tableName, "%"); while (rs1.next()) { ColumnMeta col = new ColumnMeta(); col.setTableCat(rs1.getString("TABLE_CAT")); col.setTableSchemaName(rs1.getString("TABLE_SCHEM")); col.setTableName(rs1.getString("TABLE_NAME")); col.setColumnName(rs1.getString("COLUMN_NAME")); col.setDataType(rs1.getInt("DATA_TYPE")); col.setDataTypeName(rs1.getString("TYPE_NAME")); col.setColumnSize(rs1.getInt("COLUMN_SIZE")); col.setDecimalDigits(rs1.getInt("DECIMAL_DIGITS")); col.setNumPrecRadix(rs1.getInt("NUM_PREC_RADIX")); col.setNullAble(rs1.getInt("NULLABLE")); col.setRemarks(rs1.getString("REMARKS")); col.setColumnDef(rs1.getString("COLUMN_DEF")); col.setSqlDataType(rs1.getInt("SQL_DATA_TYPE")); col.setSqlDatetimeSub(rs1.getInt("SQL_DATETIME_SUB")); col.setCharOctetLength(rs1.getInt("CHAR_OCTET_LENGTH")); col.setOrdinalPosition(rs1.getInt("ORDINAL_POSITION")); col.setIsNullAble(rs1.getString("IS_NULLABLE")); col.setIsAutoincrement(rs1.getString("IS_AUTOINCREMENT")); tm.getAllColumns().put(col.getColumnName(), col); } ResultSet rs2 = dbmd.getIndexInfo(catalogName, schemaName, tableName, false, true); String indexName = ""; while (rs2.next()) { indexName = rs2.getString("INDEX_NAME"); String colName = rs2.getString("COLUMN_NAME"); ColumnMeta col = tm.getAllColumns().get(colName); if (tm.getAllIndexes().containsKey(indexName)) { IndexMeta index = tm.getAllIndexes().get(indexName); index.getValues().add(col); } else { IndexMeta index = new IndexMeta(); index.setIndexName(indexName); index.setNonUnique(rs2.getBoolean("NON_UNIQUE")); index.setIndexQualifier(rs2.getString("INDEX_QUALIFIER")); index.setIndexName(rs2.getString("INDEX_NAME")); index.setType(rs2.getShort("TYPE")); index.setOrdinalPosition(rs2.getShort("ORDINAL_POSITION")); index.setAscOrDesc(rs2.getString("ASC_OR_DESC")); index.setCardinality(rs2.getInt("CARDINALITY")); index.getValues().add(col); if ("PRIMARY".equalsIgnoreCase(indexName) || indexName.equalsIgnoreCase( rsmd.getTableName(1) + "_pkey")) { index.setIndextype(IndexType.PRIMARY); } else if (!index.isNonUnique()) { index.setIndextype(IndexType.Unique); } else { index.setIndextype(IndexType.Normal); } tm.getAllIndexes().put(indexName, index); } } if(tm.getAllIndexes().isEmpty()){ throw new ShouldNeverHappenException("Could not found any index in the table: " + tableName); } IndexMeta index = tm.getAllIndexes().get(indexName); if (index.getIndextype().value() != 0) { if ("H2 JDBC Driver".equals(dbmd.getDriverName())) { if (indexName.length() > 11 && "PRIMARY_KEY".equalsIgnoreCase(indexName.substring(0, 11))) { index.setIndextype(IndexType.PRIMARY); } } else if (dbmd.getDriverName() != null && dbmd.getDriverName().toLowerCase().indexOf("postgresql") >= 0) { if ((tableName + "_pkey").equalsIgnoreCase(indexName)) { index.setIndextype(IndexType.PRIMARY); } } } return tm; } #location 71 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String getConfig(String dataId, String defaultValue, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, defaultValue, ConfigFuture.ConfigOperation.GET, timeoutMills); etcdConfigExecutor.execute(() -> complete(getClient().getKVClient().get(ByteSequence.from(dataId, UTF_8)), configFuture)); return (String) configFuture.get(); }
#vulnerable code @Override public String getConfig(String dataId, String defaultValue, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, defaultValue, ConfigFuture.ConfigOperation.GET, timeoutMills); etcdConfigExecutor.execute(() -> { complete(getClient().getKVClient().get(ByteSequence.from(dataId, UTF_8)), configFuture); }); return (String) configFuture.get(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String getConfig(String dataId, String defaultValue, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, defaultValue, ConfigFuture.ConfigOperation.GET, timeoutMills); consulNotifierExecutor.execute(() -> { complete(getConsulClient().getKVValue(dataId), configFuture); }); return (String) configFuture.get(); }
#vulnerable code @Override public String getConfig(String dataId, String defaultValue, long timeoutMills) { ConfigFuture configFuture = new ConfigFuture(dataId, defaultValue, ConfigFuture.ConfigOperation.GET, timeoutMills); consulConfigExecutor.execute(() -> { complete(getConsulClient().getKVValue(dataId), configFuture); }); return (String) configFuture.get(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public BranchStatus branchCommit(BranchType branchType, String xid, long branchId, String resourceId, String applicationData) throws TransactionException { try { BranchCommitRequest request = new BranchCommitRequest(); request.setXid(xid); request.setBranchId(branchId); request.setResourceId(resourceId); request.setApplicationData(applicationData); request.setBranchType(branchType); GlobalSession globalSession = SessionHolder.findGlobalSession(xid); if (globalSession == null) { return BranchStatus.PhaseTwo_Committed; } if (BranchType.SAGA.equals(branchType)) { Map<String,Channel> channels = ChannelManager.getRmChannels(); if (channels == null || channels.size() == 0) { LOGGER.error("Failed to commit SAGA global[" + globalSession.getXid() + ", RM channels is empty."); return BranchStatus.PhaseTwo_CommitFailed_Retryable; } String sagaResourceId = globalSession.getApplicationId() + "#" + globalSession.getTransactionServiceGroup(); Channel sagaChannel = channels.get(sagaResourceId); if (sagaChannel == null) { LOGGER.error("Failed to commit SAGA global[" + globalSession.getXid() + ", cannot find channel by resourceId["+sagaResourceId+"]"); return BranchStatus.PhaseTwo_CommitFailed_Retryable; } BranchCommitResponse response = (BranchCommitResponse)messageSender.sendSyncRequest(sagaChannel, request); return response.getBranchStatus(); } else { BranchSession branchSession = globalSession.getBranch(branchId); if (null != branchSession) { BranchCommitResponse response = (BranchCommitResponse)messageSender.sendSyncRequest(resourceId, branchSession.getClientId(), request); return response.getBranchStatus(); } else { return BranchStatus.PhaseTwo_Committed; } } } catch (IOException | TimeoutException e) { throw new BranchTransactionException(FailedToSendBranchCommitRequest, String.format("Send branch commit failed, xid = %s branchId = %s", xid, branchId), e); } }
#vulnerable code @Override public BranchStatus branchCommit(BranchType branchType, String xid, long branchId, String resourceId, String applicationData) throws TransactionException { try { BranchCommitRequest request = new BranchCommitRequest(); request.setXid(xid); request.setBranchId(branchId); request.setResourceId(resourceId); request.setApplicationData(applicationData); request.setBranchType(branchType); GlobalSession globalSession = SessionHolder.findGlobalSession(xid); if (globalSession == null) { return BranchStatus.PhaseTwo_Committed; } if(BranchType.SAGA.equals(branchType)){ Map<String,Channel> channels = ChannelManager.getRmChannels(); if(channels == null || channels.size() == 0){ LOGGER.error("Failed to commit SAGA global[" + globalSession.getXid() + ", RM channels is empty."); return BranchStatus.PhaseTwo_CommitFailed_Retryable; } String sagaResourceId = globalSession.getApplicationId() + "#" + globalSession.getTransactionServiceGroup(); Channel sagaChannel = channels.get(sagaResourceId); if(sagaChannel == null){ LOGGER.error("Failed to commit SAGA global[" + globalSession.getXid() + ", cannot find channel by resourceId["+sagaResourceId+"]"); return BranchStatus.PhaseTwo_CommitFailed_Retryable; } BranchCommitResponse response = (BranchCommitResponse)messageSender.sendSyncRequest(sagaChannel, request); return response.getBranchStatus(); } else{ BranchSession branchSession = globalSession.getBranch(branchId); BranchCommitResponse response = (BranchCommitResponse)messageSender.sendSyncRequest(resourceId, branchSession.getClientId(), request); return response.getBranchStatus(); } } catch (IOException | TimeoutException e) { throw new BranchTransactionException(FailedToSendBranchCommitRequest, String.format("Send branch commit failed, xid = %s branchId = %s", xid, branchId), e); } } #location 39 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.