instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getLength() { try { JarFile jarFile = new JarFile(file); try { return jarFile.getEntry(getName()).getSize(); } finally { jarFile.close(); } } catch (IOException e) { return super.getLength(); } }
#vulnerable code public long getLength() { try { JarFile jarFile = new JarFile(file); return jarFile.getEntry(getName()).getSize(); } catch (IOException e) { return super.getLength(); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { return; } if (ServletLoader.getServletContext() == null) { ServletLoader.setServletContext(servletContext); } if (ENGINE == null) { synchronized (WebEngine.class) { if (ENGINE == null) { // double check Properties properties = new Properties(); String config = servletContext.getInitParameter(CONFIG_KEY); if (StringUtils.isEmpty(config)) { config = WEBINF_CONFIG; } if (config.startsWith("/")) { InputStream in = servletContext.getResourceAsStream(config); if (in != null) { try { properties.load(in); } catch (IOException e) { throw new IllegalStateException("Failed to load httl config " + config + " in wepapp. cause: " + e.getMessage(), e); } } else if (servletContext.getInitParameter(CONFIG_KEY) != null) { // 用户主动配置错误提醒 throw new IllegalStateException("Not found httl config " + config + " in wepapp."); } else { config = null; } } ENGINE = Engine.getEngine(config, addProperties(properties)); logConfigPath(ENGINE, servletContext, config); } } } }
#vulnerable code public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { return; } if (ServletLoader.getServletContext() == null) { ServletLoader.setServletContext(servletContext); } if (ENGINE == null) { synchronized (WebEngine.class) { if (ENGINE == null) { // double check Properties properties = new Properties(); String config = servletContext.getInitParameter(CONFIG_KEY); if (config == null || config.length() == 0) { config = WEBINF_CONFIG; } if (config.startsWith("/")) { InputStream in = servletContext.getResourceAsStream(config); if (in != null) { try { properties.load(in); } catch (IOException e) { throw new IllegalStateException("Failed to load httl config " + config + " in wepapp. cause: " + e.getMessage(), e); } } else if (servletContext.getInitParameter(CONFIG_KEY) != null) { // 用户主动配置错误提醒 throw new IllegalStateException("Not found httl config " + config + " in wepapp."); } else { config = null; } } ENGINE = Engine.getEngine(config, addProperties(properties)); logConfigPath(ENGINE, servletContext, config); } } } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try { if (baos != null) baos.close(); } finally { try { if (gzis != null) gzis.close(); } finally { if (bais != null) bais.close(); } } } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; }
#vulnerable code public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } #location 50 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Object parseXbean(String xml) { if (xml == null) { return null; } ByteArrayInputStream bi = new ByteArrayInputStream(xml.getBytes()); XMLDecoder xd = new XMLDecoder(bi); try { return xd.readObject(); } finally { xd.close(); } }
#vulnerable code public static Object parseXbean(String xml) { if (xml == null) { return null; } ByteArrayInputStream bi = new ByteArrayInputStream(xml.getBytes()); XMLDecoder xd = new XMLDecoder(bi); return xd.readObject(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try { if (gzos != null) gzos.close(); } finally { try { if (b64os != null) b64os.close(); } finally { if (baos != null) baos.close(); } } } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress }
#vulnerable code public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress } #location 43 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void process(final Resource resource, final Reader reader, final Writer writer) throws IOException { try { // using ReaderInputStream instead of ByteArrayInputStream, cause processing to freeze final String encoding = Context.get().getConfig().getEncoding(); final InputStream is = new BomStripperInputStream(new ByteArrayInputStream(IOUtils.toByteArray(reader, encoding))); IOUtils.copy(is, writer, encoding); } finally { reader.close(); writer.close(); } }
#vulnerable code public void process(final Resource resource, final Reader reader, final Writer writer) throws IOException { try { System.out.println("BOM:"); // using ReaderInputStream instead of ByteArrayInputStream, cause processing to freeze final InputStream is = new BomStripperInputStream(new ByteArrayInputStream(IOUtils.toByteArray(reader))); IOUtils.copy(is, writer, Context.get().getConfig().getEncoding()); System.out.println("END BOM"); } finally { reader.close(); writer.close(); } } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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 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 public InputStream getInputStream(final HttpServletRequest request, final HttpServletResponse response, final String location) throws IOException { Validate.notNull(request); Validate.notNull(response); // where to write the bytes of the stream final ByteArrayOutputStream os = new ByteArrayOutputStream(); boolean warnOnEmptyStream = false; // preserve context, in case it is unset during dispatching final Context originalContext = Context.get(); try { final RequestDispatcher dispatcher = request.getRequestDispatcher(location); if (dispatcher == null) { // happens when dynamic servlet context relative resources are included outside of the request cycle (inside // the thread responsible for refreshing resources) // Returns the part URL from the protocol name up to the query string and contextPath. final String servletContextPath = request.getRequestURL().toString().replace(request.getServletPath(), ""); final String absolutePath = servletContextPath + location; return externalResourceLocator.locate(absolutePath); } // Wrap request final ServletRequest servletRequest = getWrappedServletRequest(request, location); // Wrap response final ServletResponse servletResponse = new RedirectedStreamServletResponseWrapper(os, response); LOG.debug("dispatching request to location: " + location); // use dispatcher dispatcher.include(servletRequest, servletResponse); warnOnEmptyStream = true; // force flushing - the content will be written to // BytArrayOutputStream. Otherwise exactly 32K of data will be // written. servletResponse.getWriter().flush(); os.close(); } catch (final Exception e) { // Not only servletException can be thrown, also dispatch.include can throw NPE when the scheduler runs outside // of the request cycle, thus connection is unavailable. This is caused mostly when invalid resources are // included. LOG.debug("[FAIL] Error while dispatching the request for location {}", location); throw new IOException("Error while dispatching the request for location " + location); } finally { if (warnOnEmptyStream && os.size() == 0) { LOG.warn("Wrong or empty resource with location: {}", location); } // Put the context back if (!Context.isContextSet()) { Context.set(originalContext); } } return new ByteArrayInputStream(os.toByteArray()); }
#vulnerable code public InputStream getInputStream(final HttpServletRequest request, final HttpServletResponse response, final String location) throws IOException { Validate.notNull(request); Validate.notNull(response); // where to write the bytes of the stream final ByteArrayOutputStream os = new ByteArrayOutputStream(); boolean warnOnEmptyStream = false; // preserve context, in case it is unset during dispatching final Context originalContext = Context.get(); try { final RequestDispatcher dispatcher = request.getRequestDispatcher(location); if (dispatcher == null) { // happens when dynamic servlet context relative resources are included outside of the request cycle (inside // the thread responsible for refreshing resources) // Returns the part URL from the protocol name up to the query string and contextPath. final String servletContextPath = request.getRequestURL().toString().replace(request.getServletPath(), ""); final String absolutePath = servletContextPath + location; return getLocationStream(absolutePath); } // Wrap request final ServletRequest wrappedRequest = getWrappedServletRequest(request, location); // Wrap response final ServletResponse wrappedResponse = getWrappedServletResponse(response, os); LOG.debug("dispatching request to location: " + location); // use dispatcher dispatcher.include(wrappedRequest, wrappedResponse); warnOnEmptyStream = true; // force flushing - the content will be written to // BytArrayOutputStream. Otherwise exactly 32K of data will be // written. wrappedResponse.getWriter().flush(); os.close(); } catch (final Exception e) { // Not only servletException can be thrown, also dispatch.include can throw NPE when the scheduler runs outside // of the request cycle, thus connection is unavailable. This is caused mostly when invalid resources are // included. LOG.debug("[FAIL] Error while dispatching the request for location {}", location); throw new IOException("Error while dispatching the request for location " + location); } finally { if (warnOnEmptyStream && os.size() == 0) { LOG.warn("Wrong or empty resource with location: {}", location); } // Put the context back if (!Context.isContextSet()) { Context.set(originalContext); } } return new ByteArrayInputStream(os.toByteArray()); } #location 34 #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 @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 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 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 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 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 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 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 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 @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 @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 @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 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 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 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 @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 { 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 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 @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 encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) { try { if (msg instanceof RpcMessage) { RpcMessage rpcMessage = (RpcMessage) msg; int fullLength = ProtocolConstants.V1_HEAD_LENGTH; int headLength = ProtocolConstants.V1_HEAD_LENGTH; byte messageType = rpcMessage.getMessageType(); out.writeBytes(ProtocolConstants.MAGIC_CODE_BYTES); out.writeByte(ProtocolConstants.VERSION); // full Length(4B) and head length(2B) will fix in the end. out.writerIndex(out.writerIndex() + 6); out.writeByte(messageType); out.writeByte(rpcMessage.getCodec()); out.writeByte(rpcMessage.getCompressor()); out.writeInt(rpcMessage.getId()); // direct write head with zero-copy Map<String, String> headMap = rpcMessage.getHeadMap(); if (headMap != null && !headMap.isEmpty()) { int headMapBytesLength = HeadMapSerializer.getInstance().encode(headMap, out); headLength += headMapBytesLength; fullLength += headMapBytesLength; } byte[] bodyBytes = null; if (messageType != ProtocolConstants.MSGTYPE_HEARTBEAT_REQUEST && messageType != ProtocolConstants.MSGTYPE_HEARTBEAT_RESPONSE) { // heartbeat has no body Codec codec = CodecFactory.getCodec(rpcMessage.getCodec()); bodyBytes = codec.encode(rpcMessage.getBody()); fullLength += bodyBytes.length; } if (bodyBytes != null) { out.writeBytes(bodyBytes); } // fix fullLength and headLength int writeIndex = out.writerIndex(); // skip magic code(2B) + version(1B) out.writerIndex(writeIndex - fullLength + 3); out.writeInt(fullLength); out.writeShort(headLength); out.writerIndex(writeIndex); } else { throw new UnsupportedOperationException("Not support this class:" + msg.getClass()); } } catch (Throwable e) { LOGGER.error("Encode request error!", e); } }
#vulnerable code @Override public void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) { try { if (msg instanceof RpcMessage) { RpcMessage rpcMessage = (RpcMessage) msg; int fullLength = 13; int headLength = 0; // count head byte[] headBytes = null; Map<String, String> headMap = rpcMessage.getHeadMap(); if (headMap != null && !headMap.isEmpty()) { headBytes = HeadMapSerializer.getInstance().encode(headMap); headLength = headBytes.length; fullLength += headLength; } byte[] bodyBytes = null; byte messageType = rpcMessage.getMessageType(); if (messageType != ProtocolConstants.MSGTYPE_HEARTBEAT_REQUEST && messageType != ProtocolConstants.MSGTYPE_HEARTBEAT_RESPONSE) { // heartbeat has no body Codec codec = CodecFactory.getCodec(rpcMessage.getCodec()); bodyBytes = codec.encode(rpcMessage.getBody()); fullLength += bodyBytes.length; } out.writeBytes(ProtocolConstants.MAGIC_CODE_BYTES); out.writeByte(ProtocolConstants.VERSION); out.writeInt(fullLength); out.writeShort(headLength); out.writeByte(messageType); out.writeByte(rpcMessage.getCodec()); out.writeByte(rpcMessage.getCompressor()); out.writeInt(rpcMessage.getId()); if (headBytes != null) { out.writeBytes(headBytes); } if (bodyBytes != null) { out.writeBytes(bodyBytes); } } else { throw new UnsupportedOperationException("Not support this class:" + msg.getClass()); } } catch (Throwable e) { LOGGER.error("Encode request error!", e); } } #location 15 #vulnerability type NULL_DEREFERENCE
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 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); 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 protected Connection getConnectionProxy(Connection connection) throws SQLException { if (!RootContext.inGlobalTransaction()) { return connection; } return getConnectionProxyXA(connection); }
#vulnerable code protected Connection getConnectionProxy(Connection connection) throws SQLException { Connection physicalConn = connection.unwrap(Connection.class); XAConnection xaConnection = XAUtils.createXAConnection(physicalConn, this); ConnectionProxyXA connectionProxyXA = new ConnectionProxyXA(connection, xaConnection, this, RootContext.getXID()); connectionProxyXA.init(); return connectionProxyXA; } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRestoredFromFileCommitRetry() 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.Committing); globalSession.changeBranchStatus(branchSession1, BranchStatus.PhaseTwo_CommitFailed_Retryable); globalSession.changeStatus(GlobalStatus.CommitRetrying); 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.CommitRetrying); GlobalSession sessionInRetryCommittingQueue = SessionHolder.getRetryCommittingSessionManager() .findGlobalSession(tid); Assert.assertTrue(reloadSession == sessionInRetryCommittingQueue); BranchSession reloadBranchSession = reloadSession.getBranch(branchSession1.getBranchId()); Assert.assertEquals(reloadBranchSession.getStatus(), BranchStatus.PhaseTwo_CommitFailed_Retryable); // Lock is held by session in CommitRetrying status Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1")); //clear reloadSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager()); reloadSession.end(); }
#vulnerable code @Test public void testRestoredFromFileCommitRetry() 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.Committing); globalSession.changeBranchStatus(branchSession1, BranchStatus.PhaseTwo_CommitFailed_Retryable); globalSession.changeStatus(GlobalStatus.CommitRetrying); 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.CommitRetrying); GlobalSession sessionInRetryCommittingQueue = SessionHolder.getRetryCommittingSessionManager() .findGlobalSession(tid); Assert.assertTrue(reloadSession == sessionInRetryCommittingQueue); BranchSession reloadBranchSession = reloadSession.getBranch(branchSession1.getBranchId()); Assert.assertEquals(reloadBranchSession.getStatus(), BranchStatus.PhaseTwo_CommitFailed_Retryable); // Lock is held by session in CommitRetrying 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 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRestoredFromFileAsyncCommitting() 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"); Assert.assertTrue(branchSession1.lock()); globalSession.addBranch(branchSession1); LockManager lockManager = LockManagerFactory.get(); Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1")); globalSession.changeStatus(GlobalStatus.AsyncCommitting); 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.AsyncCommitting); GlobalSession sessionInAsyncCommittingQueue = SessionHolder.getAsyncCommittingSessionManager() .findGlobalSession(tid); Assert.assertTrue(reloadSession == sessionInAsyncCommittingQueue); // No locking for session in AsyncCommitting status Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1")); //clear reloadSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager()); reloadSession.end(); }
#vulnerable code @Test public void testRestoredFromFileAsyncCommitting() 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"); Assert.assertTrue(branchSession1.lock()); globalSession.addBranch(branchSession1); LockManager lockManager = LockManagerFactory.get(); Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1")); globalSession.changeStatus(GlobalStatus.AsyncCommitting); 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.AsyncCommitting); GlobalSession sessionInAsyncCommittingQueue = SessionHolder.getAsyncCommittingSessionManager() .findGlobalSession(tid); Assert.assertTrue(reloadSession == sessionInAsyncCommittingQueue); // No locking for session in AsyncCommitting status Assert.assertTrue(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 @Test public void refreshTest_0() throws SQLException { MockDriver mockDriver = new MockDriver(columnMetas, indexMetas); DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setUrl("jdbc:mock:xxx"); druidDataSource.setDriver(mockDriver); DataSourceProxy dataSourceProxy = new DataSourceProxy(druidDataSource); TableMeta tableMeta = getTableMetaCache().getTableMeta(dataSourceProxy.getPlainConnection(), "t1", dataSourceProxy.getResourceId()); //change the columns meta columnMetas = new Object[][] { new Object[] {"", "", "t1", "id", Types.INTEGER, "INTEGER", 64, 0, 10, 1, "", "", 0, 0, 64, 1, "NO", "YES"}, new Object[] {"", "", "t1", "name1", Types.VARCHAR, "VARCHAR", 65, 0, 10, 0, "", "", 0, 0, 64, 2, "YES", "NO"}, new Object[] {"", "", "t1", "name2", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 3, "YES", "NO"}, new Object[] {"", "", "t1", "name3", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 4, "YES", "NO"} }; mockDriver.setMockColumnsMetasReturnValue(columnMetas); getTableMetaCache().refresh(dataSourceProxy.getPlainConnection(), dataSourceProxy.getResourceId()); }
#vulnerable code @Test public void refreshTest_0() { MockDriver mockDriver = new MockDriver(columnMetas, indexMetas); DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setUrl("jdbc:mock:xxx"); druidDataSource.setDriver(mockDriver); DataSourceProxy dataSourceProxy = new DataSourceProxy(druidDataSource); TableMeta tableMeta = getTableMetaCache().getTableMeta(dataSourceProxy, "t1"); //change the columns meta columnMetas = new Object[][] { new Object[] {"", "", "t1", "id", Types.INTEGER, "INTEGER", 64, 0, 10, 1, "", "", 0, 0, 64, 1, "NO", "YES"}, new Object[] {"", "", "t1", "name1", Types.VARCHAR, "VARCHAR", 65, 0, 10, 0, "", "", 0, 0, 64, 2, "YES", "NO"}, new Object[] {"", "", "t1", "name2", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 3, "YES", "NO"}, new Object[] {"", "", "t1", "name3", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 4, "YES", "NO"} }; mockDriver.setMockColumnsMetasReturnValue(columnMetas); getTableMetaCache().refresh(dataSourceProxy); } #location 24 #vulnerability type RESOURCE_LEAK
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 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void configure() throws BatchConfigurationException { /* * Configure CB4J logger */ configureCB4JLogger(); logger.info("Configuration started at : " + new Date()); /* * Configure record reader */ configureRecordReader(); /* * Configure record parser */ configureRecordParser(); /* * Configure loggers for ignored/rejected records */ configureIgnoredAndRejectedRecordsLoggers(); /* * Configure batch reporter : if no custom reporter registered, use default implementation */ if (batchReporter == null) { batchReporter = new DefaultBatchReporterImpl(); } /* * Configure record validator with provided validators : if no custom validator registered, use default implementation */ if (recordValidator == null) { recordValidator = new DefaultRecordValidatorImpl(fieldValidators); } /* * Check record mapper */ if (recordMapper == null) { String error = "Configuration failed : no record mapper registered"; logger.severe(error); throw new BatchConfigurationException(error); } /* * Check record processor */ if (recordProcessor == null) { String error = "Configuration failed : no record processor registered"; logger.severe(error); throw new BatchConfigurationException(error); } /* * register JMX MBean */ configureJmxMBean(); logger.info("Configuration successful"); logger.info("Configuration parameters details : " + configurationProperties); }
#vulnerable code public void configure() throws BatchConfigurationException { /* * Configure CB4J logger */ logger.setUseParentHandlers(false); ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setFormatter(new LogFormatter()); logger.addHandler(consoleHandler); logger.info("Configuration started at : " + new Date()); /* * Configure record reader parameters */ String inputData = configurationProperties.getProperty(BatchConstants.INPUT_DATA_PATH); String encoding = configurationProperties.getProperty(BatchConstants.INPUT_DATA_ENCODING); final String skipHeaderProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_SKIP_HEADER); //check if input data file is specified if (inputData == null) { String error = "Configuration failed : input data file is mandatory but was not specified"; logger.severe(error); throw new BatchConfigurationException(error); } try { boolean skipHeader; if (skipHeaderProperty != null) { skipHeader = Boolean.valueOf(skipHeaderProperty); } else { skipHeader = BatchConstants.DEFAULT_SKIP_HEADER; logger.warning("Skip header property not specified, default to false"); } if (encoding == null || (encoding != null && encoding.length() == 0)) { encoding = System.getProperty("file.encoding"); logger.warning("No encoding specified for input data, using system default encoding : " + encoding); } else { if (Charset.availableCharsets().get(encoding) != null && !Charset.isSupported(encoding)) { logger.warning("Encoding '" + encoding + "' not supported, using system default encoding : " + System.getProperty("file.encoding")); encoding = System.getProperty("file.encoding"); } else { logger.config("Using '" + encoding + "' encoding for input file reading"); } } recordReader = new RecordReaderImpl(inputData, encoding, skipHeader); logger.config("Data input file : " + inputData); } catch (FileNotFoundException e) { String error = "Configuration failed : input data file '" + inputData + "' could not be opened"; logger.severe(error); throw new BatchConfigurationException(error); } /* * Configure record parser parameters * Convention over configuration : default separator is "," */ String recordSizeProperty = configurationProperties.getProperty(BatchConstants.INPUT_RECORD_SIZE); try { if (recordSizeProperty == null || (recordSizeProperty != null && recordSizeProperty.length() == 0)) { String error = "Record size property is not set"; logger.severe(error); throw new BatchConfigurationException(error); } int recordSize = Integer.parseInt(recordSizeProperty); String fieldsSeparator = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_SEPARATOR); if (fieldsSeparator == null || (fieldsSeparator != null && fieldsSeparator.length() == 0)) { fieldsSeparator = BatchConstants.DEFAULT_FIELD_SEPARATOR; logger.warning("No field separator specified, using default : '" + fieldsSeparator + "'"); } logger.config("Record size specified : " + recordSize); logger.config("Fields separator specified : '" + fieldsSeparator + "'"); recordParser = new RecordParserImpl(recordSize, fieldsSeparator); } catch (NumberFormatException e) { String error = "Record size property is not recognized as a number : " + recordSizeProperty; logger.severe(error); throw new BatchConfigurationException(error); } /* * Configure loggers for ignored/rejected records */ ReportFormatter reportFormatter = new ReportFormatter(); String outputIgnored = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_IGNORED); if (outputIgnored == null || (outputIgnored != null && outputIgnored.length() == 0)) { outputIgnored = BatchConfigurationUtil.removeExtension(inputData) + BatchConstants.DEFAULT_IGNORED_SUFFIX; logger.warning("No log file specified for ignored records, using default : " + outputIgnored); } try { FileHandler ignoredRecordsHandler = new FileHandler(outputIgnored); ignoredRecordsHandler.setFormatter(reportFormatter); Logger ignoredRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_IGNORED); ignoredRecordsReporter.addHandler(ignoredRecordsHandler); } catch (IOException e) { String error = "Unable to use file for ignored records : " + outputIgnored; logger.severe(error); throw new BatchConfigurationException(error); } String outputRejected = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_REJECTED); if (outputRejected == null || (outputRejected != null && outputRejected.length() == 0)) { outputRejected = BatchConfigurationUtil.removeExtension(inputData) + BatchConstants.DEFAULT_REJECTED_SUFFIX; logger.warning("No log file specified for rejected records, using default : " + outputRejected); } try { FileHandler rejectedRecordsHandler = new FileHandler(outputRejected); rejectedRecordsHandler.setFormatter(reportFormatter); Logger rejectedRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_REJECTED); rejectedRecordsReporter.addHandler(rejectedRecordsHandler); } catch (IOException e) { String error = "Unable to use file for rejected records : " + outputRejected; logger.severe(error); throw new BatchConfigurationException(error); } /* * Configure batch reporter : if no custom reporter registered, use default implementation */ if (batchReporter == null) { batchReporter = new DefaultBatchReporterImpl(); } /* * Configure record validator with provided validators : : if no custom validator registered, use default implementation */ if (recordValidator == null) { recordValidator = new DefaultRecordValidatorImpl(fieldValidators); } /* * Check record mapper */ if (recordMapper == null) { String error = "Configuration failed : no record mapper registered"; logger.severe(error); throw new BatchConfigurationException(error); } /* * Check record processor */ if (recordProcessor == null) { String error = "Configuration failed : no record processor registered"; logger.severe(error); throw new BatchConfigurationException(error); } /* * Configure JMX MBean */ MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name; try { name = new ObjectName("net.benas.cb4j.jmx:type=BatchMonitorMBean"); BatchMonitorMBean batchMonitorMBean = new BatchMonitor(batchReporter); mbs.registerMBean(batchMonitorMBean, name); logger.info("CB4J JMX MBean registered successfully as: " + name.getCanonicalName()); } catch (Exception e) { String error = "Unable to register CB4J JMX MBean. Root exception is :" + e.getMessage(); logger.warning(error); } logger.info("Configuration successful"); logger.info("Configuration parameters details : " + configurationProperties); } #location 48 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testXmlRecordReading() throws Exception { // given dataSource = new File("src/test/resources/data.xml"); xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data"); xmlFileRecordReader.open(); String expectedDataSourceName = dataSource.getAbsolutePath(); // when XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord(); XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord(); XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord(); XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord(); // then assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L); assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>"); assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L); assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>"); assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L); assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>"); assertThat(xmlRecord4).isNull(); }
#vulnerable code @Test public void testXmlRecordReading() throws Exception { String expectedDataSourceName = dataSource.getAbsolutePath(); XmlRecord xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord).isNull(); } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public StringRecord processRecord(final Record<P> record) throws Exception { StringWriter stringWriter = new StringWriter(); CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat); Iterable<Object> iterable = fieldExtractor.extractFields(record.getPayload()); csvPrinter.printRecord(iterable); csvPrinter.flush(); csvPrinter.close(); return new StringRecord(record.getHeader(), stringWriter.toString()); }
#vulnerable code @Override public StringRecord processRecord(final Record<P> record) throws Exception { StringWriter stringWriter = new StringWriter(); CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat); Iterable<Object> iterable = fieldExtractor.extractFields(record.getPayload()); csvPrinter.printRecord(iterable); csvPrinter.flush(); return new StringRecord(record.getHeader(), stringWriter.toString()); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testXmlRecordReading() throws Exception { // given dataSource = new File("src/test/resources/data.xml"); xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data"); xmlFileRecordReader.open(); String expectedDataSourceName = dataSource.getAbsolutePath(); // when XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord(); XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord(); XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord(); XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord(); // then assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L); assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>"); assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L); assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>"); assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L); assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>"); assertThat(xmlRecord4).isNull(); }
#vulnerable code @Test public void testXmlRecordReading() throws Exception { String expectedDataSourceName = dataSource.getAbsolutePath(); XmlRecord xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord).isNull(); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadingEscapedXml() throws Exception { // given xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml")); xmlRecordReader.open(); // when XmlRecord record1 = xmlRecordReader.readRecord(); XmlRecord record2 = xmlRecordReader.readRecord(); XmlRecord record3 = xmlRecordReader.readRecord(); XmlRecord record4 = xmlRecordReader.readRecord(); XmlRecord record5 = xmlRecordReader.readRecord(); XmlRecord record6 = xmlRecordReader.readRecord(); // then assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&amp;sort=asc\"/>"); assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l&apos;equipe\" url=\"http://www.lequipe.fr\"/>"); assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l&quot;internaute.com\" url=\"http://www.linternaute.com\"/>"); assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&amp;sort=asc</website>"); assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\">&lt;test&gt;foo&lt;/test&gt;</website>"); assertThat(record6).isNull(); }
#vulnerable code @Test public void testReadingEscapedXml() throws Exception { xmlRecordReader.close(); xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml")); xmlRecordReader.open(); XmlRecord record = xmlRecordReader.readRecord(); assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&amp;sort=asc\"/>"); record = xmlRecordReader.readRecord(); assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l&apos;equipe\" url=\"http://www.lequipe.fr\"/>"); record = xmlRecordReader.readRecord(); assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l&quot;internaute.com\" url=\"http://www.linternaute.com\"/>"); record = xmlRecordReader.readRecord(); assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&amp;sort=asc</website>"); record = xmlRecordReader.readRecord(); assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\">&lt;test&gt;foo&lt;/test&gt;</website>"); record = xmlRecordReader.readRecord(); assertThat(record).isNull(); } #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 testXmlRecordReading() throws Exception { // given dataSource = new File("src/test/resources/data.xml"); xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data"); xmlFileRecordReader.open(); String expectedDataSourceName = dataSource.getAbsolutePath(); // when XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord(); XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord(); XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord(); XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord(); // then assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L); assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>"); assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L); assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>"); assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L); assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>"); assertThat(xmlRecord4).isNull(); }
#vulnerable code @Test public void testXmlRecordReading() throws Exception { String expectedDataSourceName = dataSource.getAbsolutePath(); XmlRecord xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L); assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName); assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>"); xmlRecord = xmlFileRecordReader.readRecord(); assertThat(xmlRecord).isNull(); } #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 integrationTest() throws Exception { File inputTweets = new File(this.getClass().getResource("/tweets-in.xls").toURI()); File outputTweets = new File(this.getClass().getResource("/tweets-out.xls").toURI()); Job job = JobBuilder.aNewJob() .reader(new MsExcelRecordReader(inputTweets)) .filter(new HeaderRecordFilter()) .mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message")) .marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message")) .writer(new MsExcelRecordWriter(outputTweets)) .build(); JobReport report = JobExecutor.execute(job); assertThat(report).isNotNull(); assertThat(report.getMetrics().getTotalCount()).isEqualTo(3); assertThat(report.getMetrics().getFilteredCount()).isEqualTo(1); assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2); }
#vulnerable code @Test public void integrationTest() throws Exception { File inputTweets = new File(this.getClass().getResource("/tweets-in.xls").toURI()); File outputTweets = new File(this.getClass().getResource("/tweets-out.xls").toURI()); Job job = JobBuilder.aNewJob() .reader(new MsExcelRecordReader(inputTweets)) .filter(new HeaderRecordFilter()) .mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message")) //.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message")) //.writer(new MsExcelRecordWriter(outputTweets)) .writer(new StandardOutputRecordWriter()) .build(); JobReport report = JobExecutor.execute(job); assertThat(report).isNotNull(); assertThat(report.getMetrics().getTotalCount()).isEqualTo(3); assertThat(report.getMetrics().getFilteredCount()).isEqualTo(1); assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadingEscapedXml() throws Exception { // given xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml")); xmlRecordReader.open(); // when XmlRecord record1 = xmlRecordReader.readRecord(); XmlRecord record2 = xmlRecordReader.readRecord(); XmlRecord record3 = xmlRecordReader.readRecord(); XmlRecord record4 = xmlRecordReader.readRecord(); XmlRecord record5 = xmlRecordReader.readRecord(); XmlRecord record6 = xmlRecordReader.readRecord(); // then assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&amp;sort=asc\"/>"); assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l&apos;equipe\" url=\"http://www.lequipe.fr\"/>"); assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l&quot;internaute.com\" url=\"http://www.linternaute.com\"/>"); assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&amp;sort=asc</website>"); assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\">&lt;test&gt;foo&lt;/test&gt;</website>"); assertThat(record6).isNull(); }
#vulnerable code @Test public void testReadingEscapedXml() throws Exception { xmlRecordReader.close(); xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml")); xmlRecordReader.open(); XmlRecord record = xmlRecordReader.readRecord(); assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&amp;sort=asc\"/>"); record = xmlRecordReader.readRecord(); assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l&apos;equipe\" url=\"http://www.lequipe.fr\"/>"); record = xmlRecordReader.readRecord(); assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l&quot;internaute.com\" url=\"http://www.linternaute.com\"/>"); record = xmlRecordReader.readRecord(); assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&amp;sort=asc</website>"); record = xmlRecordReader.readRecord(); assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\">&lt;test&gt;foo&lt;/test&gt;</website>"); record = xmlRecordReader.readRecord(); assertThat(record).isNull(); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { final SingleWriterRecorder recorder = new SingleWriterRecorder( config.lowestTrackableValue, config.highestTrackableValue, config.numberOfSignificantValueDigits ); Histogram intervalHistogram = null; HiccupRecorder hiccupRecorder; final long uptimeAtInitialStartTime = ManagementFactory.getRuntimeMXBean().getUptime(); long now = System.currentTimeMillis(); long jvmStartTime = now - uptimeAtInitialStartTime; long reportingStartTime = jvmStartTime; if (config.inputFileName == null) { // Normal operating mode. // Launch a hiccup recorder, a process termination monitor, and an optional control process: hiccupRecorder = this.createHiccupRecorder(recorder); if (config.terminateWithStdInput) { new TerminateWithStdInputReader(); } if (config.controlProcessCommand != null) { new ExecProcess(config.controlProcessCommand, "ControlProcess", log, config.verbose); } } else { // Take input from file instead of sampling it ourselves. // Launch an input hiccup recorder, but no termination monitoring or control process: hiccupRecorder = new InputRecorder(recorder, config.inputFileName); } histogramLogWriter.outputComment("[Logged with " + getVersionString() + "]"); histogramLogWriter.outputLogFormatVersion(); try { final long startTime; if (config.inputFileName == null) { // Normal operating mode: if (config.startDelayMs > 0) { // Run hiccup recorder during startDelayMs time to let code warm up: hiccupRecorder.start(); while (config.startDelayMs > System.currentTimeMillis() - jvmStartTime) { Thread.sleep(100); } hiccupRecorder.terminate(); hiccupRecorder.join(); recorder.reset(); hiccupRecorder = new HiccupRecorder(recorder, config.allocateObjects); } hiccupRecorder.start(); startTime = System.currentTimeMillis(); if (config.startTimeAtZero) { reportingStartTime = startTime; } histogramLogWriter.outputStartTime(reportingStartTime); histogramLogWriter.setBaseTime(reportingStartTime); } else { // Reading from input file, not sampling ourselves...: hiccupRecorder.start(); reportingStartTime = startTime = hiccupRecorder.getCurrentTimeMsecWithDelay(0); histogramLogWriter.outputComment("[Data read from input file \"" + config.inputFileName + "\" at " + new Date() + "]"); } histogramLogWriter.outputLegend(); long nextReportingTime = startTime + config.reportingIntervalMs; long intervalStartTimeMsec = 0; while ((now > 0) && ((config.runTimeMs == 0) || (config.runTimeMs > now - startTime))) { now = hiccupRecorder.getCurrentTimeMsecWithDelay(nextReportingTime); // could return -1 to indicate termination if (now > nextReportingTime) { // Get the latest interval histogram and give the recorder a fresh Histogram for the next interval intervalHistogram = recorder.getIntervalHistogram(intervalHistogram); while (now > nextReportingTime) { nextReportingTime += config.reportingIntervalMs; } if (config.inputFileName != null) { // When read from input file, use timestamps from file input for start/end of log intervals: intervalHistogram.setStartTimeStamp(intervalStartTimeMsec); intervalHistogram.setEndTimeStamp(now); intervalStartTimeMsec = now; } if (intervalHistogram.getTotalCount() > 0) { histogramLogWriter.outputIntervalHistogram(intervalHistogram); } } } } catch (InterruptedException e) { if (config.verbose) { log.println("# HiccupMeter terminating..."); } } try { hiccupRecorder.terminate(); hiccupRecorder.join(); } catch (InterruptedException e) { if (config.verbose) { log.println("# HiccupMeter terminate/join interrupted"); } } }
#vulnerable code @Override public void run() { final SingleWriterRecorder recorder = new SingleWriterRecorder( config.lowestTrackableValue, config.highestTrackableValue, config.numberOfSignificantValueDigits ); Histogram intervalHistogram = null; HiccupRecorder hiccupRecorder; final long uptimeAtInitialStartTime = ManagementFactory.getRuntimeMXBean().getUptime(); long now = System.currentTimeMillis(); long jvmStartTime = now - uptimeAtInitialStartTime; long reportingStartTime = jvmStartTime; if (config.inputFileName == null) { // Normal operating mode. // Launch a hiccup recorder, a process termination monitor, and an optional control process: hiccupRecorder = this.createHiccupRecorder(recorder); if (config.terminateWithStdInput) { new TerminateWithStdInputReader(); } if (config.controlProcessCommand != null) { new ExecProcess(config.controlProcessCommand, "ControlProcess", log, config.verbose); } } else { // Take input from file instead of sampling it ourselves. // Launch an input hiccup recorder, but no termination monitoring or control process: hiccupRecorder = new InputRecorder(recorder, config.inputFileName); } histogramLogWriter.outputComment("[Logged with " + getVersionString() + "]"); histogramLogWriter.outputLogFormatVersion(); try { final long startTime; if (config.inputFileName == null) { // Normal operating mode: if (config.startDelayMs > 0) { // Run hiccup recorder during startDelayMs time to let code warm up: hiccupRecorder.start(); while (config.startDelayMs > System.currentTimeMillis() - jvmStartTime) { Thread.sleep(100); } hiccupRecorder.terminate(); hiccupRecorder.join(); recorder.reset(); hiccupRecorder = new HiccupRecorder(recorder, config.allocateObjects); } hiccupRecorder.start(); startTime = System.currentTimeMillis(); if (config.startTimeAtZero) { reportingStartTime = startTime; } histogramLogWriter.outputStartTime(reportingStartTime); histogramLogWriter.setBaseTime(reportingStartTime); } else { // Reading from input file, not sampling ourselves...: hiccupRecorder.start(); reportingStartTime = startTime = hiccupRecorder.getCurrentTimeMsecWithDelay(0); histogramLogWriter.outputComment("[Data read from input file \"" + config.inputFileName + "\" at " + new Date() + "]"); } histogramLogWriter.outputLegend(); long nextReportingTime = startTime + config.reportingIntervalMs; while ((now > 0) && ((config.runTimeMs == 0) || (config.runTimeMs > now - startTime))) { now = hiccupRecorder.getCurrentTimeMsecWithDelay(nextReportingTime); // could return -1 to indicate termination if (now > nextReportingTime) { // Get the latest interval histogram and give the recorder a fresh Histogram for the next interval intervalHistogram = recorder.getIntervalHistogram(intervalHistogram); while (now > nextReportingTime) { nextReportingTime += config.reportingIntervalMs; } if (intervalHistogram.getTotalCount() > 0) { histogramLogWriter.outputIntervalHistogram(intervalHistogram); } } } } catch (InterruptedException e) { if (config.verbose) { log.println("# HiccupMeter terminating..."); } } try { hiccupRecorder.terminate(); hiccupRecorder.join(); } catch (InterruptedException e) { if (config.verbose) { log.println("# HiccupMeter terminate/join interrupted"); } } } #location 50 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void init() { KafkaConsumer kafkaConsumer=new KafkaConsumer(getProperties()); //kafka消费消息,接收MQTT发来的消息 kafkaConsumer.subscribe(Arrays.asList(conf.get("mqttwk.broker.kafka.producer.topic"))); int sum=0; while (true) { ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(500)); for (ConsumerRecord<String, String> record : records) { log.debugf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), new String(HexUtil.decodeHex(record.value()))); log.debugf("总计收到 %s条",++sum); } } }
#vulnerable code public void init() { KafkaConsumer kafkaConsumer=new KafkaConsumer(getProperties()); //kafka消费消息,接收MQTT发来的消息 kafkaConsumer.subscribe(Arrays.asList(conf.get("mqttwk.broker.kafka.producer.topic"))); int sum=0; while (true) { ConsumerRecords<String, String> records = kafkaConsumer.poll(500); for (ConsumerRecord<String, String> record : records) { log.debugf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), new String(HexUtil.decodeHex(record.value()))); log.debugf("总计收到 %s条",++sum); } } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testZipArchiveCreation() throws Exception { // Archive final File output = new File(dir, "bla.zip"); final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); ArchiveOutputStream os = null; try { os = new ArchiveStreamFactory() .createArchiveOutputStream("zip", out); os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml")); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml")); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } else { out.close(); } } // Unarchive the same List results = new ArrayList(); final InputStream is = new FileInputStream(output); ArchiveInputStream in = null; try { in = new ArchiveStreamFactory() .createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) { File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName()); outfile.getParentFile().mkdirs(); OutputStream o = new FileOutputStream(outfile); try { IOUtils.copy(in, o); } finally { o.close(); } results.add(outfile); } } finally { if (in != null) { in.close(); } else { is.close(); } } assertEquals(results.size(), 2); File result = (File)results.get(0); assertEquals(file1.length(), result.length()); result = (File)results.get(1); assertEquals(file2.length(), result.length()); }
#vulnerable code public void testZipArchiveCreation() throws Exception { // Archive final File output = new File(dir, "bla.zip"); final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); { final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out); os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml")); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml")); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); } // Unarchive the same List results = new ArrayList(); { final InputStream is = new FileInputStream(output); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); File result = File.createTempFile("dir-result", ""); result.delete(); result.mkdir(); ZipArchiveEntry entry = null; while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) { File outfile = new File(result.getCanonicalPath() + "/result/" + entry.getName()); outfile.getParentFile().mkdirs(); OutputStream out = new FileOutputStream(outfile); IOUtils.copy(in, out); out.close(); results.add(outfile); } in.close(); } assertEquals(results.size(), 2); File result = (File)results.get(0); assertEquals(file1.length(), result.length()); result = (File)results.get(1); assertEquals(file2.length(), result.length()); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testDetection() throws Exception { final ArchiveStreamFactory factory = new ArchiveStreamFactory(); final ArchiveInputStream ar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.ar").getFile())))); assertNotNull(ar); assertTrue(ar instanceof ArArchiveInputStream); final ArchiveInputStream tar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.tar").getFile())))); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); final ArchiveInputStream zip = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.zip").getFile())))); assertNotNull(zip); assertTrue(zip instanceof ZipArchiveInputStream); final ArchiveInputStream jar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.jar").getFile())))); assertNotNull(jar); assertTrue(jar instanceof ZipArchiveInputStream); final ArchiveInputStream cpio = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.cpio").getFile())))); assertNotNull(cpio); assertTrue(cpio instanceof CpioArchiveInputStream); // final ArchiveInputStream tgz = factory.createArchiveInputStream( // new BufferedInputStream(new FileInputStream( // new File(getClass().getClassLoader().getResource("bla.tgz").getFile())))); // assertTrue(tgz instanceof TarArchiveInputStream); }
#vulnerable code public void testDetection() throws Exception { final ArchiveStreamFactory factory = new ArchiveStreamFactory(); final ArchiveInputStream ar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.ar").getFile())))); assertNotNull(ar); assertTrue(ar instanceof ArArchiveInputStream); final ArchiveInputStream tar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.tar").getFile())))); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); final ArchiveInputStream zip = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.zip").getFile())))); assertNotNull(zip); assertTrue(zip instanceof ZipArchiveInputStream); final ArchiveInputStream jar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.jar").getFile())))); assertNotNull(jar); assertTrue(jar instanceof JarArchiveInputStream); final ArchiveInputStream cpio = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.cpio").getFile())))); assertNotNull(cpio); assertTrue(cpio instanceof CpioArchiveInputStream); // final ArchiveInputStream tgz = factory.createArchiveInputStream( // new BufferedInputStream(new FileInputStream( // new File(getClass().getClassLoader().getResource("bla.tgz").getFile())))); // assertTrue(tgz instanceof TarArchiveInputStream); } #location 28 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public InputStream compress(InputStream input) throws CompressException { FileOutputStream outputStream = null; FileOutputStream tempFileOutputStream = null; try { File temp = File.createTempFile("commons_","jkt"); tempFileOutputStream = new FileOutputStream(temp); compressTo(input, tempFileOutputStream); return new FileInputStream(temp); } catch (IOException e) { throw new CompressException("An IO Exception has occured", e); } finally { try { if(tempFileOutputStream != null) { tempFileOutputStream.close(); } if(outputStream != null) { outputStream.close(); } } catch (IOException e) { throw new CompressException("An IO Exception occured while closing the streams", e); } } }
#vulnerable code public InputStream compress(InputStream input) throws CompressException { FileOutputStream outputStream = null; FileOutputStream tempFileOutputStream = null; try { File temp = File.createTempFile("commons_","jkt"); tempFileOutputStream = new FileOutputStream(temp); compressTo(input, tempFileOutputStream); return new FileInputStream(temp); } catch (IOException e) { throw new CompressException("An IO Exception has occured", e); } finally { try { tempFileOutputStream.close(); outputStream.close(); } catch (IOException e) { throw new CompressException("An IO Exception occured while closing the streams", e); } } } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testCBZip2InputStreamClose() throws Exception { final InputStream input = getInputStream( "asf-logo-huge.tar.bz2" ); final File outputFile = getOutputFile( ".tar.bz2" ); final OutputStream output = new FileOutputStream( outputFile ); CompressUtils.copy( input, output ); IOUtils.closeQuietly( input ); IOUtils.closeQuietly( output ); assertTrue( "Check output file exists." , outputFile.exists() ); final InputStream input2 = new FileInputStream( outputFile ); final InputStream packedInput = getPackedInput( input2 ); IOUtils.closeQuietly( packedInput ); try { input2.read(); assertTrue("Source input stream is still opened.", false); } catch ( Exception e ) { // Read closed stream. } forceDelete( outputFile ); }
#vulnerable code public void testCBZip2InputStreamClose() throws Exception { final InputStream input = getInputStream( "asf-logo-huge.tar.bz2" ); final File outputFile = getOutputFile( ".tar.bz2" ); final OutputStream output = new FileOutputStream( outputFile ); CompressUtils.copy( input, output ); shutdownStream( input ); shutdownStream( output ); assertTrue( "Check output file exists." , outputFile.exists() ); final InputStream input2 = new FileInputStream( outputFile ); final InputStream packedInput = getPackedInput( input2 ); shutdownStream( packedInput ); try { input2.read(); assertTrue("Source input stream is still opened.", false); } catch ( Exception e ) { // Read closed stream. } forceDelete( outputFile ); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testArUnarchive() throws Exception { final File output = new File(dir, "bla.ar"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out); os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // UnArArchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is)); final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry(); File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); in.close(); is.close(); }
#vulnerable code public void testArUnarchive() throws Exception { final File output = new File(dir, "bla.ar"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out); os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // UnArArchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("ar", is); final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry(); File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); in.close(); is.close(); } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testDetection() throws Exception { final ArchiveStreamFactory factory = new ArchiveStreamFactory(); final ArchiveInputStream ar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.ar").getFile())))); assertNotNull(ar); assertTrue(ar instanceof ArArchiveInputStream); final ArchiveInputStream tar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.tar").getFile())))); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); final ArchiveInputStream zip = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.zip").getFile())))); assertNotNull(zip); assertTrue(zip instanceof ZipArchiveInputStream); final ArchiveInputStream jar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.jar").getFile())))); assertNotNull(jar); assertTrue(jar instanceof ZipArchiveInputStream); final ArchiveInputStream cpio = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.cpio").getFile())))); assertNotNull(cpio); assertTrue(cpio instanceof CpioArchiveInputStream); // final ArchiveInputStream tgz = factory.createArchiveInputStream( // new BufferedInputStream(new FileInputStream( // new File(getClass().getClassLoader().getResource("bla.tgz").getFile())))); // assertTrue(tgz instanceof TarArchiveInputStream); }
#vulnerable code public void testDetection() throws Exception { final ArchiveStreamFactory factory = new ArchiveStreamFactory(); final ArchiveInputStream ar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.ar").getFile())))); assertNotNull(ar); assertTrue(ar instanceof ArArchiveInputStream); final ArchiveInputStream tar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.tar").getFile())))); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); final ArchiveInputStream zip = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.zip").getFile())))); assertNotNull(zip); assertTrue(zip instanceof ZipArchiveInputStream); final ArchiveInputStream jar = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.jar").getFile())))); assertNotNull(jar); assertTrue(jar instanceof JarArchiveInputStream); final ArchiveInputStream cpio = factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( new File(getClass().getClassLoader().getResource("bla.cpio").getFile())))); assertNotNull(cpio); assertTrue(cpio instanceof CpioArchiveInputStream); // final ArchiveInputStream tgz = factory.createArchiveInputStream( // new BufferedInputStream(new FileInputStream( // new File(getClass().getClassLoader().getResource("bla.tgz").getFile())))); // assertTrue(tgz instanceof TarArchiveInputStream); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testJarUnarchiveAll() throws Exception { final File input = getFile("bla.jar"); final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("jar", is); ArchiveEntry entry = in.getNextEntry(); while (entry != null) { File archiveEntry = new File(dir, entry.getName()); archiveEntry.getParentFile().mkdirs(); if(entry.isDirectory()){ archiveEntry.mkdir(); entry = in.getNextEntry(); continue; } OutputStream out = new FileOutputStream(archiveEntry); IOUtils.copy(in, out); out.close(); entry = in.getNextEntry(); } in.close(); is.close(); }
#vulnerable code public void testJarUnarchiveAll() throws Exception { final File input = getFile("bla.jar"); final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("jar", is); ArchiveEntry entry = in.getNextEntry(); while (entry != null) { File archiveEntry = new File(dir, entry.getName()); archiveEntry.getParentFile().mkdirs(); if(entry.isDirectory()){ archiveEntry.mkdir(); entry = in.getNextEntry(); continue; } OutputStream out = new FileOutputStream(archiveEntry); IOUtils.copy(in, out); out.close(); entry = in.getNextEntry(); } in.close(); } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testTarArchiveLongNameCreation() throws Exception { String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml"; byte[] bytes = name.getBytes(); assertEquals(bytes.length, 99); final File output = new File(dir, "bla.tar"); final File file1 = getFile("test1.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out); final TarArchiveEntry entry = new TarArchiveEntry(name); entry.setModTime(0); entry.setSize(file1.length()); entry.setUserId(0); entry.setGroupId(0); entry.setUserName("avalon"); entry.setGroupName("excalibur"); entry.setMode(0100000); os.putArchiveEntry(entry); FileInputStream in = new FileInputStream(file1); IOUtils.copy(in, os); os.closeArchiveEntry(); os.close(); out.close(); in.close(); ArchiveOutputStream os2 = null; try { String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml"; final File output2 = new File(dir, "bla.tar"); final OutputStream out2 = new FileOutputStream(output2); os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2); final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName); entry2.setModTime(0); entry2.setSize(file1.length()); entry2.setUserId(0); entry2.setGroupId(0); entry2.setUserName("avalon"); entry2.setGroupName("excalibur"); entry2.setMode(0100000); os.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file1), os2); } catch(IOException e) { assertTrue(true); } finally { if (os2 != null){ os2.closeArchiveEntry(); os2.close(); } } }
#vulnerable code public void testTarArchiveLongNameCreation() throws Exception { String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml"; byte[] bytes = name.getBytes(); assertEquals(bytes.length, 99); final File output = new File(dir, "bla.tar"); final File file1 = getFile("test1.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out); final TarArchiveEntry entry = new TarArchiveEntry(name); entry.setModTime(0); entry.setSize(file1.length()); entry.setUserId(0); entry.setGroupId(0); entry.setUserName("avalon"); entry.setGroupName("excalibur"); entry.setMode(0100000); os.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.close(); ArchiveOutputStream os2 = null; try { String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml"; final File output2 = new File(dir, "bla.tar"); final OutputStream out2 = new FileOutputStream(output2); os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2); final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName); entry2.setModTime(0); entry2.setSize(file1.length()); entry2.setUserId(0); entry2.setGroupId(0); entry2.setUserName("avalon"); entry2.setGroupName("excalibur"); entry2.setMode(0100000); os.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file1), os2); } catch(IOException e) { assertTrue(true); } finally { if (os2 != null){ os2.closeArchiveEntry(); } } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testArUnarchive() throws Exception { final File output = new File(dir, "bla.ar"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out); os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // UnArArchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("ar", is); final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry(); File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); in.close(); is.close(); }
#vulnerable code public void testArUnarchive() throws Exception { final File output = new File(dir, "bla.ar"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out); os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); } // UnArArchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("ar", is); final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry(); File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); in.close(); } #location 31 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testGzipCreation() throws Exception { final File input = getFile("test1.xml"); final File output = new File(dir, "test1.xml.gz"); final OutputStream out = new FileOutputStream(output); final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out); IOUtils.copy(new FileInputStream(input), cos); cos.close(); }
#vulnerable code public void testGzipCreation() throws Exception { final File output = new File(dir, "bla.gz"); final File file1 = new File(getClass().getClassLoader().getResource("test1.xml").getFile()); final OutputStream out = new FileOutputStream(output); CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out); IOUtils.copy(new FileInputStream(file1), cos); cos.close(); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBzip2Unarchive() throws Exception { final File input = getFile("bla.txt.bz2"); final File output = new File(dir, "bla.txt"); final InputStream is = new FileInputStream(input); final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is); FileOutputStream os = new FileOutputStream(output); IOUtils.copy(in, os); is.close(); os.close(); }
#vulnerable code public void testBzip2Unarchive() throws Exception { final File input = getFile("bla.txt.bz2"); final File output = new File(dir, "bla.txt"); final InputStream is = new FileInputStream(input); final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is); IOUtils.copy(in, new FileOutputStream(output)); in.close(); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected File createArchive(String archivename) throws Exception { ArchiveOutputStream out = null; OutputStream stream = null; try { archive = File.createTempFile("test", "." + archivename); archiveList = new ArrayList(); stream = new FileOutputStream(archive); out = factory.createArchiveOutputStream(archivename, stream); final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final File file3 = getFile("test3.xml"); final File file4 = getFile("test4.xml"); final File file5 = getFile("test.txt"); final File file6 = getFile("test with spaces.txt"); addArchiveEntry(out, "testdata/test1.xml", file1); addArchiveEntry(out, "testdata/test2.xml", file2); addArchiveEntry(out, "test/test3.xml", file3); addArchiveEntry(out, "bla/test4.xml", file4); addArchiveEntry(out, "bla/test5.xml", file4); addArchiveEntry(out, "bla/blubber/test6.xml", file4); addArchiveEntry(out, "test.txt", file5); addArchiveEntry(out, "something/bla", file6); addArchiveEntry(out, "test with spaces.txt", file6); return archive; } finally { if (out != null) { out.close(); } else if (stream != null) { stream.close(); } } }
#vulnerable code protected File createArchive(String archivename) throws Exception { ArchiveOutputStream out = null; OutputStream stream = null; try { archive = File.createTempFile("test", "." + archivename); stream = new FileOutputStream(archive); out = new ArchiveStreamFactory().createArchiveOutputStream( archivename, stream); final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final File file3 = getFile("test3.xml"); final File file4 = getFile("test4.xml"); final File file5 = getFile("test.txt"); final File file6 = getFile("test with spaces.txt"); ZipArchiveEntry entry = new ZipArchiveEntry("testdata/test1.xml"); entry.setSize(file1.length()); out.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file1), out); out.closeArchiveEntry(); entry = new ZipArchiveEntry("testdata/test2.xml"); entry.setSize(file2.length()); out.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file2), out); out.closeArchiveEntry(); entry = new ZipArchiveEntry("test/test3.xml"); entry.setSize(file3.length()); out.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file3), out); out.closeArchiveEntry(); entry = new ZipArchiveEntry("bla/test4.xml"); entry.setSize(file4.length()); out.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file4), out); out.closeArchiveEntry(); entry = new ZipArchiveEntry("bla/test5.xml"); entry.setSize(file4.length()); out.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file4), out); out.closeArchiveEntry(); entry = new ZipArchiveEntry("bla/blubber/test6.xml"); entry.setSize(file4.length()); out.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file4), out); out.closeArchiveEntry(); entry = new ZipArchiveEntry("test.txt"); entry.setSize(file5.length()); out.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file5), out); out.closeArchiveEntry(); entry = new ZipArchiveEntry("something/bla"); entry.setSize(file6.length()); out.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file6), out); out.closeArchiveEntry(); entry = new ZipArchiveEntry("test with spaces.txt"); entry.setSize(file6.length()); out.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file6), out); out.closeArchiveEntry(); return archive; } finally { if (out != null) { out.close(); } else if (stream != null) { stream.close(); } } } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); CpioArchiveEntry entry = new CpioArchiveEntry("test1.xml", file1.length()); entry.setMode(CpioConstants.C_ISREG); os.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); entry = new CpioArchiveEntry("test2.xml", file2.length()); entry.setMode(CpioConstants.C_ISREG); os.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // Unarchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); Map result = new HashMap(); ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); result.put(entry.getName(), target); } in.close(); is.close(); int lineSepLength = System.getProperty("line.separator").length(); File t = (File)result.get("test1.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 72 + 4 * lineSepLength, t.length()); t = (File)result.get("test2.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 73 + 5 * lineSepLength, t.length()); }
#vulnerable code public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // Unarchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); Map result = new HashMap(); ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); result.put(entry.getName(), target); } in.close(); is.close(); int lineSepLength = System.getProperty("line.separator").length(); File t = (File)result.get("test1.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 72 + 4 * lineSepLength, t.length()); t = (File)result.get("test2.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 73 + 5 * lineSepLength, t.length()); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBzipCreation() throws Exception { final File input = getFile("test.txt"); final File output = new File(dir, "test.txt.bz2"); final OutputStream out = new FileOutputStream(output); final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out); FileInputStream in = new FileInputStream(input); IOUtils.copy(in, cos); cos.close(); in.close(); }
#vulnerable code public void testBzipCreation() throws Exception { final File input = getFile("test.txt"); final File output = new File(dir, "test.txt.bz2"); final OutputStream out = new FileOutputStream(output); final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out); IOUtils.copy(new FileInputStream(input), cos); cos.close(); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testArDelete() throws Exception { final File output = new File(dir, "bla.ar"); { // create final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out); os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } assertEquals(282, output.length()); final File output2 = new File(dir, "bla2.ar"); int copied = 0; int deleted = 0; { // remove all but one file final InputStream is = new FileInputStream(output); final OutputStream os = new FileOutputStream(output2); final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os); final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is)); while(true) { final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry(); if (entry == null) { break; } if ("test1.xml".equals(entry.getName())) { aos.putArchiveEntry(entry); IOUtils.copy(ais, aos); aos.closeArchiveEntry(); copied++; } else { IOUtils.copy(ais, new ByteArrayOutputStream()); deleted++; } } ais.close(); aos.close(); is.close(); os.close(); } assertEquals(1, copied); assertEquals(1, deleted); assertEquals(144, output2.length()); long files = 0; long sum = 0; { final InputStream is = new FileInputStream(output2); final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is)); while(true) { final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry(); if (entry == null) { break; } IOUtils.copy(ais, new ByteArrayOutputStream()); sum += entry.getLength(); files++; } ais.close(); is.close(); } assertEquals(1, files); assertEquals(76, sum); }
#vulnerable code public void testArDelete() throws Exception { final File output = new File(dir, "bla.ar"); { // create final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out); os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } final File output2 = new File(dir, "bla2.ar"); { // remove all but one file final InputStream is = new FileInputStream(output); final OutputStream os = new FileOutputStream(output2); final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os); final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is)); while(true) { final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry(); if (entry == null) { break; } if ("test1.xml".equals(entry.getName())) { aos.putArchiveEntry(entry); IOUtils.copy(ais, aos); } else { IOUtils.copy(ais, new ByteArrayOutputStream()); } } ais.close(); aos.close(); is.close(); os.close(); } long sum = 0; { final InputStream is = new FileInputStream(output2); final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is)); while(true) { final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry(); if (entry == null) { break; } IOUtils.copy(ais, new ByteArrayOutputStream()); sum += entry.getLength(); } ais.close(); is.close(); } assertEquals(76, sum); } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBzip2Unarchive() throws Exception { final File input = getFile("bla.txt.bz2"); final File output = new File(dir, "bla.txt"); final InputStream is = new FileInputStream(input); final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is); IOUtils.copy(in, new FileOutputStream(output)); in.close(); }
#vulnerable code public void testBzip2Unarchive() throws Exception { final File output = new File(dir, "test-entpackt.txt"); System.out.println(dir); final File input = new File(getClass().getClassLoader().getResource("bla.txt.bz2").getFile()); final InputStream is = new FileInputStream(input); //final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is); final CompressorInputStream in = new BZip2CompressorInputStream(is); IOUtils.copy(in, new FileOutputStream(output)); in.close(); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // Unarchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); Map result = new HashMap(); ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); result.put(entry.getName(), target); } in.close(); int lineSepLength = System.getProperty("line.separator").length(); File t = (File)result.get("test1.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 72 + 4 * lineSepLength, t.length()); t = (File)result.get("test2.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 73 + 5 * lineSepLength, t.length()); }
#vulnerable code public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); } // Unarchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry(); File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); in.close(); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testZipArchiveCreation() throws Exception { // Archive final File output = new File(dir, "bla.zip"); final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); ArchiveOutputStream os = null; try { os = new ArchiveStreamFactory() .createArchiveOutputStream("zip", out); os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml")); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml")); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } else { out.close(); } } // Unarchive the same List results = new ArrayList(); final InputStream is = new FileInputStream(output); ArchiveInputStream in = null; try { in = new ArchiveStreamFactory() .createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) { File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName()); outfile.getParentFile().mkdirs(); OutputStream o = new FileOutputStream(outfile); try { IOUtils.copy(in, o); } finally { o.close(); } results.add(outfile); } } finally { if (in != null) { in.close(); } else { is.close(); } } assertEquals(results.size(), 2); File result = (File)results.get(0); assertEquals(file1.length(), result.length()); result = (File)results.get(1); assertEquals(file2.length(), result.length()); }
#vulnerable code public void testZipArchiveCreation() throws Exception { // Archive final File output = new File(dir, "bla.zip"); final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); { final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out); os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml")); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml")); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); } // Unarchive the same List results = new ArrayList(); { final InputStream is = new FileInputStream(output); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); File result = File.createTempFile("dir-result", ""); result.delete(); result.mkdir(); ZipArchiveEntry entry = null; while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) { File outfile = new File(result.getCanonicalPath() + "/result/" + entry.getName()); outfile.getParentFile().mkdirs(); OutputStream out = new FileOutputStream(outfile); IOUtils.copy(in, out); out.close(); results.add(outfile); } in.close(); } assertEquals(results.size(), 2); File result = (File)results.get(0); assertEquals(file1.length(), result.length()); result = (File)results.get(1); assertEquals(file2.length(), result.length()); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // Unarchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); Map result = new HashMap(); ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); result.put(entry.getName(), target); } in.close(); is.close(); int lineSepLength = System.getProperty("line.separator").length(); File t = (File)result.get("test1.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 72 + 4 * lineSepLength, t.length()); t = (File)result.get("test2.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 73 + 5 * lineSepLength, t.length()); }
#vulnerable code public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // Unarchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); Map result = new HashMap(); ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); result.put(entry.getName(), target); } in.close(); int lineSepLength = System.getProperty("line.separator").length(); File t = (File)result.get("test1.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 72 + 4 * lineSepLength, t.length()); t = (File)result.get("test2.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 73 + 5 * lineSepLength, t.length()); } #location 36 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public InputStream compress(InputStream input) throws CompressException { FileOutputStream outputStream = null; FileOutputStream tempFileOutputStream = null; try { File temp = File.createTempFile("commons_","jkt"); tempFileOutputStream = new FileOutputStream(temp); compressTo(input, tempFileOutputStream); return new FileInputStream(temp); } catch (IOException e) { throw new CompressException("An IO Exception has occured", e); } finally { try { if(tempFileOutputStream != null) { tempFileOutputStream.close(); } if(outputStream != null) { outputStream.close(); } } catch (IOException e) { throw new CompressException("An IO Exception occured while closing the streams", e); } } }
#vulnerable code public InputStream compress(InputStream input) throws CompressException { FileOutputStream outputStream = null; FileOutputStream tempFileOutputStream = null; try { File temp = File.createTempFile("commons_","jkt"); tempFileOutputStream = new FileOutputStream(temp); compressTo(input, tempFileOutputStream); return new FileInputStream(temp); } catch (IOException e) { throw new CompressException("An IO Exception has occured", e); } finally { try { tempFileOutputStream.close(); outputStream.close(); } catch (IOException e) { throw new CompressException("An IO Exception occured while closing the streams", e); } } } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testGzipUnarchive() throws Exception { final File input = getFile("bla.tgz"); final File output = new File(dir, "bla.tar"); final InputStream is = new FileInputStream(input); final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("gz", is); FileOutputStream out = new FileOutputStream(output); IOUtils.copy(in, out); in.close(); is.close(); out.close(); }
#vulnerable code public void testGzipUnarchive() throws Exception { final File input = getFile("bla.tgz"); final File output = new File(dir, "bla.tar"); final InputStream is = new FileInputStream(input); final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("gz", is); IOUtils.copy(in, new FileOutputStream(output)); in.close(); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // instead of this, the statement below is introduced: handle(request, response, authentication); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getBean(SaService.class).userForClient())); clearAuthenticationAttributes(request); //log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser()); }
#vulnerable code public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // instead of this, the statement below is introduced: handle(request, response, authentication); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getLoggedInUser().getUserDto())); clearAuthenticationAttributes(request); log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser().getUserDto()); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @UserEditPermission @Transactional(propagation=Propagation.REQUIRED, readOnly=false) public String changePassword(U user, @Valid ChangePasswordForm changePasswordForm) { log.debug("Changing password for user: " + user); // Get the old password of the logged in user (logged in user may be an ADMIN) UserDto<ID> currentUser = LemonUtils.currentUser(); U loggedIn = userRepository.findById(currentUser.getId()).get(); String oldPassword = loggedIn.getPassword(); // checks LemonUtils.ensureFound(user); LemonUtils.validate("changePasswordForm.oldPassword", passwordEncoder.matches(changePasswordForm.getOldPassword(), oldPassword), "com.naturalprogrammer.spring.wrong.password").go(); // sets the password user.setPassword(passwordEncoder.encode(changePasswordForm.getPassword())); user.setCredentialsUpdatedMillis(System.currentTimeMillis()); userRepository.save(user); // // after successful commit // LemonUtils.afterCommit(() -> { // // UserDto<ID> currentUser = LemonUtils.getSpringUser(); // //// if (currentUser.getId().equals(user.getId())) { // if current-user's password changed, //// //// log.debug("Logging out ..."); //// LemonUtils.logOut(); // log him out //// } // }); // log.debug("Changed password for user: " + user); return user.toUserDto().getUsername(); }
#vulnerable code @UserEditPermission @Transactional(propagation=Propagation.REQUIRED, readOnly=false) public String changePassword(U user, @Valid ChangePasswordForm changePasswordForm) { log.debug("Changing password for user: " + user); // Get the old password of the logged in user (logged in user may be an ADMIN) SpringUser<ID> springUser = LemonUtils.getSpringUser(); U loggedIn = userRepository.findById(springUser.getId()).get(); String oldPassword = loggedIn.getPassword(); // checks LemonUtils.ensureFound(user); LemonUtils.validate("changePasswordForm.oldPassword", passwordEncoder.matches(changePasswordForm.getOldPassword(), oldPassword), "com.naturalprogrammer.spring.wrong.password").go(); // sets the password user.setPassword(passwordEncoder.encode(changePasswordForm.getPassword())); user.setCredentialsUpdatedMillis(System.currentTimeMillis()); userRepository.save(user); // // after successful commit // LemonUtils.afterCommit(() -> { // // SpringUser<ID> currentUser = LemonUtils.getSpringUser(); // //// if (currentUser.getId().equals(user.getId())) { // if current-user's password changed, //// //// log.debug("Logging out ..."); //// LemonUtils.logOut(); // log him out //// } // }); // log.debug("Changed password for user: " + user); return user.toSpringUser().getUsername(); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Transactional(propagation=Propagation.REQUIRED, readOnly=false) public SpringUser<ID> loginWithNonce(@Valid NonceForm<ID> nonce, HttpServletResponse response) { U user = userRepository.findById(nonce.getUserId()) .orElseThrow(MultiErrorException.supplier( "com.naturalprogrammer.spring.userNotFound")); if (user.getNonce().equals(nonce.getNonce())) { user.setNonce(null); userRepository.save(user); jwtService.addJwtAuthHeader(response, user.toSpringUser().getUsername(), properties.getJwt().getExpirationMilli()); return user.toSpringUser(); } throw MultiErrorException.supplier("com.naturalprogrammer.spring.invalidNonce").get(); }
#vulnerable code @Transactional(propagation=Propagation.REQUIRED, readOnly=false) public SpringUser<ID> loginWithNonce(@Valid NonceForm<ID> nonce, HttpServletResponse response) { U user = userRepository.findById(nonce.getUserId()) .orElseThrow(MultiErrorException.supplier( "com.naturalprogrammer.spring.userNotFound")); if (user.getNonce().equals(nonce.getNonce())) { user.setNonce(null); userRepository.save(user); jwtService.addJwtAuthHeader(response, user.getId().toString(), properties.getJwt().getExpirationMilli()); return user.toSpringUser(); } throw MultiErrorException.supplier("com.naturalprogrammer.spring.invalidNonce").get(); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) { UserDto<ID> currentUser = LemonUtils.currentUser(); String shortLivedAuthToken = jwtService.createToken( JwtService.AUTH_AUDIENCE, currentUser.getUsername(), (long) properties.getJwt().getShortLivedMillis()); String targetUrl = LemonUtils.fetchCookie(request, HttpCookieOAuth2AuthorizationRequestRepository.LEMON_REDIRECT_URI_COOKIE_PARAM_NAME) .map(Cookie::getValue) .orElse(properties.getOauth2AuthenticationSuccessUrl()); HttpCookieOAuth2AuthorizationRequestRepository.deleteCookies(request, response); return targetUrl + shortLivedAuthToken; // // return properties.getApplicationUrl() // + "/social-login-success?token=" // + shortLivedAuthToken; }
#vulnerable code @Override protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) { SpringUser<ID> springUser = LemonUtils.getSpringUser(); String shortLivedAuthToken = jwtService.createToken( JwtService.AUTH_AUDIENCE, springUser.getUsername(), (long) properties.getJwt().getShortLivedMillis()); String targetUrl = LemonUtils.fetchCookie(request, HttpCookieOAuth2AuthorizationRequestRepository.LEMON_REDIRECT_URI_COOKIE_PARAM_NAME) .map(Cookie::getValue) .orElse(properties.getOauth2AuthenticationSuccessUrl()); HttpCookieOAuth2AuthorizationRequestRepository.deleteCookies(request, response); return targetUrl + shortLivedAuthToken; // // return properties.getApplicationUrl() // + "/social-login-success?token=" // + shortLivedAuthToken; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @PreAuthorize("hasPermission(#user, 'edit')") @Validated(BaseUser.UpdateValidation.class) @Transactional(propagation=Propagation.REQUIRED, readOnly=false) public U updateUser(U user, @Valid U updatedUser) { SaUtil.validate(user != null, "userNotFound"); SaUtil.validateVersion(user, updatedUser); U loggedIn = SaUtil.getLoggedInUser(); updateUserFields(user, updatedUser, loggedIn); userRepository.save(user); return userForClient(loggedIn); }
#vulnerable code @PreAuthorize("hasPermission(#user, 'edit')") @Validated(BaseUser.UpdateValidation.class) @Transactional(propagation=Propagation.REQUIRED, readOnly=false) public U updateUser(U user, @Valid U updatedUser) { SaUtil.validate(user != null, "userNotFound"); user.setName(updatedUser.getName()); if (user.isRolesEditable()) { Set<String> roles = user.getRoles(); if (updatedUser.isUnverified()) roles.add(Role.UNVERIFIED); else roles.remove(Role.UNVERIFIED); if (updatedUser.isAdmin()) roles.add(Role.ADMIN); else roles.remove(Role.ADMIN); if (updatedUser.isBlocked()) roles.add(Role.BLOCKED); else roles.remove(Role.BLOCKED); } //user.setVersion(updatedUser.getVersion()); userRepository.save(user); U loggedIn = SaUtil.getLoggedInUser(); if (loggedIn.equals(user)) { loggedIn.setName(user.getName()); loggedIn.setRoles(user.getRoles()); } return userForClient(loggedIn); } #location 32 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String args[]) { System.out.println(test()); }
#vulnerable code public static void main(String args[]) throws IOException, ClassNotFoundException { File obfuscatedFile; JarFile jarFile = new JarFile(obfuscatedFile = new File("helloWorld-obf.jar")); Enumeration<JarEntry> e = jarFile.entries(); URL[] urls = {new URL("jar:file:" + obfuscatedFile.getAbsolutePath() + "!/")}; URLClassLoader cl = URLClassLoader.newInstance(urls); Class c = null; while (e.hasMoreElements()) { JarEntry je = e.nextElement(); if (je.isDirectory() || !je.getName().endsWith(".class")) { continue; } // -6 because of .class String className = je.getName().substring(0, je.getName().length() - 6); className = className.replace('/', '.'); System.out.println(className); if (className.equals("Test")) { c = cl.loadClass(className); } } Objects.requireNonNull(c); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void printState (PrintStream out) { Alphabet alphabet = instances.getDataAlphabet(); out.println ("#doc pos typeindex type topic"); for (int doc = 0; doc < topics.size(); doc++) { FeatureSequence tokenSequence = (FeatureSequence) instances.get(doc).getData(); FeatureSequence topicSequence = (FeatureSequence) instances.get(doc).getData(); for (int token = 0; token < topicSequence.getLength(); token++) { int type = tokenSequence.getIndexAtPosition(token); int topic = topicSequence.getIndexAtPosition(token); out.print(doc); out.print(' '); out.print(token); out.print(' '); out.print(type); out.print(' '); out.print(alphabet.lookupObject(type)); out.print(' '); out.print(topic); out.println(); } } }
#vulnerable code public void printState (PrintStream out) { Alphabet a = instances.getDataAlphabet(); out.println ("#doc pos typeindex type topic"); for (int di = 0; di < topics.length; di++) { FeatureSequence fs = (FeatureSequence) instances.get(di).getData(); for (int token = 0; token < topics[di].length; token++) { int type = fs.getIndexAtPosition(token); out.print(di); out.print(' '); out.print(token); out.print(' '); out.print(type); out.print(' '); out.print(a.lookupObject(type)); out.print(' '); out.print(topics[di][token]); out.println(); } } } #location 11 #vulnerability type NULL_DEREFERENCE