input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Override public List<net.runelite.deob.Method> getMethods() { ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup(); ClassFile otherClass = group.findClass(method.getClassEntry().getName()); if (otherClass == null) return new ArrayList<>(); // not our class // look up this method in this class and anything that inherits from it List<net.runelite.deob.Method> list = new ArrayList<>(); findMethodFromClass(list, otherClass); return list; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<net.runelite.deob.Method> getMethods() { return myMethods != null ? myMethods : Arrays.asList(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test1() throws IOException { File file = folder.newFile(); Store store = new Store(); IndexFile index = new IndexFile(store, 5, file); IndexEntry entry = new IndexEntry(index, 7, 8, 9); index.write(entry); IndexEntry entry2 = index.read(7); Assert.assertEquals(entry, entry2); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void test1() throws IOException { File file = folder.newFile(); Store store = new Store(folder.getRoot()); IndexFile index = new IndexFile(store, 5, file); IndexEntry entry = new IndexEntry(index, 7, 8, 9); index.write(entry); IndexEntry entry2 = index.read(7); Assert.assertEquals(entry, entry2); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void lookup() { ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup(); ClassFile otherClass = group.findClass(method.getClassEntry().getName()); if (otherClass == null) return; // not our class net.runelite.deob.Method other = otherClass.findMethodDeepStatic(method.getNameAndType()); assert other != null; List<net.runelite.deob.Method> list = new ArrayList<>(); list.add(other); myMethods = list; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void lookup() { myMethod = lookupMethod(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<net.runelite.deob.Method> getMethods() { ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup(); ClassFile otherClass = group.findClass(method.getClassEntry().getName()); if (otherClass == null) return new ArrayList<>(); // not our class net.runelite.deob.Method other = otherClass.findMethod(method.getNameAndType()); assert other != null; List<net.runelite.deob.Method> list = new ArrayList<>(); list.add(other); return list; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<net.runelite.deob.Method> getMethods() { return myMethods != null ? myMethods : Arrays.asList(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run(ClassGroup one, ClassGroup two) { groupOne = one; groupTwo = two; // Execution eone = new Execution(one); // eone.setBuildGraph(true); // eone.setFollowInvokes(false); // eone.populateInitialMethods(); // List<Method> initial1 = eone.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList()); // eone.run(); // // Execution etwo = new Execution(two); // etwo.setBuildGraph(true); // etwo.setFollowInvokes(false); // etwo.populateInitialMethods(); // List<Method> initial2 = etwo.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList()); // etwo.run(); // // assert initial1.size() == initial2.size(); // // for (int i = 0; i < initial1.size(); ++i) // { // Method m1 = initial1.get(i), m2 = initial2.get(i); // // assert m1.getName().equals(m2.getName()); // // objMap.put(m1, m2); // } process( one.findClass("class143").findMethod("method3014"), two.findClass("class143").findMethod("method2966") ); for (;;) { Optional next = objMap.keySet().stream() .filter(m -> !processed.contains(m)) .findAny(); if (!next.isPresent()) break; Method m = (Method) next.get(); Method m2 = (Method) objMap.get(m); if (m.getCode() == null || m2.getCode() == null) { processed.add(m); continue; } System.out.println("Scanning " + m.getMethods().getClassFile().getName() + "." + m.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName()); process(m, m2); processed.add(m); } for (Entry<Object, Object> e : objMap.entrySet()) { Method m1 = (Method) e.getKey(); Method m2 = (Method) e.getValue(); System.out.println("FINAL " + m1.getMethods().getClassFile().getName() + "." + m1.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName()); } System.out.println("done count " + objMap.size()); } #location 32 #vulnerability type NULL_DEREFERENCE
#fixed code public void run(ClassGroup one, ClassGroup two) { groupOne = one; groupTwo = two; Execution eone = new Execution(one); eone.setBuildGraph(true); eone.setFollowInvokes(false); eone.populateInitialMethods(); List<Method> initial1 = eone.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList()); eone.run(); Execution etwo = new Execution(two); etwo.setBuildGraph(true); etwo.setFollowInvokes(false); etwo.populateInitialMethods(); List<Method> initial2 = etwo.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList()); etwo.run(); assert initial1.size() == initial2.size(); for (int i = 0; i < initial1.size(); ++i) { Method m1 = initial1.get(i), m2 = initial2.get(i); assert m1.getName().equals(m2.getName()); objMap.put(m1, m2); } // process( // one.findClass("class143").findMethod("method3014"), // two.findClass("class143").findMethod("method2966") // ); for (;;) { Optional next = objMap.keySet().stream() .filter(m -> !processed.contains(m)) .findAny(); if (!next.isPresent()) break; Method m = (Method) next.get(); Method m2 = (Method) objMap.get(m); if (m.getCode() == null || m2.getCode() == null) { processed.add(m); continue; } System.out.println("Scanning " + m.getMethods().getClassFile().getName() + "." + m.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName()); process(m, m2); processed.add(m); } for (Entry<Object, Object> e : objMap.entrySet()) { Method m1 = (Method) e.getKey(); Method m2 = (Method) e.getValue(); System.out.println("FINAL " + m1.getMethods().getClassFile().getName() + "." + m1.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName()); } System.out.println("done count " + objMap.size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test1() throws IOException { File file = folder.newFile(); Store store = new Store(folder.getRoot()); DataFile df = new DataFile(store, file); int sector = df.write(42, 3, ByteBuffer.wrap("test".getBytes())); byte[] buf = df.read(42, 3, sector, 4); String str = new String(buf); Assert.assertEquals("test", str); file.delete(); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void test1() throws IOException { File file = folder.newFile(); Store store = new Store(folder.getRoot()); DataFile df = new DataFile(store, file); DataFileWriteResult res = df.write(42, 3, ByteBuffer.wrap("test".getBytes()), 0, 0); DataFileReadResult res2 = df.read(42, 3, res.sector, res.compressedLength); byte[] buf = res2.data; String str = new String(buf); Assert.assertEquals("test", str); file.delete(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test2() throws IOException { byte[] b = new byte[1024]; for (int i = 0; i < 1024; ++i) b[i] = (byte) i; File file = folder.newFile(); Store store = new Store(); DataFile df = new DataFile(store, 42, file); int sector = df.write(0x1FFFF, ByteBuffer.wrap(b)); ByteBuffer buf = df.read(0x1FFFF, sector, b.length); Assert.assertArrayEquals(b, buf.array()); file.delete(); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void test2() throws IOException { byte[] b = new byte[1024]; for (int i = 0; i < 1024; ++i) b[i] = (byte) i; File file = folder.newFile(); Store store = new Store(folder.getRoot()); DataFile df = new DataFile(store, 42, file); int sector = df.write(0x1FFFF, ByteBuffer.wrap(b)); ByteBuffer buf = df.read(0x1FFFF, sector, b.length); Assert.assertArrayEquals(b, buf.array()); file.delete(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void lookup() { ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup(); ClassFile otherClass = group.findClass(method.getClassEntry().getName()); if (otherClass == null) return; // not our class // look up this method in this class and anything that inherits from it //List<net.runelite.deob.Method> list = new ArrayList<>(); //findMethodFromClass(list, otherClass); myMethods = Renamer.getVirutalMethods(otherClass.findMethod(method.getNameAndType())); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void lookup() { myMethods = lookupMethods(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<net.runelite.deob.Method> getMethods() { ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup(); ClassFile otherClass = group.findClass(method.getClassEntry().getName()); if (otherClass == null) return new ArrayList<>(); // not our class net.runelite.deob.Method other = otherClass.findMethodDeepStatic(method.getNameAndType()); assert other != null; List<net.runelite.deob.Method> list = new ArrayList<>(); list.add(other); return list; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<net.runelite.deob.Method> getMethods() { return myMethods != null ? myMethods : Arrays.asList(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test() throws IOException { Store store = new Store(new java.io.File("c:/rs/cache")); store.load(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void test() throws IOException { Store store = new Store(new java.io.File("d:/rs/07/cache"));//c:/rs/cache")); store.load(); System.out.println(store); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { for (ClassFile cf : deobfuscated.getClasses()) { Annotations an = cf.getAttributes().getAnnotations(); String obfuscatedName = cf.getName(); Annotation obfuscatedNameAnnotation = an.find(OBFUSCATED_NAME); if (obfuscatedNameAnnotation != null) obfuscatedName = obfuscatedNameAnnotation.getElement().getString(); ClassFile other = vanilla.findClass(obfuscatedName); assert other != null; java.lang.Class implementingClass = injectInterface(cf, other); if (implementingClass == null) continue; for (Field f : cf.getFields().getFields()) { an = f.getAttributes().getAnnotations(); if (an.find(EXPORT) == null) continue; // not an exported field String exportedName = an.find(EXPORT).getElement().getString(); obfuscatedName = an.find(OBFUSCATED_NAME).getElement().getString(); Annotation getterAnnotation = an.find(OBFUSCATED_GETTER); Number getter = null; if (getterAnnotation != null) getter = (Number) getterAnnotation.getElement().getValue().getObject(); // the ob jar is the same as the vanilla so this field must exist in this class. Type obType = toObType(f.getType()); Field otherf = other.findField(new NameAndType(obfuscatedName, obType)); if (otherf == null) otherf = other.findField(new NameAndType(obfuscatedName, obType)); assert otherf != null; assert f.isStatic() == otherf.isStatic(); // ClassFile targetClass = f.isStatic() ? vanilla.findClass("client") : other; // target class for getter java.lang.Class targetApiClass = f.isStatic() ? clientClass : implementingClass; // target api class for getter java.lang.reflect.Method apiMethod = findImportMethodOnApi(targetApiClass, exportedName); if (apiMethod == null) { System.out.println("no api method"); continue; } injectGetter(targetClass, apiMethod, otherf, getter); } for (Method m : cf.getMethods().getMethods()) { an = m.getAttributes().getAnnotations(); if (an == null || an.find(EXPORT) == null) continue; // not an exported method String exportedName = an.find(EXPORT).getElement().getString(); obfuscatedName = an.find(OBFUSCATED_NAME).getElement().getString(); // XXX static methods don't have to be in the same class, so we should have @ObfuscatedClass or something Method otherm = other.findMethod(new NameAndType(obfuscatedName, toObSignature(m.getDescriptor()))); assert otherm != null; } } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public void run() { for (ClassFile cf : deobfuscated.getClasses()) { Annotations an = cf.getAttributes().getAnnotations(); if (an == null) continue; String obfuscatedName = cf.getName(); Annotation obfuscatedNameAnnotation = an.find(OBFUSCATED_NAME); if (obfuscatedNameAnnotation != null) obfuscatedName = obfuscatedNameAnnotation.getElement().getString(); ClassFile other = vanilla.findClass(obfuscatedName); assert other != null; java.lang.Class implementingClass = injectInterface(cf, other); if (implementingClass == null) continue; for (Field f : cf.getFields().getFields()) { an = f.getAttributes().getAnnotations(); if (an.find(EXPORT) == null) continue; // not an exported field String exportedName = an.find(EXPORT).getElement().getString(); obfuscatedName = an.find(OBFUSCATED_NAME).getElement().getString(); Annotation getterAnnotation = an.find(OBFUSCATED_GETTER); Number getter = null; if (getterAnnotation != null) getter = (Number) getterAnnotation.getElement().getValue().getObject(); // the ob jar is the same as the vanilla so this field must exist in this class. Type obType = toObType(f.getType()); Field otherf = other.findField(new NameAndType(obfuscatedName, obType)); assert otherf != null; assert f.isStatic() == otherf.isStatic(); ClassFile targetClass = f.isStatic() ? vanilla.findClass("client") : other; // target class for getter java.lang.Class targetApiClass = f.isStatic() ? clientClass : implementingClass; // target api class for getter java.lang.reflect.Method apiMethod = findImportMethodOnApi(targetApiClass, exportedName); if (apiMethod == null) { System.out.println("no api method"); continue; } injectGetter(targetClass, apiMethod, otherf, getter); } for (Method m : cf.getMethods().getMethods()) { an = m.getAttributes().getAnnotations(); if (an == null || an.find(EXPORT) == null) continue; // not an exported method // XXX static methods can be in any class not just 'other' so the below finding won't work. // XXX static methods can also be totally inlined by the obfuscator and thus removed by the dead code remover, // so exporting them maybe wouldn't work anyway? assert !m.isStatic(); String exportedName = an.find(EXPORT).getElement().getString(); obfuscatedName = an.find(OBFUSCATED_NAME).getElement().getString(); Method otherm; Annotation obfuscatedSignature = an.find(OBFUSCATED_SIGNATURE); String garbage = null; if (obfuscatedSignature != null) { String signatureString = obfuscatedSignature.getElements().get(0).getString(); garbage = obfuscatedSignature.getElements().get(1).getString(); Signature signature = new Signature(signatureString); // parse signature // The obfuscated signature annotation is generated post rename unique, so class // names in the signature match our class names and not theirs, so we toObSignature() it otherm = other.findMethod(new NameAndType(obfuscatedName, toObSignature(signature))); } else { // No obfuscated signature annotation, so the annotation wasn't changed during deobfuscation. // We should be able to just find it normally. otherm = other.findMethod(new NameAndType(obfuscatedName, toObSignature(m.getDescriptor()))); } assert otherm != null; java.lang.reflect.Method apiMethod = findImportMethodOnApi(implementingClass, exportedName); // api method to invoke 'otherm' if (apiMethod == null) { System.out.println("no api method"); continue; } injectInvoker(other, apiMethod, m, otherm, garbage); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ParallelExecutorMapping mapStaticMethods(ClassGroup one, ClassGroup two) { StaticMethodSignatureMapper smsm = new StaticMethodSignatureMapper(); smsm.map(one, two); List<ParallelExecutorMapping> pmes = new ArrayList<>(); for (Method m : smsm.getMap().keySet()) { Collection<Method> methods = smsm.getMap().get(m); ExecutionMapper em = new ExecutionMapper(m, methods); ParallelExecutorMapping mapping = em.run(); mapping.map(mapping.m1, mapping.m2); pmes.add(mapping); } ParallelExecutorMapping finalm = new ParallelExecutorMapping(one, two); for (ParallelExecutorMapping pme : pmes) finalm.merge(pme); return finalm; } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code private ParallelExecutorMapping mapStaticMethods(ClassGroup one, ClassGroup two) { StaticMethodSignatureMapper smsm = new StaticMethodSignatureMapper(); smsm.map(one, two); List<ParallelExecutorMapping> pmes = new ArrayList<>(); for (Method m : smsm.getMap().keySet()) { Collection<Method> methods = smsm.getMap().get(m); ExecutionMapper em = new ExecutionMapper(m, methods); ParallelExecutorMapping mapping = em.run(); if (mapping == null) continue; mapping.map(mapping.m1, mapping.m2); pmes.add(mapping); } ParallelExecutorMapping finalm = new ParallelExecutorMapping(one, two); for (ParallelExecutorMapping pme : pmes) finalm.merge(pme); return finalm; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run(ClassGroup group) { this.group = group; group.buildClassGraph(); execution = new Execution(group); execution.populateInitialMethods(); execution.run(); findUses(); Field f = group.findClass("class41").findField("field1170"); calculate(f); } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void run(ClassGroup group) { this.group = group; group.buildClassGraph(); execution = new Execution(group); execution.populateInitialMethods(); Encryption encr = new Encryption(); execution.setEncryption(encr); execution.run(); encr.doChange(); // findUses(); // // Field f = group.findClass("class41").findField("field1170"); // calculate(f); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { SocksProxy proxy1 = new Socks5(new InetSocketAddress("localhost", 1080)); proxy1.setCredentials(new UsernamePasswordCredentials("socks", "1234")); SocksProxy proxy2 = new Socks5(new InetSocketAddress("localhost", 1081)); proxy2.setCredentials(new UsernamePasswordCredentials("socks", "1234")); SocksProxy proxy3 = new Socks5(new InetSocketAddress("localhost", 1082)); proxy3.setCredentials(new UsernamePasswordCredentials("socks", "1234")); proxy1.setChainProxy(proxy2.setChainProxy(proxy3.setChainProxy(proxy1.copy().setChainProxy( proxy2.copy())))); try { @SuppressWarnings("resource") Socket socket = new SocksSocket(proxy1); socket.connect(new InetSocketAddress("whois.internic.net", 43)); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream); printWriter.print("domain google.com\r\n"); printWriter.flush(); byte[] whoisrecords = new byte[2048]; java.util.List<Byte> bytelist = new ArrayList<>(1024 * 6); int size = 0; while ((size = inputStream.read(whoisrecords)) > 0) { for (int i = 0; i < size; i++) { bytelist.add(whoisrecords[i]); } } System.out.println("size:" + bytelist.size()); byte[] resultbyte = new byte[bytelist.size()]; for (int i = 0; i < resultbyte.length; i++) { resultbyte[i] = bytelist.get(i); } String string = new String(resultbyte); System.out.println(string); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocksException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) { Socket socket = null; InputStream inputStream = null; OutputStream outputStream = null; StringBuffer response = null; byte[] buffer = new byte[2048]; int length = 0; SocksProxy proxy1 = new Socks5(new InetSocketAddress("localhost", 1080)); proxy1.setCredentials(new UsernamePasswordCredentials("socks", "1234")); SocksProxy proxy2 = new Socks5(new InetSocketAddress("localhost", 1081)); proxy2.setCredentials(new UsernamePasswordCredentials("socks", "1234")); SocksProxy proxy3 = new Socks5(new InetSocketAddress("localhost", 1082)); proxy3.setCredentials(new UsernamePasswordCredentials("socks", "1234")); proxy1.setChainProxy(proxy2.setChainProxy(proxy3)); System.out.println("USE proxy:"+proxy1); try { socket = new SocksSocket(proxy1); socket.connect(new InetSocketAddress("whois.internic.net", 43)); inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream); printWriter.print("domain google.com\r\n"); printWriter.flush(); length = 0; response = new StringBuffer(); while ((length = inputStream.read(buffer)) > 0) { response.append(new String(buffer, 0, length)); } System.out.println(response.toString()); } catch (IOException e) { e.printStackTrace(); } finally { ResourceUtil.close(inputStream, outputStream, socket); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { logger.info("Start proxy server at port:{}", bindPort); while (!stop) { try { Socket socket = serverSocket.accept(); socket = processSocketBeforeUse(socket); socket.setSoTimeout(timeout); Session session = new SocksSession(getNextSessionId(), socket, sessions); sessions.put(session.getId(), session); logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress()); try { sessionFilterChain.doFilterChain(session); } catch (InterruptedException e) { session.close(); logger.info(e.getMessage()); continue; } SocksHandler socksHandler = createSocksHandler(); /* initialize socks handler */ socksHandler.setSession(session); initializeSocksHandler(socksHandler); executorService.execute(socksHandler); } catch (IOException e) { // Catches the exception that cause by shutdown method. if (e.getMessage().equals("Socket closed") && stop) { logger.debug("Server shutdown"); return; } logger.debug(e.getMessage(), e); } } } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void run() { logger.info("Start proxy server at port:{}", bindPort); while (!stop) { try { Socket socket = serverSocket.accept(); socket = processSocketBeforeUse(socket); socket.setSoTimeout(timeout); Session session = sessionManager.newSession(socket); logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress()); try { sessionFilterChain.doFilterChain(session); } catch (InterruptedException e) { session.close(); logger.info(e.getMessage()); continue; } SocksHandler socksHandler = createSocksHandler(); /* initialize socks handler */ socksHandler.setSession(session); initializeSocksHandler(socksHandler); executorService.execute(socksHandler); } catch (IOException e) { // Catches the exception that cause by shutdown method. if (e.getMessage().equals("Socket closed") && stop) { logger.debug("Server shutdown"); return; } logger.debug(e.getMessage(), e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { SocksClientSSLUtil sslUtil = SocksClientSSLUtil.loadClassPath("client-ssl.properties"); SocksProxy proxy = new Socks5(new InetSocketAddress("localhost", 1080)); List<SocksMethod> methods = new ArrayList<SocksMethod>(); methods.add(new NoAuthencationRequiredMethod()); proxy.setAcceptableMethods(methods); SocksSocket socket = sslUtil.create(proxy); socket.connect("whois.internic.net", 43); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream); printWriter.print("domain google.com\r\n"); printWriter.flush(); byte[] whoisrecords = new byte[2048]; java.util.List<Byte> bytelist = new ArrayList<>(1024 * 6); int size = 0; while ((size = inputStream.read(whoisrecords)) > 0) { for (int i = 0; i < size; i++) { bytelist.add(whoisrecords[i]); } } byte[] resultbyte = new byte[bytelist.size()]; for (int i = 0; i < resultbyte.length; i++) { resultbyte[i] = bytelist.get(i); } String string = new String(resultbyte); System.out.println(string); inputStream.close(); outputStream.close(); socket.close(); } #location 35 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws Exception { SSLConfiguration configuration = SSLConfiguration.loadClassPath("client-ssl.properties"); SocksProxy proxy = new SSLSocks5(new InetSocketAddress("localhost", 1080), configuration); List<SocksMethod> methods = new ArrayList<SocksMethod>(); methods.add(new NoAuthencationRequiredMethod()); proxy.setAcceptableMethods(methods); SocksSocket socket = new SocksSocket(proxy); socket.connect("whois.internic.net", 43); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream); printWriter.print("domain google.com\r\n"); printWriter.flush(); byte[] whoisrecords = new byte[2048]; List<Byte> bytelist = new ArrayList<>(1024 * 6); int size = 0; while ((size = inputStream.read(whoisrecords)) > 0) { for (int i = 0; i < size; i++) { bytelist.add(whoisrecords[i]); } } byte[] resultbyte = new byte[bytelist.size()]; for (int i = 0; i < resultbyte.length; i++) { resultbyte[i] = bytelist.get(i); } String string = new String(resultbyte); System.out.println(string); inputStream.close(); outputStream.close(); socket.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { logger.info("Start proxy server at port:{}", bindPort); while (!stop) { try { Socket socket = serverSocket.accept(); socket = processSocketBeforeUse(socket); socket.setSoTimeout(timeout); Session session = new SocksSession(getNextSessionId(), socket, sessions); sessions.put(session.getId(), session); logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress()); try { sessionFilterChain.doFilterChain(session); } catch (InterruptedException e) { session.close(); logger.info(e.getMessage()); continue; } SocksHandler socksHandler = createSocksHandler(); /* initialize socks handler */ socksHandler.setSession(session); initializeSocksHandler(socksHandler); executorService.execute(socksHandler); } catch (IOException e) { // Catches the exception that cause by shutdown method. if (e.getMessage().equals("Socket closed") && stop) { logger.debug("Server shutdown"); return; } logger.debug(e.getMessage(), e); } } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void run() { logger.info("Start proxy server at port:{}", bindPort); while (!stop) { try { Socket socket = serverSocket.accept(); socket = processSocketBeforeUse(socket); socket.setSoTimeout(timeout); Session session = sessionManager.newSession(socket); logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress()); try { sessionFilterChain.doFilterChain(session); } catch (InterruptedException e) { session.close(); logger.info(e.getMessage()); continue; } SocksHandler socksHandler = createSocksHandler(); /* initialize socks handler */ socksHandler.setSession(session); initializeSocksHandler(socksHandler); executorService.execute(socksHandler); } catch (IOException e) { // Catches the exception that cause by shutdown method. if (e.getMessage().equals("Socket closed") && stop) { logger.debug("Server shutdown"); return; } logger.debug(e.getMessage(), e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws IOException { Timer.open(); SSLConfiguration configuration = SSLConfiguration.loadClassPath("server-ssl.properties"); SocksProxyServer proxyServer = new SSLSocksProxyServer(Socks5Handler.class, configuration); proxyServer.setBindPort(1081); proxyServer.setSupportMethods(new NoAuthenticationRequiredMethod()); try { proxyServer.start(); } catch (IOException e) { logger.error(e.getMessage(), e); } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws IOException { Timer.open(); SSLConfiguration configuration = SSLConfiguration.loadClassPath("server-ssl.properties"); SocksProxyServer proxyServer = SocksServerBuilder.buildAnonymousSSLSocks5Server(1081, configuration); try { proxyServer.start(); } catch (IOException e) { logger.error(e.getMessage(), e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public byte[] getBytes() { byte[] bytes = null; switch (addressType) { case AddressType.IPV4: bytes = new byte[10]; byte[] ipv4Bytes = inetAddress.getAddress();// todo System.arraycopy(ipv4Bytes, 0, bytes, 4, ipv4Bytes.length); bytes[8] = SocksUtil.getFirstByteFromInt(port); bytes[9] = SocksUtil.getSecondByteFromInt(port); break; case AddressType.IPV6: bytes = new byte[22]; byte[] ipv6Bytes = inetAddress.getAddress();// todo System.arraycopy(ipv6Bytes, 0, bytes, 4, ipv6Bytes.length); bytes[20] = SocksUtil.getFirstByteFromInt(port); bytes[21] = SocksUtil.getSecondByteFromInt(port); break; case AddressType.DOMAIN_NAME: final int hostLength = host.getBytes().length; bytes = new byte[7 + hostLength]; bytes[4] = (byte) hostLength; for (int i = 0; i < hostLength; i++) { bytes[5 + i] = host.getBytes()[i]; } bytes[5 + hostLength] = SocksUtil.getFirstByteFromInt(port); bytes[6 + hostLength] = SocksUtil.getSecondByteFromInt(port); break; default: break; } bytes[0] = (byte) version; bytes[1] = (byte) command.getValue(); bytes[2] = RESERVED; bytes[3] = (byte) addressType; return bytes; } #location 36 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public byte[] getBytes() { byte[] bytes = null; switch (addressType) { case AddressType.IPV4: bytes = new byte[10]; byte[] ipv4Bytes = inetAddress.getAddress();// todo System.arraycopy(ipv4Bytes, 0, bytes, 4, ipv4Bytes.length); bytes[8] = SocksUtil.getFirstByteFromInt(port); bytes[9] = SocksUtil.getSecondByteFromInt(port); break; case AddressType.IPV6: bytes = new byte[22]; byte[] ipv6Bytes = inetAddress.getAddress();// todo System.arraycopy(ipv6Bytes, 0, bytes, 4, ipv6Bytes.length); bytes[20] = SocksUtil.getFirstByteFromInt(port); bytes[21] = SocksUtil.getSecondByteFromInt(port); break; case AddressType.DOMAIN_NAME: final int hostLength = host.getBytes().length; bytes = new byte[7 + hostLength]; bytes[4] = (byte) hostLength; for (int i = 0; i < hostLength; i++) { bytes[5 + i] = host.getBytes()[i]; } bytes[5 + hostLength] = SocksUtil.getFirstByteFromInt(port); bytes[6 + hostLength] = SocksUtil.getSecondByteFromInt(port); break; default: break; } if (bytes != null) { bytes[0] = (byte) version; bytes[1] = (byte) command.getValue(); bytes[2] = RESERVED; bytes[3] = (byte) addressType; } return bytes; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { logger.info("Start proxy server at port:{}", bindPort); while (!stop) { try { Socket socket = serverSocket.accept(); socket = processSocketBeforeUse(socket); socket.setSoTimeout(timeout); Session session = new SocksSession(getNextSessionId(), socket, sessions); sessions.put(session.getId(), session); logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress()); try { sessionFilterChain.doFilterChain(session); } catch (InterruptedException e) { session.close(); logger.info(e.getMessage()); continue; } SocksHandler socksHandler = createSocksHandler(); /* initialize socks handler */ socksHandler.setSession(session); initializeSocksHandler(socksHandler); executorService.execute(socksHandler); } catch (IOException e) { // Catches the exception that cause by shutdown method. if (e.getMessage().equals("Socket closed") && stop) { logger.debug("Server shutdown"); return; } logger.debug(e.getMessage(), e); } } } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void run() { logger.info("Start proxy server at port:{}", bindPort); while (!stop) { try { Socket socket = serverSocket.accept(); socket = processSocketBeforeUse(socket); socket.setSoTimeout(timeout); Session session = sessionManager.newSession(socket); logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress()); try { sessionFilterChain.doFilterChain(session); } catch (InterruptedException e) { session.close(); logger.info(e.getMessage()); continue; } SocksHandler socksHandler = createSocksHandler(); /* initialize socks handler */ socksHandler.setSession(session); initializeSocksHandler(socksHandler); executorService.execute(socksHandler); } catch (IOException e) { // Catches the exception that cause by shutdown method. if (e.getMessage().equals("Socket closed") && stop) { logger.debug("Server shutdown"); return; } logger.debug(e.getMessage(), e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(@Nullable String[] args) throws IOException, InterruptedException { Timer.open(); Socks5Server socks5Server = new Socks5Server(); socks5Server.start(args); BasicSocksProxyServer server = (BasicSocksProxyServer) socks5Server.server; NetworkMonitor monitor = server.getNetworkMonitor(); while (true) { logger.info(monitor.toString()); Thread.sleep(5000); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(@Nullable String[] args) throws IOException, InterruptedException { Timer.open(); Socks5Server socks5Server = new Socks5Server(); socks5Server.start(args); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { SocksProxy proxy = new Socks5(new InetSocketAddress("localhost", 1080)); try { @SuppressWarnings("resource") Socket socket = new SocksSocket(proxy, new InetSocketAddress("whois.internic.net", 43)); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream); printWriter.print("domain google.com\r\n"); printWriter.flush(); byte[] whoisrecords = new byte[2048]; java.util.List<Byte> bytelist = new ArrayList<>(1024 * 6); int size = 0; while ((size = inputStream.read(whoisrecords)) > 0) { for (int i = 0; i < size; i++) { bytelist.add(whoisrecords[i]); } } System.out.println("size:" + bytelist.size()); byte[] resultbyte = new byte[bytelist.size()]; for (int i = 0; i < resultbyte.length; i++) { resultbyte[i] = bytelist.get(i); } String string = new String(resultbyte); System.out.println(string); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocksException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) { InputStream inputStream = null; OutputStream outputStream = null; Socket socket = null; StringBuffer response = null; int length = 0; byte[] buffer = new byte[2048]; try { SocksProxy proxy = new Socks5(new InetSocketAddress("localhost", 1080)); socket = new SocksSocket(proxy, new InetSocketAddress("whois.internic.net", 43)); inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream); printWriter.print("domain google.com\r\n"); // query google.com WHOIS. printWriter.flush(); response = new StringBuffer(); while ((length = inputStream.read(buffer)) > 0) { response.append(new String(buffer, 0, length)); } System.out.println(response.toString()); } catch (IOException e) { e.printStackTrace(); } finally { ResourceUtil.close(inputStream, outputStream, socket); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetterSetterAnnotated() throws Exception { GetterSetterAnnotated o = new GetterSetterAnnotated(); o.setId("blah"); JacksonDBCollection<GetterSetterAnnotated, String> coll = createCollFor(o, String.class); WriteResult<GetterSetterAnnotated, String> writeResult = coll.insert(o); assertThat(writeResult.getSavedId(), equalTo("blah")); assertThat(writeResult.getDbObject().get("id"), nullValue()); GetterSetterAnnotated result = coll.findOneById("blah"); assertThat(result, notNullValue()); assertThat(result.getId(), equalTo("blah")); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetterSetterAnnotated() throws Exception { GetterSetterAnnotated o = new GetterSetterAnnotated(); o.setId("blah"); JacksonDBCollection<GetterSetterAnnotated, String> coll = createCollFor(o, String.class); coll.insert(o); GetterSetterAnnotated result = coll.findOneById("blah"); assertThat(result, notNullValue()); assertThat(result.getId(), equalTo("blah")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void simpleDbRefShouldBeSavedAsDbRef() { JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class); JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class); refColl.insert(new Referenced("hello", 10)); String id = coll.insert(new Owner(new DBRef<Referenced, String>("hello", refColl.getName()))).getSavedId(); Owner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo("hello")); assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); // Try loading it Referenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo("hello")); assertThat(ref.i, equalTo(10)); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void simpleDbRefShouldBeSavedAsDbRef() { JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class); JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class); refColl.insert(new Referenced("hello", 10)); coll.insert(new Owner(new DBRef<Referenced, String>("hello", refColl.getName()))); String id = coll.findOne()._id; Owner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo("hello")); assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); // Try loading it Referenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo("hello")); assertThat(ref.i, equalTo(10)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void dbRefWithObjectIdShouldBeSavedAsDbRef() { JacksonDBCollection<ObjectIdOwner, String> coll = getCollection(ObjectIdOwner.class, String.class); JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class); byte[] refId = refColl.insert(new ObjectIdReferenced(10)).getSavedId(); String id = coll.insert(new ObjectIdOwner(new DBRef<ObjectIdReferenced, byte[]>(refId, refColl.getName()))).getSavedId(); ObjectIdOwner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo(refId)); assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); // Try loading it ObjectIdReferenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId)); assertThat(ref.i, equalTo(10)); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void dbRefWithObjectIdShouldBeSavedAsDbRef() { JacksonDBCollection<ObjectIdOwner, String> coll = getCollection(ObjectIdOwner.class, String.class); JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class); byte[] refId = new org.bson.types.ObjectId().toByteArray(); refColl.insert(new ObjectIdReferenced(refId, 10)); coll.insert(new ObjectIdOwner(new DBRef<ObjectIdReferenced, byte[]>(refId, refColl.getName()))); String id = coll.findOne()._id; ObjectIdOwner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo(refId)); assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); // Try loading it ObjectIdReferenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId)); assertThat(ref.i, equalTo(10)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public WriteResult<T, K> update(T query, T object, boolean upsert, boolean multi, WriteConcern concern) throws MongoException { return update(convertToDbObject(query), convertToDbObject(object), upsert, multi, concern); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public WriteResult<T, K> update(T query, T object, boolean upsert, boolean multi, WriteConcern concern) throws MongoException { return update(convertToBasicDbObject(query), convertToBasicDbObject(object), upsert, multi, concern); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testJpaIdFieldAnnotated() throws Exception { JpaIdFieldAnnotated o = new JpaIdFieldAnnotated(); o.id = "blah"; JacksonDBCollection<JpaIdFieldAnnotated, String> coll = createCollFor(o, String.class); WriteResult<JpaIdFieldAnnotated, String> writeResult = coll.insert(o); assertThat(writeResult.getSavedId(), equalTo("blah")); assertThat(writeResult.getDbObject().get("id"), nullValue()); JpaIdFieldAnnotated result = coll.findOneById("blah"); assertThat(result, notNullValue()); assertThat(result.id, equalTo("blah")); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testJpaIdFieldAnnotated() throws Exception { JpaIdFieldAnnotated o = new JpaIdFieldAnnotated(); o.id = "blah"; JacksonDBCollection<JpaIdFieldAnnotated, String> coll = createCollFor(o, String.class); coll.insert(o); JpaIdFieldAnnotated result = coll.findOneById("blah"); assertThat(result, notNullValue()); assertThat(result.id, equalTo("blah")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void dbRefWithObjectIdShouldBeSavedAsDbRef() { JacksonDBCollection<ObjectIdOwner, String> coll = getCollection(ObjectIdOwner.class, String.class); JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class); byte[] refId = refColl.insert(new ObjectIdReferenced(10)).getSavedId(); String id = coll.insert(new ObjectIdOwner(new DBRef<ObjectIdReferenced, byte[]>(refId, refColl.getName()))).getSavedId(); ObjectIdOwner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo(refId)); assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); // Try loading it ObjectIdReferenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId)); assertThat(ref.i, equalTo(10)); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void dbRefWithObjectIdShouldBeSavedAsDbRef() { JacksonDBCollection<ObjectIdOwner, String> coll = getCollection(ObjectIdOwner.class, String.class); JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class); byte[] refId = new org.bson.types.ObjectId().toByteArray(); refColl.insert(new ObjectIdReferenced(refId, 10)); coll.insert(new ObjectIdOwner(new DBRef<ObjectIdReferenced, byte[]>(refId, refColl.getName()))); String id = coll.findOne()._id; ObjectIdOwner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo(refId)); assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); // Try loading it ObjectIdReferenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId)); assertThat(ref.i, equalTo(10)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testIdFieldAnnotated() throws Exception { IdFieldAnnotated o = new IdFieldAnnotated(); o.id = "blah"; JacksonDBCollection<IdFieldAnnotated, String> coll = createCollFor(o, String.class); WriteResult<IdFieldAnnotated, String> writeResult = coll.insert(o); assertThat(writeResult.getSavedId(), equalTo("blah")); assertThat(writeResult.getDbObject().get("id"), nullValue()); IdFieldAnnotated result = coll.findOneById("blah"); assertThat(result, notNullValue()); assertThat(result.id, equalTo("blah")); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testIdFieldAnnotated() throws Exception { IdFieldAnnotated o = new IdFieldAnnotated(); o.id = "blah"; JacksonDBCollection<IdFieldAnnotated, String> coll = createCollFor(o, String.class); coll.insert(o); IdFieldAnnotated result = coll.findOneById("blah"); assertThat(result, notNullValue()); assertThat(result.id, equalTo("blah")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testObjectIdAnnotationOnStringGenerated() { StringId object = new StringId(); JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class); String id = coll.insert(object).getSavedId(); // Check that it's a valid object id assertTrue(org.bson.types.ObjectId.isValid(id)); StringId result = coll.findOneById(id); assertThat(result._id, equalTo(id)); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testObjectIdAnnotationOnStringGenerated() { StringId object = new StringId(); JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class); coll.insert(object); String id = coll.findOne()._id; // Check that it's a valid object id assertTrue(org.bson.types.ObjectId.isValid(id)); StringId result = coll.findOneById(id); assertThat(result._id, equalTo(id)); assertThat(coll.getDbCollection().findOne().get("_id").toString(), equalTo(id)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCreatorGetterAnnotated() throws Exception { CreatorGetterAnnotated o = new CreatorGetterAnnotated("blah"); JacksonDBCollection<CreatorGetterAnnotated, String> coll = createCollFor(o, String.class); WriteResult<CreatorGetterAnnotated, String> writeResult = coll.insert(o); assertThat(writeResult.getSavedId(), equalTo("blah")); assertThat(writeResult.getDbObject().get("id"), nullValue()); CreatorGetterAnnotated result = coll.findOneById("blah"); assertThat(result, notNullValue()); assertThat(result.getId(), equalTo("blah")); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testCreatorGetterAnnotated() throws Exception { CreatorGetterAnnotated o = new CreatorGetterAnnotated("blah"); JacksonDBCollection<CreatorGetterAnnotated, String> coll = createCollFor(o, String.class); coll.insert(o); CreatorGetterAnnotated result = coll.findOneById("blah"); assertThat(result, notNullValue()); assertThat(result.getId(), equalTo("blah")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testObjectIdGenerated() { ObjectIdId object = new ObjectIdId(); JacksonDBCollection<ObjectIdId, org.bson.types.ObjectId> coll = getCollection(ObjectIdId.class, org.bson.types.ObjectId.class); org.bson.types.ObjectId id = coll.insert(object).getSavedId(); ObjectIdId result = coll.findOneById(id); assertThat(result._id, equalTo(id)); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testObjectIdGenerated() { ObjectIdId object = new ObjectIdId(); JacksonDBCollection<ObjectIdId, org.bson.types.ObjectId> coll = getCollection(ObjectIdId.class, org.bson.types.ObjectId.class); coll.insert(object); org.bson.types.ObjectId id = coll.findOne()._id; ObjectIdId result = coll.findOneById(id); assertThat(result._id, equalTo(id)); assertThat((org.bson.types.ObjectId) coll.getDbCollection().findOne().get("_id"), equalTo(id)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testUsingMongoCollectionAnnotation() { JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class); JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class, "referenced"); refColl.insert(new Referenced("hello", 10)); String id = coll.insert(new Owner(new DBRef<Referenced, String>("hello", Referenced.class))).getSavedId(); Owner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo("hello")); assertThat(saved.ref.getCollectionName(), equalTo("referenced")); // Try loading it Referenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo("hello")); assertThat(ref.i, equalTo(10)); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testUsingMongoCollectionAnnotation() { JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class); JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class, "referenced"); refColl.insert(new Referenced("hello", 10)); coll.insert(new Owner(new DBRef<Referenced, String>("hello", Referenced.class))); String id = coll.findOne()._id; Owner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo("hello")); assertThat(saved.ref.getCollectionName(), equalTo("referenced")); // Try loading it Referenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo("hello")); assertThat(ref.i, equalTo(10)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public UpdateResult save(T object, WriteConcern concern) throws MongoWriteException, MongoWriteConcernException, MongoException { Document dbObject = convertToDocument(object); Object _id = dbObject.get("_id"); if(_id == null) { this.insert(object, concern); return UpdateResult.acknowledged(0, 1L, new BsonObjectId((ObjectId) convertToDocument(object).get("_id"))); } else { return this.replaceOne(new Document("_id", _id), object, true, concern); } } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public UpdateResult save(T object, WriteConcern concern) throws MongoWriteException, MongoWriteConcernException, MongoException { Object _id; @SuppressWarnings("unchecked") final Codec<T> codec = getMongoCollection().getCodecRegistry().get((Class<T>) object.getClass()); if (codec instanceof CollectibleCodec) { _id = JacksonCodec.extractValueEx(((CollectibleCodec<T>) codec).getDocumentId(object)); } else { Document dbObject = convertToDocument(object); _id = dbObject.get("_id"); } if(_id == null) { if (concern == null) { this.insert(object); } else { this.insert(object, concern); } if (codec instanceof CollectibleCodec) { return UpdateResult.acknowledged(0, 1L, ((CollectibleCodec<T>)codec).getDocumentId(object)); } else { return UpdateResult.acknowledged(0, 1L, null); } } else { return this.replaceOne(new Document("_id", _id), object, true, concern); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testObjectIdFieldAnnotated() throws Exception { ObjectIdFieldAnnotated o = new ObjectIdFieldAnnotated(); JacksonDBCollection<ObjectIdFieldAnnotated, String> coll = createCollFor(o, String.class); WriteResult<ObjectIdFieldAnnotated, String> writeResult = coll.insert(o); assertThat(writeResult.getDbObject().get("_id"), instanceOf(org.bson.types.ObjectId.class)); assertThat(writeResult.getSavedId(), instanceOf(String.class)); assertThat(writeResult.getDbObject().get("id"), nullValue()); ObjectIdFieldAnnotated result = coll.findOneById(writeResult.getSavedId()); assertThat(result, notNullValue()); assertThat(result.id, equalTo(writeResult.getSavedId())); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testObjectIdFieldAnnotated() throws Exception { ObjectIdFieldAnnotated o = new ObjectIdFieldAnnotated(); o.id = new org.bson.types.ObjectId().toString(); JacksonDBCollection<ObjectIdFieldAnnotated, String> coll = createCollFor(o, String.class); coll.insert(o); ObjectIdFieldAnnotated result = coll.findOneById(o.id); assertThat(result, notNullValue()); assertThat(result.id, equalTo(o.id)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testObjectIdSaved() { ObjectIdId object = new ObjectIdId(); org.bson.types.ObjectId id = new org.bson.types.ObjectId(); object._id = id; JacksonDBCollection<ObjectIdId, org.bson.types.ObjectId> coll = getCollection(ObjectIdId.class, org.bson.types.ObjectId.class); coll.insert(object); ObjectIdId result = coll.findOneById(id); assertThat(result._id, equalTo(id)); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testObjectIdSaved() { ObjectIdId object = new ObjectIdId(); org.bson.types.ObjectId id = new org.bson.types.ObjectId(); object._id = id; JacksonDBCollection<ObjectIdId, org.bson.types.ObjectId> coll = getCollection(ObjectIdId.class, org.bson.types.ObjectId.class); coll.insert(object); ObjectIdId result = coll.findOneById(id); assertThat(result._id, equalTo(id)); assertThat((org.bson.types.ObjectId) coll.getDbCollection().findOne().get("_id"), equalTo(id)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void collectionOfObjectIdDbRefsShouldBeSavedAsObjectIdDbRefs() { JacksonDBCollection<ObjectIdCollectionOwner, String> coll = getCollection(ObjectIdCollectionOwner.class, String.class); JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class, "referenced"); byte[] refId1 = refColl.insert(new ObjectIdReferenced(10)).getSavedId(); byte[] refId2 = refColl.insert(new ObjectIdReferenced(20)).getSavedId(); ObjectIdCollectionOwner owner = new ObjectIdCollectionOwner(); owner.list = Arrays.asList(new DBRef<ObjectIdReferenced, byte[]>(refId1, refColl.getName()), new DBRef<ObjectIdReferenced, byte[]>(refId2, refColl.getName())); owner._id = "foo"; coll.insert(owner); ObjectIdCollectionOwner saved = coll.findOneById("foo"); assertThat(saved.list, notNullValue()); assertThat(saved.list, hasSize(2)); assertThat(saved.list.get(0).getId(), equalTo(refId1)); assertThat(saved.list.get(0).getCollectionName(), equalTo(refColl.getName())); assertThat(saved.list.get(1).getId(), equalTo(refId2)); assertThat(saved.list.get(1).getCollectionName(), equalTo(refColl.getName())); // Try loading them ObjectIdReferenced ref = saved.list.get(0).fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId1)); assertThat(ref.i, equalTo(10)); ref = saved.list.get(1).fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId2)); assertThat(ref.i, equalTo(20)); } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void collectionOfObjectIdDbRefsShouldBeSavedAsObjectIdDbRefs() { JacksonDBCollection<ObjectIdCollectionOwner, String> coll = getCollection(ObjectIdCollectionOwner.class, String.class); JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class, "referenced"); byte[] refId1 = new org.bson.types.ObjectId().toByteArray(); refColl.insert(new ObjectIdReferenced(refId1, 10)); byte[] refId2 = new org.bson.types.ObjectId().toByteArray(); refColl.insert(new ObjectIdReferenced(refId2, 20)); ObjectIdCollectionOwner owner = new ObjectIdCollectionOwner(); owner.list = Arrays.asList(new DBRef<ObjectIdReferenced, byte[]>(refId1, refColl.getName()), new DBRef<ObjectIdReferenced, byte[]>(refId2, refColl.getName())); owner._id = "foo"; coll.insert(owner); ObjectIdCollectionOwner saved = coll.findOneById("foo"); assertThat(saved.list, notNullValue()); assertThat(saved.list, hasSize(2)); assertThat(saved.list.get(0).getId(), equalTo(refId1)); assertThat(saved.list.get(0).getCollectionName(), equalTo(refColl.getName())); assertThat(saved.list.get(1).getId(), equalTo(refId2)); assertThat(saved.list.get(1).getCollectionName(), equalTo(refColl.getName())); // Try loading them ObjectIdReferenced ref = saved.list.get(0).fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId1)); assertThat(ref.i, equalTo(10)); ref = saved.list.get(1).fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId2)); assertThat(ref.i, equalTo(20)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testUsingMongoCollectionAnnotation() { JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class); JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class, "referenced"); refColl.insert(new Referenced("hello", 10)); String id = coll.insert(new Owner(new DBRef<Referenced, String>("hello", Referenced.class))).getSavedId(); Owner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo("hello")); assertThat(saved.ref.getCollectionName(), equalTo("referenced")); // Try loading it Referenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo("hello")); assertThat(ref.i, equalTo(10)); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testUsingMongoCollectionAnnotation() { JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class); JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class, "referenced"); refColl.insert(new Referenced("hello", 10)); coll.insert(new Owner(new DBRef<Referenced, String>("hello", Referenced.class))); String id = coll.findOne()._id; Owner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo("hello")); assertThat(saved.ref.getCollectionName(), equalTo("referenced")); // Try loading it Referenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo("hello")); assertThat(ref.i, equalTo(10)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFindOneByIdWithObjectId() { JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class); StringId object = new StringId(); net.vz.mongodb.jackson.WriteResult<StringId, String> writeResult = coll.insert(object); assertThat(writeResult.getDbObject().get("_id"), instanceOf(org.bson.types.ObjectId.class)); String id = writeResult.getSavedId(); assertThat(id, instanceOf(String.class)); StringId result = coll.findOneById(id); assertThat(result._id, Matchers.equalTo(id)); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testFindOneByIdWithObjectId() { JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class); StringId object = new StringId(); coll.insert(object); assertThat(coll.getDbCollection().findOne().get("_id"), instanceOf(org.bson.types.ObjectId.class)); String id = coll.findOne()._id; assertThat(id, instanceOf(String.class)); StringId result = coll.findOneById(id); assertThat(result._id, Matchers.equalTo(id)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCreatorGetterObjectIdAnnotated() throws Exception { CreatorGetterObjectIdAnnotated o = new CreatorGetterObjectIdAnnotated(null); JacksonDBCollection<CreatorGetterObjectIdAnnotated, String> coll = createCollFor(o, String.class); WriteResult<CreatorGetterObjectIdAnnotated, String> writeResult = coll.insert(o); assertThat(writeResult.getSavedId(), notNullValue()); assertThat(writeResult.getSavedId(), instanceOf(String.class)); assertThat(writeResult.getDbObject().get("id"), nullValue()); assertThat(writeResult.getSavedId(), equalTo(writeResult.getDbObject().get("_id").toString())); CreatorGetterObjectIdAnnotated result = coll.findOneById(writeResult.getSavedId()); assertThat(result, notNullValue()); assertThat(result.getId(), equalTo(writeResult.getSavedId())); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testCreatorGetterObjectIdAnnotated() throws Exception { CreatorGetterObjectIdAnnotated o = new CreatorGetterObjectIdAnnotated(new org.bson.types.ObjectId().toString()); JacksonDBCollection<CreatorGetterObjectIdAnnotated, String> coll = createCollFor(o, String.class); coll.insert(o); CreatorGetterObjectIdAnnotated result = coll.findOneById(o.id); assertThat(result, notNullValue()); assertThat(result.getId(), equalTo(o.id)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void collectionOfObjectIdDbRefsShouldBeSavedAsObjectIdDbRefs() { JacksonDBCollection<ObjectIdCollectionOwner, String> coll = getCollection(ObjectIdCollectionOwner.class, String.class); JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class, "referenced"); byte[] refId1 = refColl.insert(new ObjectIdReferenced(10)).getSavedId(); byte[] refId2 = refColl.insert(new ObjectIdReferenced(20)).getSavedId(); ObjectIdCollectionOwner owner = new ObjectIdCollectionOwner(); owner.list = Arrays.asList(new DBRef<ObjectIdReferenced, byte[]>(refId1, refColl.getName()), new DBRef<ObjectIdReferenced, byte[]>(refId2, refColl.getName())); owner._id = "foo"; coll.insert(owner); ObjectIdCollectionOwner saved = coll.findOneById("foo"); assertThat(saved.list, notNullValue()); assertThat(saved.list, hasSize(2)); assertThat(saved.list.get(0).getId(), equalTo(refId1)); assertThat(saved.list.get(0).getCollectionName(), equalTo(refColl.getName())); assertThat(saved.list.get(1).getId(), equalTo(refId2)); assertThat(saved.list.get(1).getCollectionName(), equalTo(refColl.getName())); // Try loading them ObjectIdReferenced ref = saved.list.get(0).fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId1)); assertThat(ref.i, equalTo(10)); ref = saved.list.get(1).fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId2)); assertThat(ref.i, equalTo(20)); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void collectionOfObjectIdDbRefsShouldBeSavedAsObjectIdDbRefs() { JacksonDBCollection<ObjectIdCollectionOwner, String> coll = getCollection(ObjectIdCollectionOwner.class, String.class); JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class, "referenced"); byte[] refId1 = new org.bson.types.ObjectId().toByteArray(); refColl.insert(new ObjectIdReferenced(refId1, 10)); byte[] refId2 = new org.bson.types.ObjectId().toByteArray(); refColl.insert(new ObjectIdReferenced(refId2, 20)); ObjectIdCollectionOwner owner = new ObjectIdCollectionOwner(); owner.list = Arrays.asList(new DBRef<ObjectIdReferenced, byte[]>(refId1, refColl.getName()), new DBRef<ObjectIdReferenced, byte[]>(refId2, refColl.getName())); owner._id = "foo"; coll.insert(owner); ObjectIdCollectionOwner saved = coll.findOneById("foo"); assertThat(saved.list, notNullValue()); assertThat(saved.list, hasSize(2)); assertThat(saved.list.get(0).getId(), equalTo(refId1)); assertThat(saved.list.get(0).getCollectionName(), equalTo(refColl.getName())); assertThat(saved.list.get(1).getId(), equalTo(refId2)); assertThat(saved.list.get(1).getCollectionName(), equalTo(refColl.getName())); // Try loading them ObjectIdReferenced ref = saved.list.get(0).fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId1)); assertThat(ref.i, equalTo(10)); ref = saved.list.get(1).fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo(refId2)); assertThat(ref.i, equalTo(20)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testObjectIdAnnotationOnStringSaved() { StringId object = new StringId(); String id = new org.bson.types.ObjectId().toString(); object._id = id; JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class); coll.insert(object); StringId result = coll.findOneById(id); assertThat(result._id, equalTo(id)); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testObjectIdAnnotationOnStringSaved() { StringId object = new StringId(); String id = new org.bson.types.ObjectId().toString(); object._id = id; JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class); coll.insert(object); StringId result = coll.findOneById(id); assertThat(result._id, equalTo(id)); assertThat(coll.getDbCollection().findOne().get("_id").toString(), equalTo(id)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void simpleDbRefShouldBeSavedAsDbRef() { JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class); JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class); refColl.insert(new Referenced("hello", 10)); String id = coll.insert(new Owner(new DBRef<Referenced, String>("hello", refColl.getName()))).getSavedId(); Owner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo("hello")); assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); // Try loading it Referenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo("hello")); assertThat(ref.i, equalTo(10)); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void simpleDbRefShouldBeSavedAsDbRef() { JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class); JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class); refColl.insert(new Referenced("hello", 10)); coll.insert(new Owner(new DBRef<Referenced, String>("hello", refColl.getName()))); String id = coll.findOne()._id; Owner saved = coll.findOneById(id); assertThat(saved.ref, notNullValue()); assertThat(saved.ref.getId(), equalTo("hello")); assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); // Try loading it Referenced ref = saved.ref.fetch(); assertThat(ref, notNullValue()); assertThat(ref._id, equalTo("hello")); assertThat(ref.i, equalTo(10)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void calculate(ValuesProvider valuesProvider, List<ConnectionCandidate> connections, NeuralNetwork nn) { if (connections.size() > 0) { List<Connections> chunk = new ArrayList<>(); for (int i = 0; i < connections.size(); i++) { ConnectionCandidate c = connections.get(i); chunk.add(c.connection); if (i == connections.size() - 1 || connections.get(i + 1).target != c.target) { ConnectionCalculator cc = getConnectionCalculator(c.target); if (cc != null) { Tensor t = TensorFactory.tensor(c.target, chunk, valuesProvider); t.forEach(j -> t.getElements()[j] = 0); cc.calculate(chunk, valuesProvider, c.target); } chunk.clear(); triggerEvent(new PropagationEvent(c.target, chunk, nn, valuesProvider)); } } } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code protected void calculate(ValuesProvider valuesProvider, List<ConnectionCandidate> connections, NeuralNetwork nn) { if (connections.size() > 0) { List<Connections> chunk = new ArrayList<>(); for (int i = 0; i < connections.size(); i++) { ConnectionCandidate c = connections.get(i); chunk.add(c.connection); if (i == connections.size() - 1 || connections.get(i + 1).target != c.target) { ConnectionCalculator cc = getConnectionCalculator(c.target); if (cc != null) { Tensor t = TensorFactory.tensor(c.target, chunk, valuesProvider); float[] elements = t.getElements(); IntStream.range(t.getStartIndex(), t.getStartIndex() + t.getSize()).forEach(j -> elements[j] = 0); cc.calculate(chunk, valuesProvider, c.target); } chunk.clear(); triggerEvent(new PropagationEvent(c.target, chunk, nn, valuesProvider)); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void httpsUrlGitHubNoSuffix() { GitHubRepositoryName repo = GitHubRepositoryName .create("https://[email protected]/jenkinsci/jenkins"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("github.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void httpsUrlGitHubNoSuffix() { testURL("https://[email protected]/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void gitColonUrlGitHub() { GitHubRepositoryName repo = GitHubRepositoryName .create("git://github.com/jenkinsci/jenkins.git"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("github.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void gitColonUrlGitHub() { testURL("git://github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void httpsUrlGitHub() { GitHubRepositoryName repo = GitHubRepositoryName .create("https://[email protected]/jenkinsci/jenkins.git"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("github.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void httpsUrlGitHub() { testURL("https://[email protected]/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void gitAtUrlGitHub() { GitHubRepositoryName repo = GitHubRepositoryName .create("[email protected]:jenkinsci/jenkins.git"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("github.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void gitAtUrlGitHub() { testURL("[email protected]:jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void gitColonUrlOtherHostNoSuffix() { GitHubRepositoryName repo = GitHubRepositoryName .create("git://company.net/jenkinsci/jenkins"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("company.net", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void gitColonUrlOtherHostNoSuffix() { testURL("git://company.net/jenkinsci/jenkins", "company.net", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void gitColonUrlOtherHost() { GitHubRepositoryName repo = GitHubRepositoryName .create("git://company.net/jenkinsci/jenkins.git"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("company.net", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void gitColonUrlOtherHost() { testURL("git://company.net/jenkinsci/jenkins.git", "company.net", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void gitColonUrlGitHubNoSuffix() { GitHubRepositoryName repo = GitHubRepositoryName .create("git://github.com/jenkinsci/jenkins"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("github.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void gitColonUrlGitHubNoSuffix() { testURL("git://github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void httpsUrlGitHubWithoutUserNoSuffix() { //this is valid for anonymous usage GitHubRepositoryName repo = GitHubRepositoryName .create("https://github.com/jenkinsci/jenkins"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("github.com", repo.host); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void httpsUrlGitHubWithoutUserNoSuffix() { testURL("https://github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void trimWhitespace() { GitHubRepositoryName repo = GitHubRepositoryName .create(" https://[email protected]/jenkinsci/jenkins/ "); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("github.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void trimWhitespace() { assertThat(" https://[email protected]/jenkinsci/jenkins/ ", repo(allOf( withHost("github.com"), withUserName("jenkinsci"), withRepoName("jenkins") ))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void httpsUrlOtherHost() { GitHubRepositoryName repo = GitHubRepositoryName .create("https://[email protected]/jenkinsci/jenkins.git"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("gh.company.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void httpsUrlOtherHost() { testURL("https://[email protected]/jenkinsci/jenkins.git", "gh.company.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void httpsUrlOtherHostNoSuffix() { GitHubRepositoryName repo = GitHubRepositoryName .create("https://[email protected]/jenkinsci/jenkins"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("gh.company.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void httpsUrlOtherHostNoSuffix() { testURL("https://[email protected]/jenkinsci/jenkins", "gh.company.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void gitAtUrlOtherHostNoSuffix() { GitHubRepositoryName repo = GitHubRepositoryName .create("[email protected]:jenkinsci/jenkins"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("gh.company.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void gitAtUrlOtherHostNoSuffix() { testURL("[email protected]:jenkinsci/jenkins", "gh.company.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void httpsUrlGitHubWithoutUser() { //this is valid for anonymous usage GitHubRepositoryName repo = GitHubRepositoryName .create("https://github.com/jenkinsci/jenkins.git"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("github.com", repo.host); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void httpsUrlGitHubWithoutUser() { testURL("https://github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private OkHttpConnector connector(String apiUrl) { Jenkins jenkins = GitHubWebHook.getJenkinsInstance(); OkHttpClient client = new OkHttpClient().setProxy(getProxy(apiUrl)); if (configuration().getClientCacheSize() > 0) { File cacheDir = new File(jenkins.getRootDir(), GitHubPlugin.class.getName() + ".cache"); Cache cache = new Cache(cacheDir, configuration().getClientCacheSize() * 1024 * 1024); client.setCache(cache); } return new OkHttpConnector(new OkUrlFactory(client)); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private OkHttpConnector connector(String apiUrl) { OkHttpClient client = new OkHttpClient().setProxy(getProxy(apiUrl)); if (configuration().getClientCacheSize() > 0) { File cacheDir = getCacheBaseDirFor(GitHubWebHook.getJenkinsInstance()); Cache cache = new Cache(cacheDir, configuration().getClientCacheSize() * 1024 * 1024); client.setCache(cache); } return new OkHttpConnector(new OkUrlFactory(client)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void gitAtUrlGitHubNoSuffix() { GitHubRepositoryName repo = GitHubRepositoryName .create("[email protected]:jenkinsci/jenkins"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("github.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void gitAtUrlGitHubNoSuffix() { testURL("[email protected]:jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void gitAtUrlOtherHost() { GitHubRepositoryName repo = GitHubRepositoryName .create("[email protected]:jenkinsci/jenkins.git"); assertNotNull(repo); assertEquals("jenkinsci", repo.userName); assertEquals("jenkins", repo.repositoryName); assertEquals("gh.company.com", repo.host); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void gitAtUrlOtherHost() { testURL("[email protected]:jenkinsci/jenkins.git", "gh.company.com", "jenkinsci", "jenkins"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { CommandLineParams commandLineParams = new CommandLineParams(); JCommander jCommander = new JCommander(commandLineParams, args); if (commandLineParams.help) { jCommander.usage(); System.exit(1); } // default to src/main/webapp if (commandLineParams.paths.size() == 0) { commandLineParams.paths.add("src/main/webapp"); } final Tomcat tomcat = new Tomcat(); // set directory for temp files tomcat.setBaseDir(resolveTomcatBaseDir(commandLineParams.port)); // initialize the connector Connector nioConnector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); nioConnector.setPort(commandLineParams.port); tomcat.setConnector(nioConnector); tomcat.getService().addConnector(tomcat.getConnector()); tomcat.setPort(commandLineParams.port); if (commandLineParams.paths.size() > 1) { System.out.println("FYI... Since you specified more than one path, the context paths will be automatically set to the name of the path without the extension. A path that resolves to a context path of \"/ROOT\" will be replaced with \"/\""); if(commandLineParams.contextPath != null) { System.out.println("WARNING: context-path is ignored when more than one path or war file is specified"); } if(commandLineParams.contextXml != null) { System.out.println("WARNING: context-xml is ignored when more than one path or war file is specified"); } } Context ctx = null; for (String path : commandLineParams.paths) { File war = new File(path); if (!war.exists()) { System.err.println("The specified path \"" + path + "\" does not exist."); jCommander.usage(); System.exit(1); } String ctxName = ""; // Use the commandline context-path (or default) if there is only one war if (commandLineParams.paths.size() == 1) { // warn if the contextPath doesn't start with a '/'. This causes issues serving content at the context root. if (commandLineParams.contextPath.length() > 0 && !commandLineParams.contextPath.startsWith("/")) { System.out.println("WARNING: You entered a path: [" + commandLineParams.contextPath + "]. Your path should start with a '/'. Tomcat will update this for you, but you may still experience issues."); } ctxName = commandLineParams.contextPath; } else { ctxName = "/" + FilenameUtils.removeExtension(war.getName()); if (ctxName.equals("/ROOT") || (commandLineParams.paths.size() == 1)) { ctxName = "/"; } } System.out.println("Adding Context " + ctxName + " for " + war.getPath()); //Context ctx = tomcat.addWebapp(ctxName, war.getAbsolutePath()); ctx = tomcat.addWebapp(ctxName, war.getAbsolutePath()); } if(!commandLineParams.shutdownOverride) { final String ctxName = ctx.getName(); // allow Tomcat to shutdown if a context failure is detected ctx.addLifecycleListener(new LifecycleListener() { public void lifecycleEvent(LifecycleEvent event) { if (event.getLifecycle().getState() == LifecycleState.FAILED) { Server server = tomcat.getServer(); if (server instanceof StandardServer) { System.err.println("SEVERE: Context [" + ctxName + "] failed in [" + event.getLifecycle().getClass().getName() + "] lifecycle. Allowing Tomcat to shutdown."); ((StandardServer) server).stopAwait(); } } } }); } // set the context xml location if there is only one war if(commandLineParams.contextXml != null && commandLineParams.paths.size() == 1) { System.out.println("Using context config: " + commandLineParams.contextXml); ctx.setConfigFile(new File(commandLineParams.contextXml).toURI().toURL()); } // set the session manager if (commandLineParams.sessionStore != null) { SessionStore.getInstance(commandLineParams.sessionStore).configureSessionStore(commandLineParams, ctx); } //set the session timeout if(commandLineParams.sessionTimeout != null) { ctx.setSessionTimeout(commandLineParams.sessionTimeout); } commandLineParams = null; //start the server tomcat.start(); tomcat.getServer().await(); } #location 81 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) throws Exception { CommandLineParams commandLineParams = new CommandLineParams(); JCommander jCommander = new JCommander(commandLineParams, args); if (commandLineParams.help) { jCommander.usage(); System.exit(1); } // default to src/main/webapp if (commandLineParams.paths.size() == 0) { commandLineParams.paths.add("src/main/webapp"); } final Tomcat tomcat = new Tomcat(); // set directory for temp files tomcat.setBaseDir(resolveTomcatBaseDir(commandLineParams.port)); // initialize the connector Connector nioConnector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); nioConnector.setPort(commandLineParams.port); tomcat.setConnector(nioConnector); tomcat.getService().addConnector(tomcat.getConnector()); tomcat.setPort(commandLineParams.port); if (commandLineParams.paths.size() > 1) { System.out.println("WARNING: multiple paths are specified, but no longer supported. First path will be used."); } // Get the first path String path = commandLineParams.paths.get(0); Context ctx = null; File war = new File(path); if (!war.exists()) { System.err.println("The specified path \"" + path + "\" does not exist."); jCommander.usage(); System.exit(1); } // Use the commandline context-path (or default) // warn if the contextPath doesn't start with a '/'. This causes issues serving content at the context root. if (commandLineParams.contextPath.length() > 0 && !commandLineParams.contextPath.startsWith("/")) { System.out.println("WARNING: You entered a path: [" + commandLineParams.contextPath + "]. Your path should start with a '/'. Tomcat will update this for you, but you may still experience issues."); } final String ctxName = commandLineParams.contextPath; System.out.println("Adding Context " + ctxName + " for " + war.getPath()); ctx = tomcat.addWebapp(ctxName, war.getAbsolutePath()); if(!commandLineParams.shutdownOverride) { // allow Tomcat to shutdown if a context failure is detected ctx.addLifecycleListener(new LifecycleListener() { public void lifecycleEvent(LifecycleEvent event) { if (event.getLifecycle().getState() == LifecycleState.FAILED) { Server server = tomcat.getServer(); if (server instanceof StandardServer) { System.err.println("SEVERE: Context [" + ctxName + "] failed in [" + event.getLifecycle().getClass().getName() + "] lifecycle. Allowing Tomcat to shutdown."); ((StandardServer) server).stopAwait(); } } } }); } // set the context xml location if there is only one war if(commandLineParams.contextXml != null) { System.out.println("Using context config: " + commandLineParams.contextXml); ctx.setConfigFile(new File(commandLineParams.contextXml).toURI().toURL()); } // set the session manager if (commandLineParams.sessionStore != null) { SessionStore.getInstance(commandLineParams.sessionStore).configureSessionStore(commandLineParams, ctx); } //set the session timeout if(commandLineParams.sessionTimeout != null) { ctx.setSessionTimeout(commandLineParams.sessionTimeout); } commandLineParams = null; //start the server tomcat.start(); tomcat.getServer().await(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Process exec( String namespace, String name, String[] command, String container, boolean stdin, boolean tty) throws ApiException, IOException { if (container == null) { CoreV1Api api = new CoreV1Api(apiClient); V1Pod pod = api.readNamespacedPod(name, namespace, "false", null, null); container = pod.getSpec().getContainers().get(0).getName(); } String path = makePath(namespace, name, command, container, stdin, tty); ExecProcess exec = new ExecProcess(apiClient); WebSocketStreamHandler handler = exec.getHandler(); WebSockets.stream(path, "GET", apiClient, handler); return exec; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public Process exec( String namespace, String name, String[] command, String container, boolean stdin, boolean tty) throws ApiException, IOException { return newExecutionBuilder(namespace, name, command) .setContainer(container) .setStdin(stdin) .setTty(tty) .execute(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Benchmark public void fastjson() { JSONScanner scanner = new JSONScanner(JsoniterBenchmarkState.inputString); scanner.nextToken(); do { scanner.nextToken(); scanner.intValue(); scanner.nextToken(); } while (scanner.token() == JSONToken.COMMA); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Benchmark public void fastjson() { JSON.parseObject(JsoniterBenchmarkState.inputString, byte[].class); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ApiClient defaultClient() throws IOException { String kubeConfig = System.getenv(ENV_KUBECONFIG); if (kubeConfig != null) { return fromConfig(new FileReader(kubeConfig)); } File config = new File( new File(System.getenv(KubeConfig.ENV_HOME), KubeConfig.KUBEDIR), KubeConfig.KUBECONFIG); if (config.exists()) { return fromConfig(new FileReader(config)); } File clusterCA = new File(SERVICEACCOUNT_CA_PATH); if (clusterCA.exists()) { return fromCluster(); } ApiClient client = new ApiClient(); client.setBasePath(DEFAULT_FALLBACK_HOST); return client; } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code public static ApiClient defaultClient() throws IOException { return ClientBuilder.defaults().build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Benchmark public void fastjson() { new JSONReaderScanner(new InputStreamReader(new ByteArrayInputStream(JsoniterBenchmarkState.input))).intValue(); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Benchmark public void fastjson() { JSONScanner scanner = new JSONScanner(JsoniterBenchmarkState.inputString); scanner.nextToken(); do { scanner.nextToken(); scanner.intValue(); scanner.nextToken(); } while (scanner.token() == JSONToken.COMMA); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Process exec( String namespace, String name, String[] command, String container, boolean stdin, boolean tty) throws ApiException, IOException { if (container == null) { CoreV1Api api = new CoreV1Api(apiClient); V1Pod pod = api.readNamespacedPod(name, namespace, "false", null, null); container = pod.getSpec().getContainers().get(0).getName(); } String path = makePath(namespace, name, command, container, stdin, tty); ExecProcess exec = new ExecProcess(apiClient); WebSocketStreamHandler handler = exec.getHandler(); WebSockets.stream(path, "GET", apiClient, handler); return exec; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public Process exec( String namespace, String name, String[] command, String container, boolean stdin, boolean tty) throws ApiException, IOException { return newExecutionBuilder(namespace, name, command) .setContainer(container) .setStdin(stdin) .setTty(tty) .execute(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Benchmark public void jsoniter() throws IOException { Jsoniter iter = Jsoniter.parseBytes(JsoniterBenchmarkState.inputBytes); while (iter.ReadArray()) { iter.ReadUnsignedInt(); } } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Benchmark public void jsoniter() throws IOException { Jsoniter jsoniter = Jsoniter.parseBytes(JsoniterBenchmarkState.inputBytes); byte[] val = new byte[3]; jsoniter.Read(val); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ApiClient fromConfig(InputStream stream) throws IOException { return fromConfig(new InputStreamReader(stream)); // TODO UTF-8 } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public static ApiClient fromConfig(InputStream stream) throws IOException { return fromConfig(new InputStreamReader(stream, StandardCharsets.UTF_8.name())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T extends Message> ObjectOrStatus<T> request( T.Builder builder, String path, String method, T body, String apiVersion, String kind) throws ApiException, IOException { HashMap<String, String> headers = new HashMap<>(); headers.put("Content-Type", MEDIA_TYPE); headers.put("Accept", MEDIA_TYPE); String[] localVarAuthNames = new String[] {"BearerToken"}; Request request = apiClient.buildRequest( path, method, new ArrayList<Pair>(), new ArrayList<Pair>(), null, headers, new HashMap<String, String>(), new HashMap<String, Object>(), localVarAuthNames, null); if (body != null) { byte[] bytes = encode(body, apiVersion, kind); switch (method) { case "POST": request = request .newBuilder() .post(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes)) .build(); break; case "PUT": request = request .newBuilder() .put(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes)) .build(); break; case "PATCH": request = request .newBuilder() .patch(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes)) .build(); break; default: throw new ApiException("Unknown proto client API method: " + method); } } Response resp = apiClient.getHttpClient().newCall(request).execute(); Unknown u = parse(resp.body().byteStream()); resp.body().close(); if (u.getTypeMeta().getApiVersion().equals("v1") && u.getTypeMeta().getKind().equals("Status")) { Status status = Status.newBuilder().mergeFrom(u.getRaw()).build(); return new ObjectOrStatus(null, status); } return new ObjectOrStatus((T) builder.mergeFrom(u.getRaw()).build(), null); } #location 49 #vulnerability type NULL_DEREFERENCE
#fixed code public <T extends Message> ObjectOrStatus<T> request( T.Builder builder, String path, String method, T body, String apiVersion, String kind) throws ApiException, IOException { HashMap<String, String> headers = new HashMap<>(); headers.put("Content-Type", MEDIA_TYPE); headers.put("Accept", MEDIA_TYPE); String[] localVarAuthNames = new String[] {"BearerToken"}; Request request = apiClient.buildRequest( path, method, new ArrayList<Pair>(), new ArrayList<Pair>(), null, headers, new HashMap<String, String>(), new HashMap<String, Object>(), localVarAuthNames, null); if (body != null) { byte[] bytes = encode(body, apiVersion, kind); switch (method) { case "POST": request = request .newBuilder() .post(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes)) .build(); break; case "PUT": request = request .newBuilder() .put(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes)) .build(); break; case "PATCH": request = request .newBuilder() .patch(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes)) .build(); break; default: throw new ApiException("Unknown proto client API method: " + method); } } return getObjectOrStatusFromServer(builder, request); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ApiClient fromConfig(String fileName) throws IOException { return fromConfig(new FileReader(fileName)); } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public static ApiClient fromConfig(String fileName) throws IOException { KubeConfig config = KubeConfig.loadKubeConfig(new FileReader(fileName)); // TODO UTF-8 config.setFile(new File(fileName)); return fromConfig(config); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ClientBuilder standard(boolean persistConfig) throws IOException { final File kubeConfig = findConfigFromEnv(); if (kubeConfig != null) { try (BufferedReader kubeConfigReader = new BufferedReader( new InputStreamReader( new FileInputStream(kubeConfig), StandardCharsets.UTF_8.name()))) { KubeConfig kc = KubeConfig.loadKubeConfig(kubeConfigReader); if (persistConfig) { kc.setPersistConfig(new FilePersister(kubeConfig)); } kc.setFile(kubeConfig); return kubeconfig(kc); } } final File config = findConfigInHomeDir(); if (config != null) { try (BufferedReader configReader = new BufferedReader( new InputStreamReader(new FileInputStream(config), StandardCharsets.UTF_8.name()))) { KubeConfig kc = KubeConfig.loadKubeConfig(configReader); if (persistConfig) { kc.setPersistConfig(new FilePersister(config)); } kc.setFile(config); return kubeconfig(kc); } } final File clusterCa = new File(SERVICEACCOUNT_CA_PATH); if (clusterCa.exists()) { return cluster(); } return new ClientBuilder(); } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code public static ClientBuilder standard(boolean persistConfig) throws IOException { final File kubeConfig = findConfigFromEnv(); ClientBuilder clientBuilderEnv = getClientBuilder(persistConfig, kubeConfig); if (clientBuilderEnv != null) return clientBuilderEnv; final File config = findConfigInHomeDir(); ClientBuilder clientBuilderHomeDir = getClientBuilder(persistConfig, config); if (clientBuilderHomeDir != null) return clientBuilderHomeDir; final File clusterCa = new File(SERVICEACCOUNT_CA_PATH); if (clusterCa.exists()) { return cluster(); } return new ClientBuilder(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws IOException, ApiException { ApiClient client = Config.defaultClient(); Configuration.setDefaultApiClient(client); CoreV1Api api = new CoreV1Api(); V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null); for (V1Pod item : list.getItems()) { System.out.println(item.getMetadata().getName()); } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) { try { Example operation = new Example(); operation.executeCommand(); } catch (ApiException ex) { LOGGER.log(Level.SEVERE, null, ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ApiListType executeRequest(Call call) throws IOException, ApiException, ObjectMetaReflectException { ApiListType data = client.handleResponse(call.execute(), listType); V1ListMeta listMetaData = Reflect.listMetadata(data); continueToken = listMetaData.getContinue(); return data; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private ApiListType executeRequest(Call call) throws IOException, ApiException { return client.handleResponse(call.execute(), listType); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Benchmark public void jsoniter() throws IOException { Jsoniter.parse(new ByteArrayInputStream(JsoniterBenchmarkState.input), 4096).ReadUnsignedInt(); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Benchmark public void jsoniter() throws IOException { Jsoniter iter = Jsoniter.parseBytes(JsoniterBenchmarkState.inputBytes); while (iter.ReadArray()) { iter.ReadUnsignedInt(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void writeToStream(DataOutputStream os) throws IOException { WritableByteChannel dataChannel = Channels.newChannel(os); os.writeInt(getOriginalSize()); os.writeInt(getSamplingRateSA()); os.writeInt(getSamplingRateISA()); os.writeInt(getSamplingRateNPA()); os.writeInt(getSampleBitWidth()); os.writeInt(getAlphabetSize()); for (Byte c : alphabetMap.keySet()) { Pair<Integer, Integer> cval = alphabetMap.get(c); os.write(c); os.writeInt(cval.first); os.writeInt(cval.second); } os.write(alphabet); ByteBuffer bufSA = ByteBuffer.allocate(sa.limit() * SuccinctConstants.LONG_SIZE_BYTES); bufSA.asLongBuffer().put(sa.buffer()); dataChannel.write(bufSA.order(ByteOrder.BIG_ENDIAN)); sa.rewind(); ByteBuffer bufISA = ByteBuffer.allocate(isa.limit() * SuccinctConstants.LONG_SIZE_BYTES); bufISA.asLongBuffer().put(isa.buffer()); dataChannel.write(bufISA.order(ByteOrder.BIG_ENDIAN)); isa.rewind(); ByteBuffer bufColOff = ByteBuffer.allocate(getAlphabetSize() * SuccinctConstants.LONG_SIZE_BYTES); bufColOff.asLongBuffer().put(columnoffsets.buffer()); dataChannel.write(bufColOff.order(ByteOrder.BIG_ENDIAN)); columnoffsets.rewind(); for (int i = 0; i < columns.length; i++) { os.writeInt(columns[i].limit()); dataChannel.write(columns[i].order(ByteOrder.BIG_ENDIAN)); columns[i].rewind(); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code public void writeToStream(DataOutputStream os) throws IOException { WritableByteChannel dataChannel = Channels.newChannel(os); os.writeInt(getOriginalSize()); os.writeInt(getSamplingRateSA()); os.writeInt(getSamplingRateISA()); os.writeInt(getSamplingRateNPA()); os.writeInt(getSampleBitWidth()); os.writeInt(getAlphabetSize()); for (int i = 0; i < getAlphabetSize(); i++) { os.writeInt(alphabet[i]); } ByteBuffer bufSA = ByteBuffer.allocate(sa.limit() * SuccinctConstants.LONG_SIZE_BYTES); bufSA.asLongBuffer().put(sa.buffer()); dataChannel.write(bufSA.order(ByteOrder.BIG_ENDIAN)); sa.rewind(); ByteBuffer bufISA = ByteBuffer.allocate(isa.limit() * SuccinctConstants.LONG_SIZE_BYTES); bufISA.asLongBuffer().put(isa.buffer()); dataChannel.write(bufISA.order(ByteOrder.BIG_ENDIAN)); isa.rewind(); ByteBuffer bufColOff = ByteBuffer.allocate(getAlphabetSize() * SuccinctConstants.LONG_SIZE_BYTES); bufColOff.asLongBuffer().put(columnoffsets.buffer()); dataChannel.write(bufColOff.order(ByteOrder.BIG_ENDIAN)); columnoffsets.rewind(); for (int i = 0; i < columns.length; i++) { os.writeInt(columns[i].limit()); dataChannel.write(columns[i].order(ByteOrder.BIG_ENDIAN)); columns[i].rewind(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws IOException { if (args.length < 2 || args.length > 3) { System.err.println("Parameters: [input-path] [output-path] <[type]>"); System.exit(-1); } File file = new File(args[0]); if (file.length() > 1L << 31) { System.err.println("Cant handle files > 2GB"); System.exit(-1); } byte[] fileData = new byte[(int) file.length()]; System.out.println("File size: " + fileData.length + " bytes"); DataInputStream dis = new DataInputStream(new FileInputStream(file)); dis.readFully(fileData, 0, (int) file.length()); FileOutputStream fos = new FileOutputStream(args[1]); DataOutputStream os = new DataOutputStream(fos); String type = "file"; if (args.length == 3) { type = args[2]; } long start = System.currentTimeMillis(); SuccinctCore.LOG.setLevel(Level.ALL); switch (type) { case "file": { SuccinctFileBuffer.construct(fileData, os); break; } case "indexed-file": { IntArrayList offsets = new IntArrayList(); offsets.add(0); for (int i = 0; i < fileData.length; i++) { if (fileData[i] == '\n') { offsets.add(i + 1); } } SuccinctIndexedFileBuffer.construct(fileData, offsets.toArray(), os); break; } default: throw new UnsupportedOperationException("Unsupported mode: " + type); } long end = System.currentTimeMillis(); System.out.println("Time to construct: " + (end - start) / 1000 + "s"); } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws IOException { if (args.length < 2 || args.length > 3) { System.err.println("Parameters: [input-path] [output-path] <[file-type]>"); System.exit(-1); } File file = new File(args[0]); if (file.length() > 1L << 31) { System.err.println("Cant handle files > 2GB"); System.exit(-1); } FileOutputStream fos = new FileOutputStream(args[1]); DataOutputStream os = new DataOutputStream(fos); String type = "text-file"; if (args.length == 3) { type = args[2]; } long start = System.currentTimeMillis(); SuccinctCore.LOG.setLevel(Level.ALL); switch (type) { case "text-file": { SuccinctFileBuffer.construct(readTextFile(file), os); break; } case "binary-file": { SuccinctFileBuffer.construct(readBinaryFile(file), os); break; } case "indexed-text-file": { char[] fileData = readTextFile(file); IntArrayList offsets = new IntArrayList(); offsets.add(0); for (int i = 0; i < fileData.length; i++) { if (fileData[i] == '\n') { offsets.add(i + 1); } } SuccinctIndexedFileBuffer.construct(fileData, offsets.toArray(), os); break; } case "indexed-binary-file": { byte[] fileData = readBinaryFile(file); IntArrayList offsets = new IntArrayList(); offsets.add(0); for (int i = 0; i < fileData.length; i++) { if (fileData[i] == '\n') { offsets.add(i + 1); } } SuccinctIndexedFileBuffer.construct(fileData, offsets.toArray(), os); break; } default: throw new UnsupportedOperationException("Unsupported mode: " + type); } long end = System.currentTimeMillis(); System.out.println("Time to construct: " + (end - start) / 1000 + "s"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void setUp() throws Exception { super.setUp(); instance = new QSufSort(); File file = new File("data/test_file"); byte[] data = new byte[(int) file.length()]; try { new FileInputStream(file).read(data); } catch (Exception e) { e.printStackTrace(); assertTrue("Could not read from data/test_file.", false); } instance.buildSuffixArray(data); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public void setUp() throws Exception { super.setUp(); instance = new QSufSort(); File inputFile = new File("data/test_file"); byte[] fileData = new byte[(int) inputFile.length()]; DataInputStream dis = new DataInputStream( new FileInputStream(inputFile)); dis.readFully(fileData); byte[] data = (new String(fileData) + (char) 1).getBytes(); instance.buildSuffixArray(data); fileSize = (int) (inputFile.length() + 1); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void readFromFile(String path) throws IOException { FileInputStream fis = new FileInputStream(path); DataInputStream is = new DataInputStream(fis); readFromStream(is); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public void readFromFile(String path) throws IOException { readCoreFromFile(path); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws IOException { if(args.length != 1) { System.err.println("Paramters: [input-path]"); System.exit(-1); } File file = new File(args[0]); if(file.length() > 1L<<31) { System.err.println("Cant handle files > 2GB"); System.exit(-1); } byte[] fileData = new byte[(int) file.length()]; System.out.println("File size: " + fileData.length + " bytes"); DataInputStream dis = new DataInputStream(new FileInputStream(file)); dis.readFully(fileData, 0, (int)file.length()); SuccinctFileBuffer succinctFileBuffer = new SuccinctFileBuffer(fileData); BufferedReader shellReader = new BufferedReader(new InputStreamReader(System.in)); while(true) { System.out.print("succinct> "); String command = shellReader.readLine(); String[] cmdArray = command.split(" "); if(cmdArray[0].compareTo("count") == 0) { if(cmdArray.length != 2) { System.err.println("Could not parse count query."); System.err.println("Usage: count [query]"); continue; } System.out.println("Count[" + cmdArray[1] + "] = " + succinctFileBuffer.count(cmdArray[1].getBytes())); } else if(cmdArray[0].compareTo("search") == 0) { if(cmdArray.length != 2) { System.err.println("Could not parse search query."); System.err.println("Usage: search [query]"); continue; } Long[] results = succinctFileBuffer.search(cmdArray[1].getBytes()); System.out.println("Result size = " + results.length); System.out.print("Search[" + cmdArray[1] + "] = {"); if(results.length < 10) { for (int i = 0; i < results.length; i++) { System.out.print(results[i] + ", "); } System.out.println("}"); } else { for (int i = 0; i < 10; i++) { System.out.print(results[i] + ", "); } System.out.println("...}"); } } else if(cmdArray[0].compareTo("extract") == 0) { if(cmdArray.length != 3) { System.err.println("Could not parse extract query."); System.err.println("Usage: extract [offset] [length]"); continue; } Integer offset, length; try { offset = Integer.parseInt(cmdArray[1]); } catch (Exception e) { System.err.println("[Extract]: Failed to parse offset: must be an integer."); continue; } try { length = Integer.parseInt(cmdArray[2]); } catch (Exception e) { System.err.println("[Extract]: Failed to parse length: must be an integer."); continue; } System.out.println("Extract[" + offset + ", " + length + "] = " + new String(succinctFileBuffer.extract(offset, length))); } else if (cmdArray[0].compareTo("regex") == 0) { if(cmdArray.length != 2) { System.err.println("Could not parse regex query."); System.err.println("Usage: regex [query]"); continue; } Map<Long, Integer> results = null; try { results = succinctFileBuffer.regexSearch(cmdArray[1]); } catch (RegExParsingException e) { System.err.println("Could not parse regular expression: [" + cmdArray[1] + "]"); continue; } System.out.println("Result size = " + results.size()); System.out.print("Regex[" + cmdArray[1] + "] = {"); int count = 0; for (Map.Entry<Long, Integer> entry: results.entrySet()) { if (count >= 10) break; System.out.print("offset = " + entry.getKey() + "; len = " + entry.getValue() + ", "); count++; } System.out.println("...}"); } else if(cmdArray[0].compareTo("quit") == 0) { System.out.println("Quitting..."); break; } else { System.err.println("Unknown command. Command must be one of: count, search, extract, quit."); continue; } } } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws IOException { if(args.length != 1) { System.err.println("Paramters: [input-path]"); System.exit(-1); } SuccinctFileBuffer succinctFileBuffer; if(args[0].endsWith(".succinct")) { succinctFileBuffer = new SuccinctFileBuffer(args[0], StorageMode.MEMORY_ONLY); } else { File file = new File(args[0]); if (file.length() > 1L << 31) { System.err.println("Cant handle files > 2GB"); System.exit(-1); } byte[] fileData = new byte[(int) file.length()]; System.out.println("File size: " + fileData.length + " bytes"); DataInputStream dis = new DataInputStream(new FileInputStream(file)); dis.readFully(fileData, 0, (int) file.length()); succinctFileBuffer = new SuccinctFileBuffer(fileData); } BufferedReader shellReader = new BufferedReader(new InputStreamReader(System.in)); while(true) { System.out.print("succinct> "); String command = shellReader.readLine(); String[] cmdArray = command.split(" "); if(cmdArray[0].compareTo("count") == 0) { if(cmdArray.length != 2) { System.err.println("Could not parse count query."); System.err.println("Usage: count [query]"); continue; } System.out.println("Count[" + cmdArray[1] + "] = " + succinctFileBuffer.count(cmdArray[1].getBytes())); } else if(cmdArray[0].compareTo("search") == 0) { if(cmdArray.length != 2) { System.err.println("Could not parse search query."); System.err.println("Usage: search [query]"); continue; } Long[] results = succinctFileBuffer.search(cmdArray[1].getBytes()); System.out.println("Result size = " + results.length); System.out.print("Search[" + cmdArray[1] + "] = {"); if(results.length < 10) { for (int i = 0; i < results.length; i++) { System.out.print(results[i] + ", "); } System.out.println("}"); } else { for (int i = 0; i < 10; i++) { System.out.print(results[i] + ", "); } System.out.println("...}"); } } else if(cmdArray[0].compareTo("extract") == 0) { if(cmdArray.length != 3) { System.err.println("Could not parse extract query."); System.err.println("Usage: extract [offset] [length]"); continue; } Integer offset, length; try { offset = Integer.parseInt(cmdArray[1]); } catch (Exception e) { System.err.println("[Extract]: Failed to parse offset: must be an integer."); continue; } try { length = Integer.parseInt(cmdArray[2]); } catch (Exception e) { System.err.println("[Extract]: Failed to parse length: must be an integer."); continue; } System.out.println("Extract[" + offset + ", " + length + "] = " + new String(succinctFileBuffer.extract(offset, length))); } else if (cmdArray[0].compareTo("regex") == 0) { if(cmdArray.length != 2) { System.err.println("Could not parse regex query."); System.err.println("Usage: regex [query]"); continue; } Map<Long, Integer> results = null; try { results = succinctFileBuffer.regexSearch(cmdArray[1]); } catch (RegExParsingException e) { System.err.println("Could not parse regular expression: [" + cmdArray[1] + "]"); continue; } System.out.println("Result size = " + results.size()); System.out.print("Regex[" + cmdArray[1] + "] = {"); int count = 0; for (Map.Entry<Long, Integer> entry: results.entrySet()) { if (count >= 10) break; System.out.print("offset = " + entry.getKey() + "; len = " + entry.getValue() + ", "); count++; } System.out.println("...}"); } else if(cmdArray[0].compareTo("quit") == 0) { System.out.println("Quitting..."); break; } else { System.err.println("Unknown command. Command must be one of: count, search, extract, quit."); continue; } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<StorageState> decode(byte[] bs, Charset charset) throws IOException { // 获取对象转换定义 ObjectMateData objectMateData = FdfsParamMapper.getObjectMap(StorageState.class); int fixFieldsTotalSize = objectMateData.getFieldsFixTotalSize(); if (bs.length % fixFieldsTotalSize != 0) { throw new IOException("fixFieldsTotalSize=" + fixFieldsTotalSize + "but byte array length: " + bs.length + " is invalid!"); } // 计算反馈对象数量 int count = bs.length / fixFieldsTotalSize; int offset = 0; List<StorageState> results = new ArrayList<StorageState>(count); for (int i = 0; i < count; i++) { byte[] one = new byte[fixFieldsTotalSize]; System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize); results.add(FdfsParamMapper.map(one, StorageState.class, charset)); offset += fixFieldsTotalSize; } return results; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private List<StorageState> decode(byte[] bs, Charset charset) throws IOException { // 获取对象转换定义 ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(StorageState.class); int fixFieldsTotalSize = objectMataData.getFieldsFixTotalSize(); if (bs.length % fixFieldsTotalSize != 0) { throw new IOException("fixFieldsTotalSize=" + fixFieldsTotalSize + "but byte array length: " + bs.length + " is invalid!"); } // 计算反馈对象数量 int count = bs.length / fixFieldsTotalSize; int offset = 0; List<StorageState> results = new ArrayList<StorageState>(count); for (int i = 0; i < count; i++) { byte[] one = new byte[fixFieldsTotalSize]; System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize); results.add(FdfsParamMapper.map(one, StorageState.class, charset)); offset += fixFieldsTotalSize; } return results; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<GroupState> decode(byte[] bs, Charset charset) throws IOException { // 获取对象转换定义 ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(GroupState.class); int fixFieldsTotalSize = objectMataData.getFieldsFixTotalSize(); if (bs.length % fixFieldsTotalSize != 0) { throw new IOException("byte array length: " + bs.length + " is invalid!"); } // 计算反馈对象数量 int count = bs.length / fixFieldsTotalSize; int offset = 0; List<GroupState> results = new ArrayList<GroupState>(count); for (int i = 0; i < count; i++) { byte[] one = new byte[fixFieldsTotalSize]; System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize); results.add(FdfsParamMapper.map(one, GroupState.class, charset)); offset += fixFieldsTotalSize; } return results; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private List<GroupState> decode(byte[] bs, Charset charset) throws IOException { // 获取对象转换定义 ObjectMetaData objectMetaData = FdfsParamMapper.getObjectMap(GroupState.class); int fixFieldsTotalSize = objectMetaData.getFieldsFixTotalSize(); if (bs.length % fixFieldsTotalSize != 0) { throw new IOException("byte array length: " + bs.length + " is invalid!"); } // 计算反馈对象数量 int count = bs.length / fixFieldsTotalSize; int offset = 0; List<GroupState> results = new ArrayList<GroupState>(count); for (int i = 0; i < count; i++) { byte[] one = new byte[fixFieldsTotalSize]; System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize); results.add(FdfsParamMapper.map(one, GroupState.class, charset)); offset += fixFieldsTotalSize; } return results; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected long getBodyLength(Charset charset) { ObjectMateData objectMateData = FdfsParamMapper.getObjectMap(this.getClass()); return objectMateData.getFieldsSendTotalByteSize(this, charset) + getFileSize(); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code protected long getBodyLength(Charset charset) { ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(this.getClass()); return objectMataData.getFieldsSendTotalByteSize(this, charset) + getFileSize(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected long getBodyLength(Charset charset) { ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(this.getClass()); return objectMataData.getFieldsSendTotalByteSize(this, charset) + getFileSize(); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code protected long getBodyLength(Charset charset) { ObjectMetaData objectMetaData = FdfsParamMapper.getObjectMap(this.getClass()); return objectMetaData.getFieldsSendTotalByteSize(this, charset) + getFileSize(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void service() { int i = 0; try { serverSocket = new ServerSocket(port); } catch (IOException e1) { e1.printStackTrace(); } while (true) { Socket socket = null; try { i++; socket = serverSocket.accept(); // 主线程获取客户端连接 System.out.println("第" + i + "个客户端成功连接!"); Thread workThread = new Thread(new Handler(socket)); // 创建线程 workThread.start(); // 启动线程 } catch (Exception e) { e.printStackTrace(); } } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code public void service() { int i = 0; try { serverSocket = new ServerSocket(port); } catch (BindException e) { LOGGER.error("端口绑定错误", e.getCause()); throw new RuntimeException("端口已经被绑定"); } catch (IOException e1) { LOGGER.error("其他错误", e1.getCause()); throw new RuntimeException(e1.getMessage()); } while (true) { Socket socket = null; try { i++; socket = serverSocket.accept(); // 主线程获取客户端连接 LOGGER.debug("第{}个客户端成功连接!", i); Thread workThread = new Thread(new Handler(socket)); // 创建线程 workThread.start(); // 启动线程 } catch (Exception e) { e.printStackTrace(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConnectionManager() { // 初始化 TrackerConnectionManager manager = new TrackerConnectionManager(createPool()); manager.setTrackerList(trackerIpList); manager.initTracker(); List<GroupState> list = null; // 第一次执行 try { // 连接失败 list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand()); fail("No exception thrown."); } catch (Exception e) { assertTrue(e instanceof FdfsConnectException); } // 第二次执行 try { // 连接失败 list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand()); fail("No exception thrown."); } catch (Exception e) { assertTrue(e instanceof FdfsConnectException); } LOGGER.debug("执行结果{}", list); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testConnectionManager() { // 初始化 TrackerConnectionManager manager = crtInvalidateIpListManager(); List<GroupState> list = null; // 第一次执行 try { // 连接失败 list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand()); fail("No exception thrown."); } catch (Exception e) { assertTrue(e instanceof FdfsConnectException); } // 第二次执行 try { // 连接失败 list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand()); fail("No exception thrown."); } catch (Exception e) { assertTrue(e instanceof FdfsConnectException); } assertNull(list); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testCheck() { // 创建连接测试 Connection conn = createConnection(); System.out.println("当前连接状态" + conn.isValid()); conn.close(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public void testCheck() { // 创建连接测试 Connection conn = createConnection(); LOGGER.debug("当前连接状态={}", conn.isValid()); conn.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<StorageState> decode(byte[] bs, Charset charset) throws IOException { // 获取对象转换定义 ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(StorageState.class); int fixFieldsTotalSize = objectMataData.getFieldsFixTotalSize(); if (bs.length % fixFieldsTotalSize != 0) { throw new IOException("fixFieldsTotalSize=" + fixFieldsTotalSize + "but byte array length: " + bs.length + " is invalid!"); } // 计算反馈对象数量 int count = bs.length / fixFieldsTotalSize; int offset = 0; List<StorageState> results = new ArrayList<StorageState>(count); for (int i = 0; i < count; i++) { byte[] one = new byte[fixFieldsTotalSize]; System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize); results.add(FdfsParamMapper.map(one, StorageState.class, charset)); offset += fixFieldsTotalSize; } return results; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private List<StorageState> decode(byte[] bs, Charset charset) throws IOException { // 获取对象转换定义 ObjectMetaData objectMetaData = FdfsParamMapper.getObjectMap(StorageState.class); int fixFieldsTotalSize = objectMetaData.getFieldsFixTotalSize(); if (bs.length % fixFieldsTotalSize != 0) { throw new IOException("fixFieldsTotalSize=" + fixFieldsTotalSize + "but byte array length: " + bs.length + " is invalid!"); } // 计算反馈对象数量 int count = bs.length / fixFieldsTotalSize; int offset = 0; List<StorageState> results = new ArrayList<StorageState>(count); for (int i = 0; i < count; i++) { byte[] one = new byte[fixFieldsTotalSize]; System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize); results.add(FdfsParamMapper.map(one, StorageState.class, charset)); offset += fixFieldsTotalSize; } return results; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConnectionManager() { // 初始化 TrackerConnectionManager manager = new TrackerConnectionManager(createPool()); manager.setTrackerList(trackerIpList); manager.initTracker(); List<GroupState> list = null; // 第一次执行 try { // 连接失败 list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand()); fail("No exception thrown."); } catch (Exception e) { assertTrue(e instanceof FdfsConnectException); } // 第二次执行 try { // 连接失败 list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand()); fail("No exception thrown."); } catch (Exception e) { assertTrue(e instanceof FdfsConnectException); } LOGGER.debug("执行结果{}", list); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testConnectionManager() { // 初始化 TrackerConnectionManager manager = crtInvalidateIpListManager(); List<GroupState> list = null; // 第一次执行 try { // 连接失败 list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand()); fail("No exception thrown."); } catch (Exception e) { assertTrue(e instanceof FdfsConnectException); } // 第二次执行 try { // 连接失败 list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand()); fail("No exception thrown."); } catch (Exception e) { assertTrue(e instanceof FdfsConnectException); } assertNull(list); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<GroupState> decode(byte[] bs, Charset charset) throws IOException { // 获取对象转换定义 ObjectMateData objectMateData = FdfsParamMapper.getObjectMap(GroupState.class); int fixFieldsTotalSize = objectMateData.getFieldsFixTotalSize(); if (bs.length % fixFieldsTotalSize != 0) { throw new IOException("byte array length: " + bs.length + " is invalid!"); } // 计算反馈对象数量 int count = bs.length / fixFieldsTotalSize; int offset = 0; List<GroupState> results = new ArrayList<GroupState>(count); for (int i = 0; i < count; i++) { byte[] one = new byte[fixFieldsTotalSize]; System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize); results.add(FdfsParamMapper.map(one, GroupState.class, charset)); offset += fixFieldsTotalSize; } return results; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private List<GroupState> decode(byte[] bs, Charset charset) throws IOException { // 获取对象转换定义 ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(GroupState.class); int fixFieldsTotalSize = objectMataData.getFieldsFixTotalSize(); if (bs.length % fixFieldsTotalSize != 0) { throw new IOException("byte array length: " + bs.length + " is invalid!"); } // 计算反馈对象数量 int count = bs.length / fixFieldsTotalSize; int offset = 0; List<GroupState> results = new ArrayList<GroupState>(count); for (int i = 0; i < count; i++) { byte[] one = new byte[fixFieldsTotalSize]; System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize); results.add(FdfsParamMapper.map(one, GroupState.class, charset)); offset += fixFieldsTotalSize; } return results; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testImaging144() throws Exception { tiffOutputSet.setGPSInDegrees(1.0, 1.0); TiffOutputDirectory gpsDirectory = tiffOutputSet.getGPSDirectory(); TiffOutputField gpsVersionId = getGpsVersionId(gpsDirectory); assertNotNull(gpsVersionId); assertTrue(gpsVersionId.bytesEqual(GpsTagConstants.GPS_VERSION)); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testImaging144() throws Exception { tiffOutputSet.setGPSInDegrees(1.0, 1.0); TiffOutputDirectory gpsDirectory = tiffOutputSet.getGPSDirectory(); TiffOutputField gpsVersionId = gpsDirectory.findField(GpsTagConstants.GPS_TAG_GPS_VERSION_ID); assertNotNull(gpsVersionId); assertTrue(gpsVersionId.bytesEqual(GpsTagConstants.GPS_VERSION)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<IptcBlock> parseAllBlocks(byte bytes[], boolean verbose, boolean strict) throws ImageReadException, IOException { List<IptcBlock> blocks = new ArrayList<IptcBlock>(); BinaryInputStream bis = new BinaryInputStream(bytes, APP13_BYTE_ORDER); // Note that these are unsigned quantities. Name is always an even // number of bytes (including the 1st byte, which is the size.) byte[] idString = bis.readByteArray( PHOTOSHOP_IDENTIFICATION_STRING.size(), "App13 Segment missing identification string"); if (!PHOTOSHOP_IDENTIFICATION_STRING.equals(idString)) throw new ImageReadException("Not a Photoshop App13 Segment"); // int index = PHOTOSHOP_IDENTIFICATION_STRING.length; while (true) { byte[] imageResourceBlockSignature = bis .readByteArray(CONST_8BIM.size(), "App13 Segment missing identification string", false, false); if (null == imageResourceBlockSignature) break; if (!CONST_8BIM.equals(imageResourceBlockSignature)) throw new ImageReadException( "Invalid Image Resource Block Signature"); int blockType = bis .read2ByteInteger("Image Resource Block missing type"); if (verbose) Debug.debug("blockType", blockType + " (0x" + Integer.toHexString(blockType) + ")"); int blockNameLength = bis .read1ByteInteger("Image Resource Block missing name length"); if (verbose && blockNameLength > 0) Debug.debug("blockNameLength", blockNameLength + " (0x" + Integer.toHexString(blockNameLength) + ")"); byte[] blockNameBytes; if (blockNameLength == 0) { bis.read1ByteInteger("Image Resource Block has invalid name"); blockNameBytes = new byte[0]; } else { blockNameBytes = bis.readByteArray(blockNameLength, "Invalid Image Resource Block name", verbose, strict); if (null == blockNameBytes) break; if (blockNameLength % 2 == 0) bis.read1ByteInteger("Image Resource Block missing padding byte"); } int blockSize = bis .read4ByteInteger("Image Resource Block missing size"); if (verbose) Debug.debug("blockSize", blockSize + " (0x" + Integer.toHexString(blockSize) + ")"); /* * doesn't catch cases where blocksize is invalid but is still less * than bytes.length but will at least prevent OutOfMemory errors */ if (blockSize > bytes.length) { throw new ImageReadException("Invalid Block Size : " + blockSize + " > " + bytes.length); } byte[] blockData = bis.readByteArray(blockSize, "Invalid Image Resource Block data", verbose, strict); if (null == blockData) break; blocks.add(new IptcBlock(blockType, blockNameBytes, blockData)); if ((blockSize % 2) != 0) bis.read1ByteInteger("Image Resource Block missing padding byte"); } return blocks; } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code protected List<IptcBlock> parseAllBlocks(byte bytes[], boolean verbose, boolean strict) throws ImageReadException, IOException { List<IptcBlock> blocks = new ArrayList<IptcBlock>(); BinaryInputStream bis = null; try { bis = new BinaryInputStream(bytes, APP13_BYTE_ORDER); // Note that these are unsigned quantities. Name is always an even // number of bytes (including the 1st byte, which is the size.) byte[] idString = bis.readByteArray( PHOTOSHOP_IDENTIFICATION_STRING.size(), "App13 Segment missing identification string"); if (!PHOTOSHOP_IDENTIFICATION_STRING.equals(idString)) throw new ImageReadException("Not a Photoshop App13 Segment"); // int index = PHOTOSHOP_IDENTIFICATION_STRING.length; while (true) { byte[] imageResourceBlockSignature = bis .readByteArray(CONST_8BIM.size(), "App13 Segment missing identification string", false, false); if (null == imageResourceBlockSignature) break; if (!CONST_8BIM.equals(imageResourceBlockSignature)) throw new ImageReadException( "Invalid Image Resource Block Signature"); int blockType = bis .read2ByteInteger("Image Resource Block missing type"); if (verbose) Debug.debug("blockType", blockType + " (0x" + Integer.toHexString(blockType) + ")"); int blockNameLength = bis .read1ByteInteger("Image Resource Block missing name length"); if (verbose && blockNameLength > 0) Debug.debug("blockNameLength", blockNameLength + " (0x" + Integer.toHexString(blockNameLength) + ")"); byte[] blockNameBytes; if (blockNameLength == 0) { bis.read1ByteInteger("Image Resource Block has invalid name"); blockNameBytes = new byte[0]; } else { blockNameBytes = bis.readByteArray(blockNameLength, "Invalid Image Resource Block name", verbose, strict); if (null == blockNameBytes) break; if (blockNameLength % 2 == 0) bis.read1ByteInteger("Image Resource Block missing padding byte"); } int blockSize = bis .read4ByteInteger("Image Resource Block missing size"); if (verbose) Debug.debug("blockSize", blockSize + " (0x" + Integer.toHexString(blockSize) + ")"); /* * doesn't catch cases where blocksize is invalid but is still less * than bytes.length but will at least prevent OutOfMemory errors */ if (blockSize > bytes.length) { throw new ImageReadException("Invalid Block Size : " + blockSize + " > " + bytes.length); } byte[] blockData = bis.readByteArray(blockSize, "Invalid Image Resource Block data", verbose, strict); if (null == blockData) break; blocks.add(new IptcBlock(blockType, blockNameBytes, blockData)); if ((blockSize % 2) != 0) bis.read1ByteInteger("Image Resource Block missing padding byte"); } return blocks; } finally { if (bis != null) { bis.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void dump() { dump(new PrintWriter(new OutputStreamWriter(System.out))); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public void dump() { PrintWriter pw = new PrintWriter(System.out); dump(pw); pw.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public final byte[] deflate(byte bytes[]) throws IOException { ByteArrayInputStream in = new ByteArrayInputStream(bytes); DeflaterInputStream zIn = new DeflaterInputStream(in); return getStreamBytes(zIn); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public final byte[] deflate(byte bytes[]) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream dos = new DeflaterOutputStream(baos); dos.write(bytes); dos.flush(); return baos.toByteArray(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public final void debugNumber(String msg, int data, int bytes) { debugNumber(new PrintWriter(new OutputStreamWriter(System.out)), msg, data, bytes); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public final void debugNumber(String msg, int data, int bytes) { PrintWriter pw = new PrintWriter(System.out); debugNumber(pw, msg, data, bytes); pw.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public byte[] compress(byte bytes[]) throws IOException { MyByteArrayOutputStream baos = new MyByteArrayOutputStream( bytes.length * 2); // max length 1 extra byte for every 128 int ptr = 0; int count = 0; while (ptr < bytes.length) { count++; int dup = findNextDuplicate(bytes, ptr); if (dup == ptr) // write run length { int len = findRunLength(bytes, dup); int actual_len = Math.min(len, 128); baos.write(-(actual_len - 1)); baos.write(bytes[ptr]); ptr += actual_len; } else { // write literals int len = dup - ptr; if (dup > 0) { int runlen = findRunLength(bytes, dup); if (runlen < 3) // may want to discard next run. { int nextptr = ptr + len + runlen; int nextdup = findNextDuplicate(bytes, nextptr); if (nextdup != nextptr) // discard 2-byte run { dup = nextdup; len = dup - ptr; } } } if (dup < 0) len = bytes.length - ptr; int actual_len = Math.min(len, 128); baos.write(actual_len - 1); for (int i = 0; i < actual_len; i++) { baos.write(bytes[ptr]); ptr++; } } } byte result[] = baos.toByteArray(); return result; } #location 46 #vulnerability type RESOURCE_LEAK
#fixed code public byte[] compress(byte bytes[]) throws IOException { MyByteArrayOutputStream baos = null; try { baos = new MyByteArrayOutputStream( bytes.length * 2); // max length 1 extra byte for every 128 int ptr = 0; int count = 0; while (ptr < bytes.length) { count++; int dup = findNextDuplicate(bytes, ptr); if (dup == ptr) // write run length { int len = findRunLength(bytes, dup); int actual_len = Math.min(len, 128); baos.write(-(actual_len - 1)); baos.write(bytes[ptr]); ptr += actual_len; } else { // write literals int len = dup - ptr; if (dup > 0) { int runlen = findRunLength(bytes, dup); if (runlen < 3) // may want to discard next run. { int nextptr = ptr + len + runlen; int nextdup = findNextDuplicate(bytes, nextptr); if (nextdup != nextptr) // discard 2-byte run { dup = nextdup; len = dup - ptr; } } } if (dup < 0) len = bytes.length - ptr; int actual_len = Math.min(len, 128); baos.write(actual_len - 1); for (int i = 0; i < actual_len; i++) { baos.write(bytes[ptr]); ptr++; } } } byte result[] = baos.toByteArray(); return result; } finally { if (baos != null) { baos.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] decompressModifiedHuffman(final byte[] compressed, final int width, final int height) throws ImageReadException { final BitInputStreamFlexible inputStream = new BitInputStreamFlexible( new ByteArrayInputStream(compressed)); BitArrayOutputStream outputStream = null; boolean canThrow = false; try { outputStream = new BitArrayOutputStream(); for (int y = 0; y < height; y++) { int color = WHITE; int rowLength; for (rowLength = 0; rowLength < width;) { final int runLength = readTotalRunLength(inputStream, color); for (int i = 0; i < runLength; i++) { outputStream.writeBit(color); } color = 1 - color; rowLength += runLength; } if (rowLength == width) { inputStream.flushCache(); outputStream.flush(); } else if (rowLength > width) { throw new ImageReadException("Unrecoverable row length error in image row " + y); } } final byte[] ret = outputStream.toByteArray(); canThrow = true; return ret; } finally { try { IoUtils.closeQuietly(canThrow, outputStream); } catch (final IOException ioException) { throw new ImageReadException("I/O error", ioException); } } } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code public static byte[] decompressModifiedHuffman(final byte[] compressed, final int width, final int height) throws ImageReadException { try (ByteArrayInputStream baos = new ByteArrayInputStream(compressed); BitInputStreamFlexible inputStream = new BitInputStreamFlexible(baos); BitArrayOutputStream outputStream = new BitArrayOutputStream()) { for (int y = 0; y < height; y++) { int color = WHITE; int rowLength; for (rowLength = 0; rowLength < width;) { final int runLength = readTotalRunLength(inputStream, color); for (int i = 0; i < runLength; i++) { outputStream.writeBit(color); } color = 1 - color; rowLength += runLength; } if (rowLength == width) { inputStream.flushCache(); outputStream.flush(); } else if (rowLength > width) { throw new ImageReadException("Unrecoverable row length error in image row " + y); } } final byte[] ret = outputStream.toByteArray(); return ret; } catch (final IOException ioException) { throw new ImageReadException("Error reading image to decompress", ioException); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public byte[] getAll() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = null; boolean canThrow = false; try { is = new FileInputStream(file); is = new BufferedInputStream(is); final byte[] buffer = new byte[1024]; int read; while ((read = is.read(buffer)) > 0) { baos.write(buffer, 0, read); } final byte[] ret = baos.toByteArray(); canThrow = true; return ret; } finally { IoUtils.closeQuietly(canThrow, is); } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Override public byte[] getAll() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (FileInputStream fis = new FileInputStream(file); InputStream is = new BufferedInputStream(fis)) { final byte[] buffer = new byte[1024]; int read; while ((read = is.read(buffer)) > 0) { baos.write(buffer, 0, read); } final byte[] ret = baos.toByteArray(); return ret; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void removeExifMetadata(final File jpegImageFile, final File dst) throws IOException, ImageReadException, ImageWriteException { OutputStream os = null; boolean canThrow = false; try { os = new FileOutputStream(dst); os = new BufferedOutputStream(os); new ExifRewriter().removeExifMetadata(jpegImageFile, os); canThrow = true; } finally { IoUtils.closeQuietly(canThrow, os); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code public void removeExifMetadata(final File jpegImageFile, final File dst) throws IOException, ImageReadException, ImageWriteException { try (FileOutputStream fos = new FileOutputStream(dst); OutputStream os = new BufferedOutputStream(fos)) { new ExifRewriter().removeExifMetadata(jpegImageFile, os); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void dump() { dump(new PrintWriter(new OutputStreamWriter(System.out))); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public void dump() { PrintWriter pw = new PrintWriter(System.out); dump(pw); pw.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void writeImage(BufferedImage src, OutputStream os, Map params) throws ImageWriteException, IOException { // make copy of params; we'll clear keys as we consume them. params = (params == null) ? new HashMap() : new HashMap(params); Integer xResolution = Integer.valueOf(0); Integer yResolution = Integer.valueOf(0); // clear format key. if (params.containsKey(PARAM_KEY_FORMAT)) params.remove(PARAM_KEY_FORMAT); if (params.containsKey(PARAM_KEY_X_RESOLUTION)) xResolution = (Integer) params.remove(PARAM_KEY_X_RESOLUTION); if (params.containsKey(PARAM_KEY_Y_RESOLUTION)) yResolution = (Integer) params.remove(PARAM_KEY_Y_RESOLUTION); if (params.size() > 0) { Object firstKey = params.keySet().iterator().next(); throw new ImageWriteException("Unknown parameter: " + firstKey); } final SimplePalette palette = new PaletteFactory().makePaletteSimple( src, 256); BmpWriter writer = null; if (palette == null) writer = new BmpWriterRgb(); else writer = new BmpWriterPalette(palette); byte imagedata[] = writer.getImageData(src); BinaryOutputStream bos = new BinaryOutputStream(os, BYTE_ORDER_INTEL); { // write BitmapFileHeader os.write(0x42); // B, Windows 3.1x, 95, NT, Bitmap os.write(0x4d); // M int filesize = BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_SIZE + // header // size 4 * writer.getPaletteSize() + // palette size in bytes imagedata.length; bos.write4Bytes(filesize); bos.write4Bytes(0); // reserved bos.write4Bytes(BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_SIZE + 4 * writer.getPaletteSize()); // Bitmap Data Offset } int width = src.getWidth(); int height = src.getHeight(); { // write BitmapInfoHeader bos.write4Bytes(BITMAP_INFO_HEADER_SIZE); // Bitmap Info Header Size bos.write4Bytes(width); // width bos.write4Bytes(height); // height bos.write2Bytes(1); // Number of Planes bos.write2Bytes(writer.getBitsPerPixel()); // Bits Per Pixel bos.write4Bytes(BI_RGB); // Compression bos.write4Bytes(imagedata.length); // Bitmap Data Size bos.write4Bytes(xResolution.intValue()); // HResolution bos.write4Bytes(yResolution.intValue()); // VResolution if (palette == null) bos.write4Bytes(0); // Colors else bos.write4Bytes(palette.length()); // Colors bos.write4Bytes(0); // Important Colors // bos.write_4_bytes(0); // Compression } { // write Palette writer.writePalette(bos); } { // write Image Data bos.writeByteArray(imagedata); } } #location 78 #vulnerability type RESOURCE_LEAK
#fixed code public void writeImage(BufferedImage src, OutputStream os, Map params) throws ImageWriteException, IOException { // make copy of params; we'll clear keys as we consume them. params = (params == null) ? new HashMap() : new HashMap(params); PixelDensity pixelDensity = null; // clear format key. if (params.containsKey(PARAM_KEY_FORMAT)) params.remove(PARAM_KEY_FORMAT); if (params.containsKey(PARAM_KEY_PIXEL_DENSITY)) pixelDensity = (PixelDensity) params.remove(PARAM_KEY_PIXEL_DENSITY); if (params.size() > 0) { Object firstKey = params.keySet().iterator().next(); throw new ImageWriteException("Unknown parameter: " + firstKey); } final SimplePalette palette = new PaletteFactory().makePaletteSimple( src, 256); BmpWriter writer = null; if (palette == null) writer = new BmpWriterRgb(); else writer = new BmpWriterPalette(palette); byte imagedata[] = writer.getImageData(src); BinaryOutputStream bos = new BinaryOutputStream(os, BYTE_ORDER_INTEL); { // write BitmapFileHeader os.write(0x42); // B, Windows 3.1x, 95, NT, Bitmap os.write(0x4d); // M int filesize = BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_SIZE + // header // size 4 * writer.getPaletteSize() + // palette size in bytes imagedata.length; bos.write4Bytes(filesize); bos.write4Bytes(0); // reserved bos.write4Bytes(BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_SIZE + 4 * writer.getPaletteSize()); // Bitmap Data Offset } int width = src.getWidth(); int height = src.getHeight(); { // write BitmapInfoHeader bos.write4Bytes(BITMAP_INFO_HEADER_SIZE); // Bitmap Info Header Size bos.write4Bytes(width); // width bos.write4Bytes(height); // height bos.write2Bytes(1); // Number of Planes bos.write2Bytes(writer.getBitsPerPixel()); // Bits Per Pixel bos.write4Bytes(BI_RGB); // Compression bos.write4Bytes(imagedata.length); // Bitmap Data Size bos.write4Bytes(pixelDensity != null ? (int)Math.round(pixelDensity.horizontalDensityMetres()) : 0); // HResolution bos.write4Bytes(pixelDensity != null ? (int)Math.round(pixelDensity.verticalDensityMetres()) : 0); // VResolution if (palette == null) bos.write4Bytes(0); // Colors else bos.write4Bytes(palette.length()); // Colors bos.write4Bytes(0); // Important Colors // bos.write_4_bytes(0); // Compression } { // write Palette writer.writePalette(bos); } { // write Image Data bos.writeByteArray(imagedata); } }
Below is the vulnerable code, please generate the patch based on the following information.