instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getArchName() { String osArch = System.getProperty("os.arch"); if(osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); }
#vulnerable code public static String getArchName() { String osArch = System.getProperty("os.arch"); if(osArch.startsWith("arm")) { // Java 1.8 introduces a system property to determine armel or armhf if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) { return translateArchNameToFolderName("armhf"); } // For java7, we stil need to if run some shell commands to determine ABI of JVM if(System.getProperty("os.name").contains("Linux")) { String javaHome = System.getProperty("java.home"); try { // determine if first JVM found uses ARM hard-float ABI int exitCode = Runtime.getRuntime().exec("which readelf").waitFor(); if(exitCode == 0) { String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'"}; exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if (exitCode == 0) { return translateArchNameToFolderName("armhf"); } } else { System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " + "armel architecture will be presumed."); } } catch(IOException e) { // ignored: fall back to "arm" arch (soft-float ABI) } catch(InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code int shared_cache(boolean enable) throws SQLException { // The shared cache is per-process, so it is useless as // each nested connection is its own process. return -1; }
#vulnerable code int enable_load_extension(boolean enable) throws SQLException { return call("sqlite3_enable_load_extension", handle, enable ? 1 : 0); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setMaxRows(int max) throws SQLException { //checkOpen(); if (max < 0) throw new SQLException("max row count must be >= 0"); rs.maxRows = max; }
#vulnerable code public void setMaxRows(int max) throws SQLException { checkOpen(); if (max < 0) throw new SQLException("max row count must be >= 0"); rs.maxRows = max; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; final String prefix = String.format("sqlite-%s-", getVersion()); String extractedLibFileName = prefix + libraryFileName; File extractedLibFile = new File(targetFolder, extractedLibFileName); try { if (extractedLibFile.exists()) { // test md5sum value String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath)); String md5sum2 = md5sum(new FileInputStream(extractedLibFile)); if (md5sum1.equals(md5sum2)) { return loadNativeLibrary(targetFolder, extractedLibFileName); } else { // remove old native library file boolean deletionSucceeded = extractedLibFile.delete(); if (!deletionSucceeded) { throw new IOException("failed to remove existing native library file: " + extractedLibFile.getAbsolutePath()); } } } // extract file into the current directory InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); FileOutputStream writer = new FileOutputStream(extractedLibFile); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); } writer.close(); reader.close(); if (!System.getProperty("os.name").contains("Windows")) { try { Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() }) .waitFor(); } catch (Throwable e) {} } return loadNativeLibrary(targetFolder, extractedLibFileName); } catch (IOException e) { System.err.println(e.getMessage()); return false; } catch (NoSuchAlgorithmException e) { System.err.println(e.getMessage()); return false; } }
#vulnerable code private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; final String prefix = "sqlite-3.6.4-"; String extractedLibFileName = prefix + libraryFileName; File extractedLibFile = new File(targetFolder, extractedLibFileName); try { if (extractedLibFile.exists()) { // test md5sum value String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath)); String md5sum2 = md5sum(new FileInputStream(extractedLibFile)); if (md5sum1.equals(md5sum2)) { return loadNativeLibrary(targetFolder, extractedLibFileName); } else { // remove old native library file boolean deletionSucceeded = extractedLibFile.delete(); if (!deletionSucceeded) { throw new IOException("failed to remove existing native library file: " + extractedLibFile.getAbsolutePath()); } } } // extract file into the current directory InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); FileOutputStream writer = new FileOutputStream(extractedLibFile); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); } writer.close(); reader.close(); if (!System.getProperty("os.name").contains("Windows")) { try { Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() }) .waitFor(); } catch (Throwable e) {} } return loadNativeLibrary(targetFolder, extractedLibFileName); } catch (IOException e) { System.err.println(e.getMessage()); return false; } catch (NoSuchAlgorithmException e) { System.err.println(e.getMessage()); return false; } } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getArchName() { String osArch = System.getProperty("os.arch"); if(osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); }
#vulnerable code public static String getArchName() { String osArch = System.getProperty("os.arch"); if(osArch.startsWith("arm")) { // Java 1.8 introduces a system property to determine armel or armhf if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) { return translateArchNameToFolderName("armhf"); } // For java7, we stil need to if run some shell commands to determine ABI of JVM if(System.getProperty("os.name").contains("Linux")) { String javaHome = System.getProperty("java.home"); try { // determine if first JVM found uses ARM hard-float ABI int exitCode = Runtime.getRuntime().exec("which readelf").waitFor(); if(exitCode == 0) { String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'"}; exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if (exitCode == 0) { return translateArchNameToFolderName("armhf"); } } else { System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " + "armel architecture will be presumed."); } } catch(IOException e) { // ignored: fall back to "arm" arch (soft-float ABI) } catch(InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; // Include architecture name in temporary filename in order to avoid conflicts // when multiple JVMs with different architectures running at the same time String uuid = UUID.randomUUID().toString(); String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName); String extractedLckFileName = extractedLibFileName + ".lck"; File extractedLibFile = new File(targetFolder, extractedLibFileName); File extractedLckFile = new File(targetFolder, extractedLckFileName); try { // Extract a native library file into the target directory InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); FileOutputStream writer = new FileOutputStream(extractedLibFile); try { byte[] buffer = new byte[8192]; int bytesRead = 0; while((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); } } finally { if (!extractedLckFile.exists()) { new FileOutputStream(extractedLckFile).close(); } // Delete the extracted lib file on JVM exit. extractedLibFile.deleteOnExit(); extractedLckFile.deleteOnExit(); if(writer != null) { writer.close(); } if(reader != null) { reader.close(); } } // Set executable (x) flag to enable Java to load the native library extractedLibFile.setReadable(true); extractedLibFile.setWritable(true, true); extractedLibFile.setExecutable(true); // Check whether the contents are properly copied from the resource folder { InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); InputStream extractedLibIn = new FileInputStream(extractedLibFile); try { if(!contentsEquals(nativeIn, extractedLibIn)) { throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile)); } } finally { if(nativeIn != null) { nativeIn.close(); } if(extractedLibIn != null) { extractedLibIn.close(); } } } return loadNativeLibrary(targetFolder, extractedLibFileName); } catch(IOException e) { System.err.println(e.getMessage()); return false; } }
#vulnerable code private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; // Include architecture name in temporary filename in order to avoid conflicts // when multiple JVMs with different architectures running at the same time String uuid = UUID.randomUUID().toString(); String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName); File extractedLibFile = new File(targetFolder, extractedLibFileName); try { // Extract a native library file into the target directory InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); FileOutputStream writer = new FileOutputStream(extractedLibFile); try { byte[] buffer = new byte[8192]; int bytesRead = 0; while((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); } } finally { // Delete the extracted lib file on JVM exit. extractedLibFile.deleteOnExit(); if(writer != null) { writer.close(); } if(reader != null) { reader.close(); } } // Set executable (x) flag to enable Java to load the native library extractedLibFile.setReadable(true); extractedLibFile.setWritable(true, true); extractedLibFile.setExecutable(true); // Check whether the contents are properly copied from the resource folder { InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); InputStream extractedLibIn = new FileInputStream(extractedLibFile); try { if(!contentsEquals(nativeIn, extractedLibIn)) { throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile)); } } finally { if(nativeIn != null) { nativeIn.close(); } if(extractedLibIn != null) { extractedLibIn.close(); } } } return loadNativeLibrary(targetFolder, extractedLibFileName); } catch(IOException e) { System.err.println(e.getMessage()); return false; } } #location 43 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getArchName() { String osArch = System.getProperty("os.arch"); if(osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); }
#vulnerable code public static String getArchName() { String osArch = System.getProperty("os.arch"); if(osArch.startsWith("arm")) { // Java 1.8 introduces a system property to determine armel or armhf if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) { return translateArchNameToFolderName("armhf"); } // For java7, we stil need to if run some shell commands to determine ABI of JVM if(System.getProperty("os.name").contains("Linux")) { String javaHome = System.getProperty("java.home"); try { // determine if first JVM found uses ARM hard-float ABI int exitCode = Runtime.getRuntime().exec("which readelf").waitFor(); if(exitCode == 0) { String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'"}; exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if (exitCode == 0) { return translateArchNameToFolderName("armhf"); } } else { System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " + "armel architecture will be presumed."); } } catch(IOException e) { // ignored: fall back to "arm" arch (soft-float ABI) } catch(InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean execute(String sql) throws SQLException { internalClose(); SQLExtension ext = ExtendedCommand.parse(sql); if (ext != null) { ext.execute(db); return false; } this.sql = sql; db.prepare(this); return exec(); }
#vulnerable code public boolean execute(String sql) throws SQLException { internalClose(); SQLExtension ext = ExtendedCommand.parse(sql); if (ext != null) { ext.execute(db); return false; } this.sql = sql; boolean success = false; try { db.prepare(this); final boolean result = exec(); success = true; return result; } finally { if (!success) { internalClose(); } } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setTypeMap(Map map) throws SQLException { synchronized (this) { this.typeMap = map; } }
#vulnerable code public void setTypeMap(Map map) throws SQLException { synchronized (typeMap) { this.typeMap = map; } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; // Include architecture name in temporary filename in order to avoid conflicts // when multiple JVMs with different architectures running at the same time String uuid = UUID.randomUUID().toString(); String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName); String extractedLckFileName = extractedLibFileName + ".lck"; File extractedLibFile = new File(targetFolder, extractedLibFileName); File extractedLckFile = new File(targetFolder, extractedLckFileName); try { // Extract a native library file into the target directory InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); FileOutputStream writer = new FileOutputStream(extractedLibFile); try { byte[] buffer = new byte[8192]; int bytesRead = 0; while((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); } } finally { if (!extractedLckFile.exists()) { new FileOutputStream(extractedLckFile).close(); } // Delete the extracted lib file on JVM exit. extractedLibFile.deleteOnExit(); extractedLckFile.deleteOnExit(); if(writer != null) { writer.close(); } if(reader != null) { reader.close(); } } // Set executable (x) flag to enable Java to load the native library extractedLibFile.setReadable(true); extractedLibFile.setWritable(true, true); extractedLibFile.setExecutable(true); // Check whether the contents are properly copied from the resource folder { InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); InputStream extractedLibIn = new FileInputStream(extractedLibFile); try { if(!contentsEquals(nativeIn, extractedLibIn)) { throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile)); } } finally { if(nativeIn != null) { nativeIn.close(); } if(extractedLibIn != null) { extractedLibIn.close(); } } } return loadNativeLibrary(targetFolder, extractedLibFileName); } catch(IOException e) { System.err.println(e.getMessage()); return false; } }
#vulnerable code private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; // Include architecture name in temporary filename in order to avoid conflicts // when multiple JVMs with different architectures running at the same time String uuid = UUID.randomUUID().toString(); String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName); File extractedLibFile = new File(targetFolder, extractedLibFileName); try { // Extract a native library file into the target directory InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); FileOutputStream writer = new FileOutputStream(extractedLibFile); try { byte[] buffer = new byte[8192]; int bytesRead = 0; while((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); } } finally { // Delete the extracted lib file on JVM exit. extractedLibFile.deleteOnExit(); if(writer != null) { writer.close(); } if(reader != null) { reader.close(); } } // Set executable (x) flag to enable Java to load the native library extractedLibFile.setReadable(true); extractedLibFile.setWritable(true, true); extractedLibFile.setExecutable(true); // Check whether the contents are properly copied from the resource folder { InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath); InputStream extractedLibIn = new FileInputStream(extractedLibFile); try { if(!contentsEquals(nativeIn, extractedLibIn)) { throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile)); } } finally { if(nativeIn != null) { nativeIn.close(); } if(extractedLibIn != null) { extractedLibIn.close(); } } } return loadNativeLibrary(targetFolder, extractedLibFileName); } catch(IOException e) { System.err.println(e.getMessage()); return false; } } #location 56 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GetMapping() public String profile(ModelMap mmap) { SysUser user = getSysUser(); user.setSex(dictDataService.selectDictLabel("sys_user_sex", user.getSex())); mmap.put("user", user); mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId())); mmap.put("postGroup", userService.selectUserPostGroup(user.getUserId())); return prefix + "/profile"; }
#vulnerable code @GetMapping() public String profile(ModelMap mmap) { SysUser user = getUser(); user.setSex(dictDataService.selectDictLabel("sys_user_sex", user.getSex())); mmap.put("user", user); mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId())); mmap.put("postGroup", userService.selectUserPostGroup(user.getUserId())); return prefix + "/profile"; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Async protected void handleLog(final JoinPoint joinPoint, final Exception e) { try { // 获得注解 Log controllerLog = getAnnotationLog(joinPoint); if (controllerLog == null) { return; } // 获取当前的用户 User currentUser = ShiroUtils.getUser(); // *========数据库日志=========*// OperLog operLog = new OperLog(); operLog.setStatus(BusinessStatus.SUCCESS); // 请求的地址 String ip = ShiroUtils.getIp(); operLog.setOperIp(ip); // 操作地点 operLog.setOperLocation(AddressUtils.getRealAddressByIP(ip)); operLog.setOperUrl(ServletUtils.getRequest().getRequestURI()); if (currentUser != null) { operLog.setOperName(currentUser.getLoginName()); if (StringUtils.isNotNull(currentUser.getDept()) && StringUtils.isEmpty(currentUser.getDept().getDeptName())) { operLog.setDeptName(currentUser.getDept().getDeptName()); } } if (e != null) { operLog.setStatus(BusinessStatus.FAIL); operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000)); } // 设置方法名称 String className = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); operLog.setMethod(className + "." + methodName + "()"); // 处理设置注解上的参数 getControllerMethodDescription(controllerLog, operLog); // 保存数据库 operLogService.insertOperlog(operLog); } catch (Exception exp) { // 记录本地异常日志 log.error("==前置通知异常=="); log.error("异常信息:{}", exp.getMessage()); exp.printStackTrace(); } }
#vulnerable code @Async protected void handleLog(final JoinPoint joinPoint, final Exception e) { try { // 获得注解 Log controllerLog = getAnnotationLog(joinPoint); if (controllerLog == null) { return; } // 获取当前的用户 User currentUser = ShiroUtils.getUser(); // *========数据库日志=========*// OperLog operLog = new OperLog(); operLog.setStatus(BusinessStatus.SUCCESS); // 请求的地址 String ip = ShiroUtils.getIp(); operLog.setOperIp(ip); // 操作地点 operLog.setOperLocation(AddressUtils.getRealAddressByIP(ip)); operLog.setOperUrl(ServletUtils.getRequest().getRequestURI()); if (currentUser != null) { operLog.setOperName(currentUser.getLoginName()); operLog.setDeptName(currentUser.getDept().getDeptName()); } if (e != null) { operLog.setStatus(BusinessStatus.FAIL); operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000)); } // 设置方法名称 String className = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); operLog.setMethod(className + "." + methodName + "()"); // 处理设置注解上的参数 getControllerMethodDescription(controllerLog, operLog); // 保存数据库 operLogService.insertOperlog(operLog); } catch (Exception exp) { // 记录本地异常日志 log.error("==前置通知异常=="); log.error("异常信息:{}", exp.getMessage()); exp.printStackTrace(); } } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GetMapping("/checkPassword") @ResponseBody public boolean checkPassword(String password) { SysUser user = getSysUser(); String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString(); if (user.getPassword().equals(encrypt)) { return true; } return false; }
#vulnerable code @GetMapping("/checkPassword") @ResponseBody public boolean checkPassword(String password) { SysUser user = getUser(); String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString(); if (user.getPassword().equals(encrypt)) { return true; } return false; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getLoginName() { return getSysUser().getLoginName(); }
#vulnerable code public static String getLoginName() { return getUser().getLoginName(); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Long getUserId() { return getSysUser().getUserId(); }
#vulnerable code public Long getUserId() { return getUser().getUserId(); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Long getUserId() { return getSysUser().getUserId().longValue(); }
#vulnerable code public static Long getUserId() { return getUser().getUserId().longValue(); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<T> importExcel(String sheetName, InputStream input) throws Exception { List<T> list = new ArrayList<T>(); Workbook workbook = WorkbookFactory.create(input); Sheet sheet = null; if (StringUtils.isNotEmpty(sheetName)) { // 如果指定sheet名,则取指定sheet中的内容. sheet = workbook.getSheet(sheetName); } else { // 如果传入的sheet名不存在则默认指向第1个sheet. sheet = workbook.getSheetAt(0); } if (sheet == null) { throw new IOException("文件sheet不存在"); } int rows = sheet.getPhysicalNumberOfRows(); if (rows > 0) { // 默认序号 int serialNum = 0; // 有数据时才处理 得到类的所有field. Field[] allFields = clazz.getDeclaredFields(); // 定义一个map用于存放列的序号和field. Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>(); for (int col = 0; col < allFields.length; col++) { Field field = allFields[col]; // 将有注解的field存放到map中. if (field.isAnnotationPresent(Excel.class)) { // 设置类的私有字段属性可访问. field.setAccessible(true); fieldsMap.put(++serialNum, field); } } for (int i = 1; i < rows; i++) { // 从第2行开始取数据,默认第一行是表头. Row row = sheet.getRow(i); int cellNum = serialNum; T entity = null; for (int j = 0; j < cellNum; j++) { Cell cell = row.getCell(j); if (cell == null) { continue; } else { // 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了 row.getCell(j).setCellType(CellType.STRING); cell = row.getCell(j); } String c = cell.getStringCellValue(); if (StringUtils.isEmpty(c)) { continue; } // 如果不存在实例则新建. entity = (entity == null ? clazz.newInstance() : entity); // 从map中得到对应列的field. Field field = fieldsMap.get(j + 1); // 取得类型,并根据对象类型设置值. Class<?> fieldType = field.getType(); if (String.class == fieldType) { field.set(entity, String.valueOf(c)); } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) { field.set(entity, Integer.parseInt(c)); } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) { field.set(entity, Long.valueOf(c)); } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) { field.set(entity, Float.valueOf(c)); } else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) { field.set(entity, Short.valueOf(c)); } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) { field.set(entity, Double.valueOf(c)); } else if (Character.TYPE == fieldType) { if ((c != null) && (c.length() > 0)) { field.set(entity, Character.valueOf(c.charAt(0))); } } else if (java.util.Date.class == fieldType) { if (cell.getCellTypeEnum() == CellType.NUMERIC) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cell.setCellValue(sdf.format(cell.getNumericCellValue())); c = sdf.format(cell.getNumericCellValue()); } else { c = cell.getStringCellValue(); } } else if (java.math.BigDecimal.class == fieldType) { c = cell.getStringCellValue(); } } if (entity != null) { list.add(entity); } } } return list; }
#vulnerable code public List<T> importExcel(String sheetName, InputStream input) throws Exception { List<T> list = new ArrayList<T>(); Workbook workbook = WorkbookFactory.create(input); Sheet sheet = null; if (StringUtils.isNotEmpty(sheetName)) { // 如果指定sheet名,则取指定sheet中的内容. sheet = workbook.getSheet(sheetName); } else { // 如果传入的sheet名不存在则默认指向第1个sheet. sheet = workbook.getSheetAt(0); } if (sheet == null) { throw new IOException("文件sheet不存在"); } int rows = sheet.getPhysicalNumberOfRows(); if (rows > 0) { // 有数据时才处理 得到类的所有field. Field[] allFields = clazz.getDeclaredFields(); // 定义一个map用于存放列的序号和field. Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>(); for (int col = 0; col < allFields.length; col++) { Field field = allFields[col]; // 将有注解的field存放到map中. if (field.isAnnotationPresent(Excel.class)) { // 设置类的私有字段属性可访问. field.setAccessible(true); fieldsMap.put(col, field); } } for (int i = 1; i < rows; i++) { // 从第2行开始取数据,默认第一行是表头. Row row = sheet.getRow(i); int cellNum = sheet.getRow(0).getPhysicalNumberOfCells(); T entity = null; for (int j = 0; j < cellNum; j++) { Cell cell = row.getCell(j); if (cell == null) { continue; } else { // 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了 row.getCell(j).setCellType(Cell.CELL_TYPE_STRING); cell = row.getCell(j); } String c = cell.getStringCellValue(); if (StringUtils.isEmpty(c)) { continue; } // 如果不存在实例则新建. entity = (entity == null ? clazz.newInstance() : entity); // 从map中得到对应列的field. Field field = fieldsMap.get(j + 1); // 取得类型,并根据对象类型设置值. Class<?> fieldType = field.getType(); if (String.class == fieldType) { field.set(entity, String.valueOf(c)); } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) { field.set(entity, Integer.parseInt(c)); } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) { field.set(entity, Long.valueOf(c)); } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) { field.set(entity, Float.valueOf(c)); } else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) { field.set(entity, Short.valueOf(c)); } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) { field.set(entity, Double.valueOf(c)); } else if (Character.TYPE == fieldType) { if ((c != null) && (c.length() > 0)) { field.set(entity, Character.valueOf(c.charAt(0))); } } else if (java.util.Date.class == fieldType) { if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cell.setCellValue(sdf.format(cell.getNumericCellValue())); c = sdf.format(cell.getNumericCellValue()); } else { c = cell.getStringCellValue(); } } else if (java.math.BigDecimal.class == fieldType) { c = cell.getStringCellValue(); } } if (entity != null) { list.add(entity); } } } return list; } #location 73 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void clearState() { setConnection(null); activeSenders.clear(); activeRequestResponseClients.clear(); failAllCreationRequests(); // make sure we make configured number of attempts to re-connect connectAttempts = new AtomicInteger(0); }
#vulnerable code protected void clearState() { setConnection(null); offeredCapabilities = Collections.emptyList(); activeSenders.clear(); activeRequestResponseClients.clear(); failAllCreationRequests(); // make sure we make configured number of attempts to re-connect connectAttempts = new AtomicInteger(0); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetOrCreateSenderFailsOnConnectionFailure(final TestContext ctx) { // GIVEN a client that tries to create a telemetry sender for "tenant" final Async connected = ctx.async(); final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete())); connected.await(); final Async disconnected = ctx.async(); client.getOrCreateSender( "telemetry/tenant", () -> Future.future(), ctx.asyncAssertFailure(cause -> { disconnected.complete(); })); // WHEN the underlying connection fails connectionFactory.getDisconnectHandler().handle(con); // THEN all creation requests are failed disconnected.await(); }
#vulnerable code @Test public void testGetOrCreateSenderFailsOnConnectionFailure(final TestContext ctx) { // GIVEN a client that tries to create a telemetry sender for "tenant" ProtonConnection con = mock(ProtonConnection.class); DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con); final Async connected = ctx.async(); final Async disconnected = ctx.async(); HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete())); connected.await(200); client.getOrCreateSender("telemetry/tenant", creationResultHandler -> { ctx.assertFalse(disconnected.isCompleted()); }, ctx.asyncAssertFailure(cause -> { disconnected.complete(); })); // WHEN the underlying connection fails connectionFactory.getDisconnectHandler().handle(con); // THEN all creation requests are failed disconnected.await(200); } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCreateTelemetryConsumerFailsOnConnectionFailure(final TestContext ctx) { // GIVEN a client that already tries to create a telemetry sender for "tenant" final Async connected = ctx.async(); final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete())); connected.await(); final Async disconnected = ctx.async(); client.createTelemetryConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> { disconnected.complete(); })); // WHEN the underlying connection fails connectionFactory.getDisconnectHandler().handle(con); // THEN all creation requests are failed disconnected.await(); }
#vulnerable code @Test public void testCreateTelemetryConsumerFailsOnConnectionFailure(final TestContext ctx) { // GIVEN a client that already tries to create a telemetry sender for "tenant" ProtonConnection con = mock(ProtonConnection.class); DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con); final Async connected = ctx.async(); final Async disconnected = ctx.async(); HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete())); connected.await(200); client.createTelemetryConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> { disconnected.complete(); })); // WHEN the underlying connection fails connectionFactory.getDisconnectHandler().handle(con); // THEN all creation requests are failed disconnected.await(200); } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEachOnce() throws Exception { //Each record exactly once - see commit b8f6d6dfaf11cce7d8cba54e6011e8684ade0e85, issue #68 Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 63))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 63, 121))); Assert.assertArrayEquals(new int[] { 4 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 121, 187))); Assert.assertArrayEquals(new int[] { 5, 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 187, 264))); Assert.assertArrayEquals(new int[] { 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 264, 352))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 352, 412))); Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 23))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 23, 41))); // Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); }
#vulnerable code @Test public void TestEachOnce() throws IOException { //Each record exactly once - see commit b8f6d6dfaf11cce7d8cba54e6011e8684ade0e85, issue #68 Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 63))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 63, 121))); Assert.assertArrayEquals(new int[] { 4 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 121, 187))); Assert.assertArrayEquals(new int[] { 5, 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 187, 264))); Assert.assertArrayEquals(new int[] { 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 264, 352))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 352, 412))); Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 23))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 23, 41))); // Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); }
#vulnerable code @Test public void TestArbitrarySplitLocations() throws IOException { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscCloseLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140))); }
#vulnerable code @Test public void TestEscCloseLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140))); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); }
#vulnerable code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscSlashLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140))); }
#vulnerable code @Test public void TestEscSlashLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140))); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Ignore // May not be guaranteed behavior public void TestComma() throws Exception { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); }
#vulnerable code @Ignore // May not be guaranteed behavior public void TestComma() throws IOException { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscCloseLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140))); }
#vulnerable code @Test public void TestEscCloseLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140))); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscQuoteLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140))); }
#vulnerable code @Test public void TestEscQuoteLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140))); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscape() throws Exception { // Issue #68 //int [] recordBreaks = new int[] { 0, 44, 88, 137, 181, 229, 270, 311, 354 }; //length 395 Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 43, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 140))); Assert.assertArrayEquals(new int[] {2, 3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 45, 140))); Assert.assertArrayEquals(new int[] {4,5,6}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 181, 289))); Assert.assertArrayEquals(new int[] { 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 336, 400))); // 7|{}" Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 14, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 22, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 23, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 24, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 25, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 68))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 69))); }
#vulnerable code @Test public void TestEscape() throws IOException { // Issue #68 //int [] recordBreaks = new int[] { 0, 44, 88, 137, 181, 229, 270, 311, 354 }; //length 395 Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 43, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 140))); Assert.assertArrayEquals(new int[] {2, 3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 45, 140))); Assert.assertArrayEquals(new int[] {4,5,6}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 181, 289))); Assert.assertArrayEquals(new int[] { 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 336, 400))); // 7|{}" Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 14, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 22, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 23, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 24, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 25, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 68))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 69))); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscPoints() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 74), true)); Assert.assertArrayEquals(new int[] {0, 75}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 76), true)); Assert.assertArrayEquals(new int[] {75, 146}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 70, 148), true)); }
#vulnerable code @Test public void TestEscPoints() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 74), true)); Assert.assertArrayEquals(new int[] {0, 75}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 76), true)); Assert.assertArrayEquals(new int[] {75, 146}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 70, 148), true)); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscSlashLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140))); }
#vulnerable code @Test public void TestEscSlashLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140))); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); }
#vulnerable code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscCloseLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140))); }
#vulnerable code @Test public void TestEscCloseLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140))); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Ignore // May not be guaranteed behavior public void TestComma() throws Exception { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); }
#vulnerable code @Ignore // May not be guaranteed behavior public void TestComma() throws IOException { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestWhitespace() throws Exception { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); }
#vulnerable code @Test public void TestWhitespace() throws IOException { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscCloseLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140))); }
#vulnerable code @Test public void TestEscCloseLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140))); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEachOnce() throws Exception { //Each record exactly once - see commit b8f6d6dfaf11cce7d8cba54e6011e8684ade0e85, issue #68 Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 63))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 63, 121))); Assert.assertArrayEquals(new int[] { 4 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 121, 187))); Assert.assertArrayEquals(new int[] { 5, 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 187, 264))); Assert.assertArrayEquals(new int[] { 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 264, 352))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 352, 412))); Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 23))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 23, 41))); // Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); }
#vulnerable code @Test public void TestEachOnce() throws IOException { //Each record exactly once - see commit b8f6d6dfaf11cce7d8cba54e6011e8684ade0e85, issue #68 Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 63))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 63, 121))); Assert.assertArrayEquals(new int[] { 4 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 121, 187))); Assert.assertArrayEquals(new int[] { 5, 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 187, 264))); Assert.assertArrayEquals(new int[] { 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 264, 352))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 352, 412))); Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 23))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 23, 41))); // Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); }
#vulnerable code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestWhitespace() throws Exception { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); }
#vulnerable code @Test public void TestWhitespace() throws IOException { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-return.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscape() throws Exception { // Issue #68 //int [] recordBreaks = new int[] { 0, 44, 88, 137, 181, 229, 270, 311, 354 }; //length 395 Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 43, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 140))); Assert.assertArrayEquals(new int[] {2, 3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 45, 140))); Assert.assertArrayEquals(new int[] {4,5,6}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 181, 289))); Assert.assertArrayEquals(new int[] { 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 336, 400))); // 7|{}" Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 14, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 22, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 23, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 24, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 25, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 68))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 69))); }
#vulnerable code @Test public void TestEscape() throws IOException { // Issue #68 //int [] recordBreaks = new int[] { 0, 44, 88, 137, 181, 229, 270, 311, 354 }; //length 395 Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 43, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 140))); Assert.assertArrayEquals(new int[] {2, 3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 45, 140))); Assert.assertArrayEquals(new int[] {4,5,6}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 181, 289))); Assert.assertArrayEquals(new int[] { 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 336, 400))); // 7|{}" Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 14, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 22, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 23, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 24, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 25, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 68))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 69))); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscAposLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 43, 140))); }
#vulnerable code @Test public void TestEscAposLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 43, 140))); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestGeomFirst() throws Exception { Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 32, 54))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 48, 54))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 49, 54))); Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 0, 52), true)); }
#vulnerable code @Test public void TestGeomFirst() throws IOException { Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 32, 54))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 48, 54))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 49, 54))); Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 0, 52), true)); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); }
#vulnerable code @Test public void TestArbitrarySplitLocations() throws IOException { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscPoints() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 74), true)); Assert.assertArrayEquals(new int[] {0, 75}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 76), true)); Assert.assertArrayEquals(new int[] {75, 146}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 70, 148), true)); }
#vulnerable code @Test public void TestEscPoints() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 74), true)); Assert.assertArrayEquals(new int[] {0, 75}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 76), true)); Assert.assertArrayEquals(new int[] {75, 146}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 70, 148), true)); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); }
#vulnerable code @Test public void TestArbitrarySplitLocations() throws IOException { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Ignore // May not be guaranteed behavior public void TestComma() throws Exception { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); }
#vulnerable code @Ignore // May not be guaranteed behavior public void TestComma() throws IOException { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscQuoteLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140))); }
#vulnerable code @Test public void TestEscQuoteLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140))); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Ignore // May not be guaranteed behavior public void TestComma() throws Exception { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); }
#vulnerable code @Ignore // May not be guaranteed behavior public void TestComma() throws IOException { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); }
#vulnerable code @Test public void TestArbitrarySplitLocations() throws IOException { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscOpenLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 44, 140))); Assert.assertArrayEquals(new int[] { 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 268, 280))); }
#vulnerable code @Test public void TestEscOpenLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 44, 140))); Assert.assertArrayEquals(new int[] { 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 268, 280))); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private UnenclosedJsonRecordReader getReaderFor(String resource, int start, int end) throws Exception { Path path = new Path(this.getClass().getResource(resource).getFile()); FileSplit split = new FileSplit(path, start, end - start, new String[0]); UnenclosedJsonRecordReader rr = new UnenclosedJsonRecordReader(); try { TaskAttemptContext tac = createTaskAttemptContext(new Configuration(), new TaskAttemptID()); rr.initialize(split, tac); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } return rr; }
#vulnerable code private UnenclosedJsonRecordReader getReaderFor(String resource, int start, int end) throws IOException { Path path = new Path(this.getClass().getResource(resource).getFile()); JobConf conf = new JobConf(); FileSplit split = new FileSplit(path, start, end - start, new String[0]); return new UnenclosedJsonRecordReader(split, conf); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscape() throws Exception { // Issue #68 //int [] recordBreaks = new int[] { 0, 44, 88, 137, 181, 229, 270, 311, 354 }; //length 395 Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 43, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 140))); Assert.assertArrayEquals(new int[] {2, 3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 45, 140))); Assert.assertArrayEquals(new int[] {4,5,6}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 181, 289))); Assert.assertArrayEquals(new int[] { 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 336, 400))); // 7|{}" Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 14, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 22, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 23, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 24, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 25, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 68))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 69))); }
#vulnerable code @Test public void TestEscape() throws IOException { // Issue #68 //int [] recordBreaks = new int[] { 0, 44, 88, 137, 181, 229, 270, 311, 354 }; //length 395 Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 43, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 140))); Assert.assertArrayEquals(new int[] {2, 3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 45, 140))); Assert.assertArrayEquals(new int[] {4,5,6}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 181, 289))); Assert.assertArrayEquals(new int[] { 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 336, 400))); // 7|{}" Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 14, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 22, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 23, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 24, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 25, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 68))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 69))); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscAposLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 43, 140))); }
#vulnerable code @Test public void TestEscAposLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 43, 140))); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscPoints() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 74), true)); Assert.assertArrayEquals(new int[] {0, 75}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 76), true)); Assert.assertArrayEquals(new int[] {75, 146}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 70, 148), true)); }
#vulnerable code @Test public void TestEscPoints() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 74), true)); Assert.assertArrayEquals(new int[] {0, 75}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 76), true)); Assert.assertArrayEquals(new int[] {75, 146}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 70, 148), true)); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscQuoteLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140))); }
#vulnerable code @Test public void TestEscQuoteLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140))); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Ignore // May not be guaranteed behavior public void TestComma() throws Exception { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); }
#vulnerable code @Ignore // May not be guaranteed behavior public void TestComma() throws IOException { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscape() throws Exception { // Issue #68 //int [] recordBreaks = new int[] { 0, 44, 88, 137, 181, 229, 270, 311, 354 }; //length 395 Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 43, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 140))); Assert.assertArrayEquals(new int[] {2, 3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 45, 140))); Assert.assertArrayEquals(new int[] {4,5,6}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 181, 289))); Assert.assertArrayEquals(new int[] { 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 336, 400))); // 7|{}" Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 14, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 22, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 23, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 24, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 25, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 68))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 69))); }
#vulnerable code @Test public void TestEscape() throws IOException { // Issue #68 //int [] recordBreaks = new int[] { 0, 44, 88, 137, 181, 229, 270, 311, 354 }; //length 395 Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 43, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 140))); Assert.assertArrayEquals(new int[] {2, 3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 45, 140))); Assert.assertArrayEquals(new int[] {4,5,6}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 181, 289))); Assert.assertArrayEquals(new int[] { 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 336, 400))); // 7|{}" Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 14, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 22, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 23, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 24, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 25, 45))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 68))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 69))); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestIntPoint() throws Exception { ArrayList<Object> stuff = new ArrayList<Object>(); Properties proptab = new Properties(); proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMNS, "num,shape"); proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMN_TYPES, "bigint,binary"); SerDe jserde = mkSerDe(proptab); StructObjectInspector rowOI = (StructObjectInspector)jserde.getObjectInspector(); // value.set("{\"properties\":{\"num\":7},\"geometry\":{\"type\":\"Point\",\"coordinates\":[15.0,5.0]}}"); addWritable(stuff, 7L); addWritable(stuff, new Point(15.0, 5.0)); Object row = runSerDe(stuff, jserde, rowOI); Object fieldData = getField("num", row, rowOI); Assert.assertEquals(7, ((LongWritable)fieldData).get()); //value.set("{\"properties\":{\"num\":4},\"geometry\":{\"type\":\"Point\",\"coordinates\":[7.0,2.0]}}"); stuff.clear(); addWritable(stuff, 4L); addWritable(stuff, new Point(7.0, 2.0)); row = runSerDe(stuff, jserde, rowOI); fieldData = getField("num", row, rowOI); Assert.assertEquals(4, ((LongWritable)fieldData).get()); fieldData = getField("shape", row, rowOI); ckPoint(new Point(7.0, 2.0), (BytesWritable)fieldData); }
#vulnerable code @Test public void TestIntPoint() throws Exception { Configuration config = new Configuration(); Text value = new Text(); SerDe jserde = new GeoJsonSerDe(); Properties proptab = new Properties(); proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMNS, "num,shape"); proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMN_TYPES, "bigint,binary"); jserde.initialize(config, proptab); StructObjectInspector rowOI = (StructObjectInspector)jserde.getObjectInspector(); value.set("{\"properties\":{\"num\":7},\"geometry\":{\"type\":\"Point\",\"coordinates\":[15.0,5.0]}}"); Object row = jserde.deserialize(value); StructField fref = rowOI.getStructFieldRef("num"); Object fieldData = rowOI.getStructFieldData(row, fref); Assert.assertEquals(7, ((LongWritable)fieldData).get()); value.set("{\"properties\":{\"num\":4},\"geometry\":{\"type\":\"Point\",\"coordinates\":[7.0,2.0]}}"); row = jserde.deserialize(value); fref = rowOI.getStructFieldRef("num"); fieldData = rowOI.getStructFieldData(row, fref); Assert.assertEquals(4, ((LongWritable)fieldData).get()); fref = rowOI.getStructFieldRef("shape"); fieldData = rowOI.getStructFieldData(row, fref); ckPoint(new Point(7.0, 2.0), (BytesWritable)fieldData); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEscSlashLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140))); }
#vulnerable code @Test public void TestEscSlashLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140))); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEachOnce() throws Exception { //Each record exactly once - see commit b8f6d6dfaf11cce7d8cba54e6011e8684ade0e85, issue #68 Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 63))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 63, 121))); Assert.assertArrayEquals(new int[] { 4 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 121, 187))); Assert.assertArrayEquals(new int[] { 5, 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 187, 264))); Assert.assertArrayEquals(new int[] { 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 264, 352))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 352, 412))); Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 23))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 23, 41))); // Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); }
#vulnerable code @Test public void TestEachOnce() throws IOException { //Each record exactly once - see commit b8f6d6dfaf11cce7d8cba54e6011e8684ade0e85, issue #68 Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 63))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 63, 121))); Assert.assertArrayEquals(new int[] { 4 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 121, 187))); Assert.assertArrayEquals(new int[] { 5, 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 187, 264))); Assert.assertArrayEquals(new int[] { 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 264, 352))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 352, 412))); Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 23))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 23, 41))); // Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Ignore // May not be guaranteed behavior public void TestComma() throws Exception { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); }
#vulnerable code @Ignore // May not be guaranteed behavior public void TestComma() throws IOException { //int [] recordBreaks = new int[] { 0, 57, 111, , }; int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true); Assert.assertEquals(4, rslt.length); int[] before = null, after = null; before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true); Assert.assertEquals(4, before.length + after.length); before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true); after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true); Assert.assertEquals(4, before.length + after.length); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private PackrOutput buildMacBundle(PackrOutput output) throws IOException { if (config.platform != PackrConfig.Platform.MacOS) { return output; } // replacement strings for Info.plist Map<String, String> values = new HashMap<>(); values.put("${executable}", config.executable); if (config.bundleIdentifier != null) { values.put("${bundleIdentifier}", config.bundleIdentifier); } else { values.put("${bundleIdentifier}", config.mainClass.substring(0, config.mainClass.lastIndexOf('.'))); } // create folder structure File root = output.executableFolder; PackrFileUtils.mkdirs(new File(root, "Contents")); try (FileWriter info = new FileWriter(new File(root, "Contents/Info.plist"))) { String plist = readResourceAsString("/Info.plist", values); info.write(plist); } File target = new File(root, "Contents/MacOS"); PackrFileUtils.mkdirs(target); File resources = new File(root, "Contents/Resources"); PackrFileUtils.mkdirs(resources); if (config.iconResource != null) { // copy icon to Contents/Resources/icons.icns if (config.iconResource.exists()) { PackrFileUtils.copyFile(config.iconResource, new File(resources, "icons.icns")); } } return new PackrOutput(target, resources); }
#vulnerable code private PackrOutput buildMacBundle(PackrOutput output) throws IOException { if (config.platform != PackrConfig.Platform.MacOS) { return output; } // replacement strings for Info.plist Map<String, String> values = new HashMap<>(); values.put("${executable}", config.executable); if (config.bundleIdentifier != null) { values.put("${bundleIdentifier}", config.bundleIdentifier); } else { values.put("${bundleIdentifier}", config.mainClass.substring(0, config.mainClass.lastIndexOf('.'))); } // create folder structure File root = output.executableFolder; PackrFileUtils.mkdirs(new File(root, "Contents")); new FileWriter(new File(root, "Contents/Info.plist")).write(readResourceAsString("/Info.plist", values)); File target = new File(root, "Contents/MacOS"); PackrFileUtils.mkdirs(target); File resources = new File(root, "Contents/Resources"); PackrFileUtils.mkdirs(resources); if (config.iconResource != null) { // copy icon to Contents/Resources/icons.icns if (config.iconResource.exists()) { PackrFileUtils.copyFile(config.iconResource, new File(resources, "icons.icns")); } } return new PackrOutput(target, resources); } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void copyExecutableAndClasspath(PackrOutput output) throws IOException { byte[] exe = null; String extension = ""; switch (config.platform) { case Windows32: exe = readResource("/packr-windows.exe"); extension = ".exe"; break; case Windows64: exe = readResource("/packr-windows-x64.exe"); extension = ".exe"; break; case Linux32: exe = readResource("/packr-linux"); break; case Linux64: exe = readResource("/packr-linux-x64"); break; case MacOS: exe = readResource("/packr-mac"); break; } System.out.println("Copying executable ..."); try (OutputStream writer = new FileOutputStream( new File(output.executableFolder, config.executable + extension))) { writer.write(exe); } PackrFileUtils.chmodX(new File(output.executableFolder, config.executable + extension)); System.out.println("Copying classpath(s) ..."); for (String file : config.classpath) { File cpSrc = new File(file); File cpDst = new File(output.resourcesFolder, new File(file).getName()); if (cpSrc.isFile()) { PackrFileUtils.copyFile(cpSrc, cpDst); } else if (cpSrc.isDirectory()) { PackrFileUtils.copyDirectory(cpSrc, cpDst); } else { System.err.println("Warning! Classpath not found: " + cpSrc); } } }
#vulnerable code private void copyExecutableAndClasspath(PackrOutput output) throws IOException { byte[] exe = null; String extension = ""; switch (config.platform) { case Windows32: exe = readResource("/packr-windows.exe"); extension = ".exe"; break; case Windows64: exe = readResource("/packr-windows-x64.exe"); extension = ".exe"; break; case Linux32: exe = readResource("/packr-linux"); break; case Linux64: exe = readResource("/packr-linux-x64"); break; case MacOS: exe = readResource("/packr-mac"); break; } System.out.println("Copying executable ..."); new FileOutputStream(new File(output.executableFolder, config.executable + extension)).write(exe); PackrFileUtils.chmodX(new File(output.executableFolder, config.executable + extension)); System.out.println("Copying classpath(s) ..."); for (String file : config.classpath) { File cpSrc = new File(file); File cpDst = new File(output.resourcesFolder, new File(file).getName()); if (cpSrc.isFile()) { PackrFileUtils.copyFile(cpSrc, cpDst); } else if (cpSrc.isDirectory()) { PackrFileUtils.copyDirectory(cpSrc, cpDst); } else { System.err.println("Warning! Classpath not found: " + cpSrc); } } } #location 26 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public SmsAlphabet getAlphabet() { switch (getGroup()) { case GENERAL_DATA_CODING: // General Data Coding Indication if (dcs_ == 0x00) { return SmsAlphabet.ASCII; } switch (dcs_ & 0x0C) { case 0x00: return SmsAlphabet.ASCII; case 0x04: return SmsAlphabet.LATIN1; case 0x08: return SmsAlphabet.UCS2; case 0x0C: return SmsAlphabet.RESERVED; default: return SmsAlphabet.UCS2; } case MESSAGE_WAITING_STORE_GSM: return SmsAlphabet.ASCII; case MESSAGE_WAITING_STORE_UCS2: return SmsAlphabet.UCS2; case DATA_CODING_MESSAGE: switch (dcs_ & 0x04) { case 0x00: return SmsAlphabet.ASCII; case 0x04: return SmsAlphabet.LATIN1; default: return SmsAlphabet.UCS2; } default: return SmsAlphabet.UCS2; } }
#vulnerable code public SmsAlphabet getAlphabet() { switch (getGroup()) { case GENERAL_DATA_CODING: // General Data Coding Indication if (dcs_ == 0x00) { return SmsAlphabet.ASCII; } switch (dcs_ & 0x0C) { case 0x00: return SmsAlphabet.ASCII; case 0x04: return SmsAlphabet.LATIN1; case 0x08: return SmsAlphabet.UCS2; case 0x0C: return SmsAlphabet.RESERVED; default: return null; } case MESSAGE_WAITING_STORE_GSM: return SmsAlphabet.ASCII; case MESSAGE_WAITING_STORE_UCS2: return SmsAlphabet.UCS2; case DATA_CODING_MESSAGE: switch (dcs_ & 0x04) { case 0x00: return SmsAlphabet.ASCII; case 0x04: return SmsAlphabet.LATIN1; default: return null; } default: return null; } } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testZkClientMonitor() throws Exception { final String TEST_TAG = "test_monitor"; final String TEST_KEY = "test_key"; final String TEST_DATA = "testData"; final String TEST_ROOT = "/my_cluster/IDEALSTATES"; final String TEST_NODE = "/test_zkclient_monitor"; final String TEST_PATH = TEST_ROOT + TEST_NODE; ZkClient.Builder builder = new ZkClient.Builder(); builder.setZkServer(ZK_ADDR).setMonitorKey(TEST_KEY).setMonitorType(TEST_TAG) .setMonitorRootPathOnly(false); ZkClient zkClient = builder.build(); final long TEST_DATA_SIZE = zkClient.serialize(TEST_DATA, TEST_PATH).length; if (_zkClient.exists(TEST_PATH)) { _zkClient.delete(TEST_PATH); } if (!_zkClient.exists(TEST_ROOT)) { _zkClient.createPersistent(TEST_ROOT, true); } MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName name = MBeanRegistrar .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY); ObjectName rootname = MBeanRegistrar .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY, ZkClientPathMonitor.MONITOR_PATH, "Root"); ObjectName idealStatename = MBeanRegistrar .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY, ZkClientPathMonitor.MONITOR_PATH, "IdealStates"); Assert.assertTrue(beanServer.isRegistered(rootname)); Assert.assertTrue(beanServer.isRegistered(idealStatename)); // Test exists Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadLatencyGauge.Max"), 0); zkClient.exists(TEST_ROOT); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 1); Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter") >= 0); Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadLatencyGauge.Max") >= 0); // Test create Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteLatencyGauge.Max"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteLatencyGauge.Max"), 0); zkClient.create(TEST_PATH, TEST_DATA, CreateMode.PERSISTENT); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 1); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), TEST_DATA_SIZE); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 1); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), TEST_DATA_SIZE); long origWriteTotalLatencyCounter = (long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter"); Assert.assertTrue(origWriteTotalLatencyCounter >= 0); Assert.assertTrue((long) beanServer.getAttribute(rootname, "WriteLatencyGauge.Max") >= 0); long origIdealStatesWriteTotalLatencyCounter = (long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter"); Assert.assertTrue(origIdealStatesWriteTotalLatencyCounter >= 0); Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "WriteLatencyGauge.Max") >= 0); // Test read Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 1); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), 0); long origReadTotalLatencyCounter = (long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter"); long origIdealStatesReadTotalLatencyCounter = (long) beanServer.getAttribute(idealStatename, "ReadTotalLatencyCounter"); Assert.assertEquals(origIdealStatesReadTotalLatencyCounter, 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadLatencyGauge.Max"), 0); zkClient.readData(TEST_PATH, new Stat()); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 2); Assert .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 1); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), TEST_DATA_SIZE); Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter") >= origReadTotalLatencyCounter); Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "ReadTotalLatencyCounter") >= origIdealStatesReadTotalLatencyCounter); Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "ReadLatencyGauge.Max") >= 0); zkClient.getChildren(TEST_PATH); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 3); Assert .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 2); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), TEST_DATA_SIZE); zkClient.getStat(TEST_PATH); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 4); Assert .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 3); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), TEST_DATA_SIZE); zkClient.readDataAndStat(TEST_PATH, new Stat(), true); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 5); ZkAsyncCallbacks.ExistsCallbackHandler callbackHandler = new ZkAsyncCallbacks.ExistsCallbackHandler(); zkClient.asyncExists(TEST_PATH, callbackHandler); callbackHandler.waitForSuccess(); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 6); // Test write zkClient.writeData(TEST_PATH, TEST_DATA); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 2); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), TEST_DATA_SIZE * 2); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 2); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), TEST_DATA_SIZE * 2); Assert.assertTrue((long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter") >= origWriteTotalLatencyCounter); Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter") >= origIdealStatesWriteTotalLatencyCounter); // Test data change count final Lock lock = new ReentrantLock(); final Condition callbackFinish = lock.newCondition(); zkClient.subscribeDataChanges(TEST_PATH, new IZkDataListener() { @Override public void handleDataChange(String dataPath, Object data) throws Exception { } @Override public void handleDataDeleted(String dataPath) throws Exception { lock.lock(); try { callbackFinish.signal(); } finally { lock.unlock(); } } }); lock.lock(); _zkClient.delete(TEST_PATH); Assert.assertTrue(callbackFinish.await(10, TimeUnit.SECONDS)); Assert.assertEquals((long) beanServer.getAttribute(name, "DataChangeEventCounter"), 1); }
#vulnerable code @Test public void testZkClientMonitor() throws Exception { final String TEST_TAG = "test_monitor"; final String TEST_KEY = "test_key"; final String TEST_DATA = "testData"; final String TEST_ROOT = "/my_cluster/IDEALSTATES"; final String TEST_NODE = "/test_zkclient_monitor"; final String TEST_PATH = TEST_ROOT + TEST_NODE; ZkClient zkClient = new ZkClient(ZK_ADDR, TEST_TAG, TEST_KEY); final long TEST_DATA_SIZE = zkClient.serialize(TEST_DATA, TEST_PATH).length; if (_zkClient.exists(TEST_PATH)) { _zkClient.delete(TEST_PATH); } if (!_zkClient.exists(TEST_ROOT)) { _zkClient.createPersistent(TEST_ROOT, true); } MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName name = MBeanRegistrar .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY); ObjectName rootname = MBeanRegistrar .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY, ZkClientPathMonitor.MONITOR_PATH, "Root"); ObjectName idealStatename = MBeanRegistrar .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY, ZkClientPathMonitor.MONITOR_PATH, "IdealStates"); Assert.assertTrue(beanServer.isRegistered(rootname)); Assert.assertTrue(beanServer.isRegistered(idealStatename)); // Test exists Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadMaxLatencyGauge"), 0); zkClient.exists(TEST_ROOT); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 1); Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter") >= 0); Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadMaxLatencyGauge") >= 0); // Test create Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteMaxLatencyGauge"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteMaxLatencyGauge"), 0); zkClient.create(TEST_PATH, TEST_DATA, CreateMode.PERSISTENT); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 1); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), TEST_DATA_SIZE); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 1); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), TEST_DATA_SIZE); long origWriteTotalLatencyCounter = (long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter"); Assert.assertTrue(origWriteTotalLatencyCounter >= 0); Assert.assertTrue((long) beanServer.getAttribute(rootname, "WriteMaxLatencyGauge") >= 0); long origIdealStatesWriteTotalLatencyCounter = (long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter"); Assert.assertTrue(origIdealStatesWriteTotalLatencyCounter >= 0); Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "WriteMaxLatencyGauge") >= 0); // Test read Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 1); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), 0); long origReadTotalLatencyCounter = (long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter"); long origIdealStatesReadTotalLatencyCounter = (long) beanServer.getAttribute(idealStatename, "ReadTotalLatencyCounter"); Assert.assertEquals(origIdealStatesReadTotalLatencyCounter, 0); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadMaxLatencyGauge"), 0); zkClient.readData(TEST_PATH, new Stat()); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 2); Assert .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 1); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), TEST_DATA_SIZE); Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter") >= origReadTotalLatencyCounter); Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "ReadTotalLatencyCounter") >= origIdealStatesReadTotalLatencyCounter); Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "ReadMaxLatencyGauge") >= 0); zkClient.getChildren(TEST_PATH); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 3); Assert .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 2); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), TEST_DATA_SIZE); zkClient.getStat(TEST_PATH); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 4); Assert .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 3); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), TEST_DATA_SIZE); zkClient.readDataAndStat(TEST_PATH, new Stat(), true); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 5); ZkAsyncCallbacks.ExistsCallbackHandler callbackHandler = new ZkAsyncCallbacks.ExistsCallbackHandler(); zkClient.asyncExists(TEST_PATH, callbackHandler); callbackHandler.waitForSuccess(); Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 6); // Test write zkClient.writeData(TEST_PATH, TEST_DATA); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 2); Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), TEST_DATA_SIZE * 2); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 2); Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), TEST_DATA_SIZE * 2); Assert.assertTrue((long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter") >= origWriteTotalLatencyCounter); Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter") >= origIdealStatesWriteTotalLatencyCounter); // Test data change count final Lock lock = new ReentrantLock(); final Condition callbackFinish = lock.newCondition(); zkClient.subscribeDataChanges(TEST_PATH, new IZkDataListener() { @Override public void handleDataChange(String dataPath, Object data) throws Exception { } @Override public void handleDataDeleted(String dataPath) throws Exception { lock.lock(); try { callbackFinish.signal(); } finally { lock.unlock(); } } }); lock.lock(); _zkClient.delete(TEST_PATH); Assert.assertTrue(callbackFinish.await(10, TimeUnit.SECONDS)); Assert.assertEquals((long) beanServer.getAttribute(name, "DataChangeEventCounter"), 1); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setRequestedState(String partitionName, String state) { setProperty(partitionName, CurrentStateProperty.REQUESTED_STATE, state); }
#vulnerable code public void setRequestedState(String partitionName, String state) { Map<String, Map<String, String>> mapFields = _record.getMapFields(); if (mapFields.get(partitionName) == null) { mapFields.put(partitionName, new TreeMap<String, String>()); } mapFields.get(partitionName).put(CurrentStateProperty.REQUESTED_STATE.name(), state); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void process(ClusterEvent event) throws Exception { ClusterManager manager = event.getAttribute("clustermanager"); if (manager == null) { throw new StageException("ClusterManager attribute value is null"); } ClusterDataAccessor dataAccessor = manager.getDataAccessor(); Map<String, ResourceGroup> resourceGroupMap = event .getAttribute(AttributeName.RESOURCE_GROUPS.toString()); if (resourceGroupMap == null) { throw new StageException("ResourceGroupMap attribute value is null"); } MessageSelectionStageOutput messageSelectionStageOutput = event .getAttribute(AttributeName.MESSAGES_SELECTED.toString()); for (String resourceGroupName : resourceGroupMap.keySet()) { ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); for (ResourceKey resource : resourceGroup.getResourceKeys()) { List<Message> messages = messageSelectionStageOutput.getMessages( resourceGroupName, resource); sendMessages(dataAccessor, messages); } } }
#vulnerable code @Override public void process(ClusterEvent event) throws Exception { ClusterManager manager = event.getAttribute("clustermanager"); if (manager == null) { throw new StageException("ClusterManager attribute value is null"); } ClusterDataAccessor dataAccessor = manager.getDataAccessor(); Map<String, ResourceGroup> resourceGroupMap = event .getAttribute(AttributeName.RESOURCE_GROUPS.toString()); MessageSelectionStageOutput messageSelectionStageOutput = event .getAttribute(AttributeName.MESSAGES_SELECTED.toString()); for (String resourceGroupName : resourceGroupMap.keySet()) { ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); for (ResourceKey resource : resourceGroup.getResourceKeys()) { List<Message> messages = messageSelectionStageOutput.getMessages( resourceGroupName, resource); sendMessages(dataAccessor, messages); } } } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testSimpleCS() { // setup resource group Map<String, ResourceGroup> resourceGroupMap = getResourceGroupMap(); setupLiveInstances(5); event.addAttribute(AttributeName.RESOURCE_GROUPS.toString(), resourceGroupMap); CurrentStateComputationStage stage = new CurrentStateComputationStage(); runStage(event, new ReadClusterDataStage()); runStage(event, stage); CurrentStateOutput output1 = event.getAttribute(AttributeName.CURRENT_STATE .toString()); Assert.assertEquals( output1.getCurrentStateMap("testResourceGroupName", new ResourceKey("testResourceGroupName_0")).size(), 0); // Add a state transition messages Message message = new Message(Message.MessageType.STATE_TRANSITION, "msg1"); message.setFromState("OFFLINE"); message.setToState("SLAVE"); message.setStateUnitGroup("testResourceGroupName"); message.setStateUnitKey("testResourceGroupName_1"); message.setTgtName("localhost_3"); message.setTgtSessionId("session_3"); accessor.setProperty(PropertyType.MESSAGES, message.getRecord(), "localhost_" + 3, message.getId()); runStage(event, new ReadClusterDataStage()); runStage(event, stage); CurrentStateOutput output2 = event.getAttribute(AttributeName.CURRENT_STATE .toString()); String pendingState = output2.getPendingState("testResourceGroupName", new ResourceKey("testResourceGroupName_1"), "localhost_3"); Assert.assertEquals(pendingState, "SLAVE"); ZNRecord record1 = new ZNRecord("testResourceGroupName"); // Add a current state that matches sessionId and one that does not match CurrentState stateWithLiveSession = new CurrentState(record1); stateWithLiveSession.setSessionId("session_3"); stateWithLiveSession.setStateModelDefRef("MasterSlave"); stateWithLiveSession.setState("testResourceGroupName_1", "OFFLINE"); ZNRecord record2 = new ZNRecord("testResourceGroupName"); CurrentState stateWithDeadSession = new CurrentState(record2); stateWithDeadSession.setSessionId("session_dead"); stateWithDeadSession.setStateModelDefRef("MasterSlave"); stateWithDeadSession.setState("testResourceGroupName_1", "MASTER"); accessor.setProperty(PropertyType.CURRENTSTATES, stateWithLiveSession.getRecord(), "localhost_3", "session_3", "testResourceGroupName"); accessor.setProperty(PropertyType.CURRENTSTATES, stateWithDeadSession.getRecord(), "localhost_3", "session_dead", "testResourceGroupName"); runStage(event, new ReadClusterDataStage()); runStage(event, stage); CurrentStateOutput output3 = event.getAttribute(AttributeName.CURRENT_STATE .toString()); String currentState = output3.getCurrentState("testResourceGroupName", new ResourceKey("testResourceGroupName_1"), "localhost_3"); Assert.assertEquals(currentState, "OFFLINE"); }
#vulnerable code public void testSimpleCS() { // setup resource group Map<String, ResourceGroup> resourceGroupMap = getResourceGroupMap(); setupLiveInstances(5); event.addAttribute(AttributeName.RESOURCE_GROUPS.toString(), resourceGroupMap); CurrentStateComputationStage stage = new CurrentStateComputationStage(); runStage(event, stage); CurrentStateOutput output1 = event.getAttribute(AttributeName.CURRENT_STATE .toString()); Assert.assertEquals( output1.getCurrentStateMap("testResourceGroupName", new ResourceKey("testResourceGroupName_0")).size(), 0); // Add a state transition messages Message message = new Message(Message.MessageType.STATE_TRANSITION, "msg1"); message.setFromState("OFFLINE"); message.setToState("SLAVE"); message.setStateUnitGroup("testResourceGroupName"); message.setStateUnitKey("testResourceGroupName_1"); message.setTgtName("localhost_3"); message.setTgtSessionId("session_3"); accessor.setProperty(PropertyType.MESSAGES, message.getRecord(), "localhost_" + 3, message.getId()); runStage(event, stage); CurrentStateOutput output2 = event.getAttribute(AttributeName.CURRENT_STATE .toString()); String pendingState = output2.getPendingState("testResourceGroupName", new ResourceKey("testResourceGroupName_1"), "localhost_3"); Assert.assertEquals(pendingState, "SLAVE"); ZNRecord record1 = new ZNRecord("testResourceGroupName"); // Add a current state that matches sessionId and one that does not match CurrentState stateWithLiveSession = new CurrentState(record1); stateWithLiveSession.setSessionId("session_3"); stateWithLiveSession.setStateModelDefRef("MasterSlave"); stateWithLiveSession.setState("testResourceGroupName_1", "OFFLINE"); ZNRecord record2 = new ZNRecord("testResourceGroupName"); CurrentState stateWithDeadSession = new CurrentState(record2); stateWithDeadSession.setSessionId("session_dead"); stateWithDeadSession.setStateModelDefRef("MasterSlave"); stateWithDeadSession.setState("testResourceGroupName_1", "MASTER"); accessor.setProperty(PropertyType.CURRENTSTATES, stateWithLiveSession.getRecord(), "localhost_3", "session_3", "testResourceGroupName"); accessor.setProperty(PropertyType.CURRENTSTATES, stateWithDeadSession.getRecord(), "localhost_3", "session_dead", "testResourceGroupName"); runStage(event, stage); CurrentStateOutput output3 = event.getAttribute(AttributeName.CURRENT_STATE .toString()); String currentState = output3.getCurrentState("testResourceGroupName", new ResourceKey("testResourceGroupName_1"), "localhost_3"); Assert.assertEquals(currentState, "OFFLINE"); } #location 56 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void startRebalancingTimer(long period, HelixManager manager) { if (period != _timerPeriod) { logger.info("Controller starting timer at period " + period); if (_rebalanceTimer != null) { _rebalanceTimer.cancel(); } _rebalanceTimer = new Timer(true); _timerPeriod = period; _rebalanceTimer .scheduleAtFixedRate(new RebalanceTask(manager), _timerPeriod, _timerPeriod); } else { logger.info("Controller already has timer at period " + _timerPeriod); } }
#vulnerable code void stopRebalancingTimer() { if (_rebalanceTimer != null) { _rebalanceTimer.cancel(); _rebalanceTimer = null; } _timerPeriod = Integer.MAX_VALUE; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void checkConnected() { checkConnected(-1); }
#vulnerable code void createClient() throws Exception { final RealmAwareZkClient newClient = createSingleRealmZkClient(); synchronized (this) { if (_zkclient != null) { _zkclient.close(); } _zkclient = newClient; _baseDataAccessor = createBaseDataAccessor(); _dataAccessor = new ZKHelixDataAccessor(_clusterName, _instanceType, _baseDataAccessor); _configAccessor = new ConfigAccessor(_zkclient); if (_instanceType == InstanceType.CONTROLLER || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { addBuiltInStateModelDefinitions(); } } // subscribe to state change _zkclient.subscribeStateChanges(this); int retryCount = 0; while (retryCount < 3) { try { final long sessionId = _zkclient.waitForEstablishedSession(_connectionInitTimeout, TimeUnit.MILLISECONDS); handleStateChanged(KeeperState.SyncConnected); /* * This listener is subscribed after SyncConnected and firing new session events, * which means this listener has not yet handled new session, so we have to handle new * session here just for this listener. */ handleNewSession(ZKUtil.toHexSessionId(sessionId)); break; } catch (HelixException e) { LOG.error("fail to createClient.", e); throw e; } catch (Exception e) { retryCount++; LOG.error("fail to createClient. retry " + retryCount, e); if (retryCount == 3) { throw e; } } } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object deserialize(byte[] bytes) throws ZkMarshallingError { if (bytes == null || bytes.length == 0) { LOG.error("ZNode is empty."); return null; } ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ZNRecord record = null; String id = null; Map<String, String> simpleFields = Maps.newHashMap(); Map<String, List<String>> listFields = Maps.newHashMap(); Map<String, Map<String, String>> mapFields = Maps.newHashMap(); byte[] rawPayload = null; try { JsonFactory f = new JsonFactory(); JsonParser jp = f.createJsonParser(bais); jp.nextToken(); // will return JsonToken.START_OBJECT (verify?) while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldname = jp.getCurrentName(); jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY if ("id".equals(fieldname)) { // contains an object id = jp.getText(); } else if ("simpleFields".equals(fieldname)) { while (jp.nextToken() != JsonToken.END_OBJECT) { String key = jp.getCurrentName(); jp.nextToken(); // move to value simpleFields.put(key, jp.getText()); } } else if ("mapFields".equals(fieldname)) { // user.setVerified(jp.getCurrentToken() == JsonToken.VALUE_TRUE); while (jp.nextToken() != JsonToken.END_OBJECT) { String key = jp.getCurrentName(); mapFields.put(key, new TreeMap<String, String>()); jp.nextToken(); // move to value while (jp.nextToken() != JsonToken.END_OBJECT) { String mapKey = jp.getCurrentName(); jp.nextToken(); // move to value mapFields.get(key).put(mapKey, jp.getText()); } } } else if ("listFields".equals(fieldname)) { // user.setUserImage(jp.getBinaryValue()); while (jp.nextToken() != JsonToken.END_OBJECT) { String key = jp.getCurrentName(); listFields.put(key, new ArrayList<String>()); jp.nextToken(); // move to value while (jp.nextToken() != JsonToken.END_ARRAY) { listFields.get(key).add(jp.getText()); } } } else if ("rawPayload".equals(fieldname)) { rawPayload = Base64.decode(jp.getText()); } else { throw new IllegalStateException("Unrecognized field '" + fieldname + "'!"); } } jp.close(); // ensure resources get cleaned up timely and properly if (id == null) { throw new IllegalStateException("ZNRecord id field is required!"); } record = new ZNRecord(id); record.setSimpleFields(simpleFields); record.setListFields(listFields); record.setMapFields(mapFields); record.setRawPayload(rawPayload); } catch (Exception e) { LOG.error("Exception during deserialization of bytes: " + new String(bytes), e); } return record; }
#vulnerable code @Override public Object deserialize(byte[] bytes) throws ZkMarshallingError { if (bytes == null || bytes.length == 0) { LOG.error("ZNode is empty."); return null; } ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ZNRecord record = null; try { JsonFactory f = new JsonFactory(); JsonParser jp = f.createJsonParser(bais); jp.nextToken(); // will return JsonToken.START_OBJECT (verify?) while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldname = jp.getCurrentName(); jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY if ("id".equals(fieldname)) { // contains an object record = new ZNRecord(jp.getText()); } else if ("simpleFields".equals(fieldname)) { while (jp.nextToken() != JsonToken.END_OBJECT) { String key = jp.getCurrentName(); jp.nextToken(); // move to value record.setSimpleField(key, jp.getText()); } } else if ("mapFields".equals(fieldname)) { // user.setVerified(jp.getCurrentToken() == JsonToken.VALUE_TRUE); while (jp.nextToken() != JsonToken.END_OBJECT) { String key = jp.getCurrentName(); record.setMapField(key, new TreeMap<String, String>()); jp.nextToken(); // move to value while (jp.nextToken() != JsonToken.END_OBJECT) { String mapKey = jp.getCurrentName(); jp.nextToken(); // move to value record.getMapField(key).put(mapKey, jp.getText()); } } } else if ("listFields".equals(fieldname)) { // user.setUserImage(jp.getBinaryValue()); while (jp.nextToken() != JsonToken.END_OBJECT) { String key = jp.getCurrentName(); record.setListField(key, new ArrayList<String>()); jp.nextToken(); // move to value while (jp.nextToken() != JsonToken.END_ARRAY) { record.getListField(key).add(jp.getText()); } } } else if ("rawPayload".equals(fieldname)) { record.setRawPayload(Base64.decode(jp.getText())); } else { throw new IllegalStateException("Unrecognized field '" + fieldname + "'!"); } } jp.close(); // ensure resources get cleaned up timely and properly } catch (Exception e) { LOG.error("Exception during deserialization of bytes: " + new String(bytes), e); } return record; } #location 55 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onControllerChange(NotificationContext changeContext) { logger.info("START: GenericClusterController.onControllerChange() for cluster " + _clusterName); _cache.requireFullRefresh(); _taskCache.requireFullRefresh(); if (changeContext != null && changeContext.getType() == Type.FINALIZE) { logger.info("GenericClusterController.onControllerChange() FINALIZE for cluster " + _clusterName); return; } HelixDataAccessor accessor = changeContext.getManager().getHelixDataAccessor(); // double check if this controller is the leader Builder keyBuilder = accessor.keyBuilder(); LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader()); if (leader == null) { logger .warn("No controller exists for cluster:" + changeContext.getManager().getClusterName()); return; } else { String leaderName = leader.getInstanceName(); String instanceName = changeContext.getManager().getInstanceName(); if (leaderName == null || !leaderName.equals(instanceName)) { logger.warn("leader name does NOT match, my name: " + instanceName + ", leader: " + leader); return; } } PauseSignal pauseSignal = accessor.getProperty(keyBuilder.pause()); if (pauseSignal != null) { if (!_paused) { _paused = true; logger.info("controller is now paused"); } } else { if (_paused) { _paused = false; logger.info("controller is now resumed"); ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.Resume); event.addAttribute(AttributeName.changeContext.name(), changeContext); event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); event.addAttribute(AttributeName.eventData.name(), pauseSignal); _eventQueue.put(event); _taskEventQueue.put(event.clone()); } } if (_clusterStatusMonitor == null) { _clusterStatusMonitor = new ClusterStatusMonitor(changeContext.getManager().getClusterName()); } _clusterStatusMonitor.setEnabled(!_paused); logger.info("END: GenericClusterController.onControllerChange() for cluster " + _clusterName); }
#vulnerable code @Override public void onControllerChange(NotificationContext changeContext) { logger.info("START: GenericClusterController.onControllerChange() for cluster " + _clusterName); _cache.requireFullRefresh(); if (changeContext != null && changeContext.getType() == Type.FINALIZE) { logger.info("GenericClusterController.onControllerChange() FINALIZE for cluster " + _clusterName); return; } HelixDataAccessor accessor = changeContext.getManager().getHelixDataAccessor(); // double check if this controller is the leader Builder keyBuilder = accessor.keyBuilder(); LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader()); if (leader == null) { logger .warn("No controller exists for cluster:" + changeContext.getManager().getClusterName()); return; } else { String leaderName = leader.getInstanceName(); String instanceName = changeContext.getManager().getInstanceName(); if (leaderName == null || !leaderName.equals(instanceName)) { logger.warn("leader name does NOT match, my name: " + instanceName + ", leader: " + leader); return; } } PauseSignal pauseSignal = accessor.getProperty(keyBuilder.pause()); if (pauseSignal != null) { if (!_paused) { _paused = true; logger.info("controller is now paused"); } } else { if (_paused) { _paused = false; logger.info("controller is now resumed"); ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.Resume); event.addAttribute(AttributeName.changeContext.name(), changeContext); event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); event.addAttribute(AttributeName.eventData.name(), pauseSignal); _eventQueue.put(event); } } if (_clusterStatusMonitor == null) { _clusterStatusMonitor = new ClusterStatusMonitor(changeContext.getManager().getClusterName()); } _clusterStatusMonitor.setEnabled(!_paused); logger.info("END: GenericClusterController.onControllerChange() for cluster " + _clusterName); } #location 46 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testInvocation() throws Exception { System.out.println("TestCMTaskHandler.testInvocation()"); Message message = new Message(MessageType.STATE_TRANSITION); message.setSrcName("cm-instance-0"); message.setTgtSessionId("1234"); message.setFromState("Offline"); message.setToState("Slave"); message.setStateUnitKey("Teststateunitkey"); message.setId("Some unique id"); message.setMsgId("Some unique message id"); message.setStateUnitGroup("TeststateunitGroup"); MockStateModel stateModel = new MockStateModel(); NotificationContext context; CMStateTransitionHandler stHandler = new CMStateTransitionHandler(stateModel); context = new NotificationContext(new MockManager()); CMTaskHandler handler; handler = new CMTaskHandler(message, context, stHandler, null); handler.call(); AssertJUnit.assertTrue(stateModel.stateModelInvoked); }
#vulnerable code @Test public void testInvocation() throws Exception { System.out.println("TestCMTaskHandler.testInvocation()"); Message message = new Message(MessageType.STATE_TRANSITION); message.setSrcName("cm-instance-0"); message.setTgtSessionId("1234"); message.setFromState("Offline"); message.setToState("Slave"); message.setStateUnitKey("Teststateunitkey"); message.setId("Some unique id"); message.setMsgId("Some unique message id"); message.setStateUnitGroup("TeststateunitGroup"); MockStateModel stateModel = new MockStateModel(); NotificationContext context; context = new NotificationContext(new MockManager()); CMTaskHandler handler; handler = new CMTaskHandler(message, context, null, null); handler.call(); AssertJUnit.assertTrue(stateModel.stateModelInvoked); } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void startRebalancingTimer(long period, HelixManager manager) { if (period != _timerPeriod) { logger.info("Controller starting timer at period " + period); if (_rebalanceTimer != null) { _rebalanceTimer.cancel(); } _rebalanceTimer = new Timer(true); _timerPeriod = period; _rebalanceTimer.scheduleAtFixedRate(new RebalanceTask(manager), _timerPeriod, _timerPeriod); } else { logger.info("Controller already has timer at period " + _timerPeriod); } }
#vulnerable code void checkRebalancingTimer(HelixManager manager, List<IdealState> idealStates) { if (manager.getConfigAccessor() == null) { logger.warn(manager.getInstanceName() + " config accessor doesn't exist. should be in file-based mode."); return; } for (IdealState idealState : idealStates) { int period = idealState.getRebalanceTimerPeriod(); if (period > 0) { startRebalancingTimer(period, manager); } } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void process(ClusterEvent event) throws Exception { ClusterDataCache cache = event.getAttribute("ClusterDataCache"); if (cache == null) { throw new StageException("Missing attributes in event:" + event + ". Requires DataCache"); } Map<String, IdealState> idealStates = cache.getIdealStates(); Map<String, ResourceGroup> resourceGroupMap = new LinkedHashMap<String, ResourceGroup>(); if (idealStates != null && idealStates.size() > 0) { for (IdealState idealState : idealStates.values()) { Set<String> resourceSet = idealState.getResourceKeySet(); String resourceGroupName = idealState.getResourceGroup(); for (String resourceKey : resourceSet) { addResource(resourceKey, resourceGroupName, resourceGroupMap); ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); resourceGroup.setStateModelDefRef(idealState.getStateModelDefRef()); } } } // It's important to get resourceKeys from CurrentState as well since the // idealState might be removed. Map<String, LiveInstance> availableInstances = cache.getLiveInstances(); if (availableInstances != null && availableInstances.size() > 0) { for (LiveInstance instance : availableInstances.values()) { String instanceName = instance.getInstanceName(); String clientSessionId = instance.getSessionId(); Map<String, CurrentState> currentStateMap = cache.getCurrentState(instanceName, clientSessionId); if (currentStateMap == null || currentStateMap.size() == 0) { continue; } for (CurrentState currentState : currentStateMap.values()) { String resourceGroupName = currentState.getResourceGroupName(); Map<String, String> resourceStateMap = currentState.getResourceKeyStateMap(); for (String resourceKey : resourceStateMap.keySet()) { addResource(resourceKey, resourceGroupName, resourceGroupMap); ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); resourceGroup.setStateModelDefRef(currentState.getStateModelDefRef()); } } } } event.addAttribute(AttributeName.RESOURCE_GROUPS.toString(), resourceGroupMap); }
#vulnerable code @Override public void process(ClusterEvent event) throws Exception { ClusterDataCache cache = event.getAttribute("ClusterDataCache"); Map<String, IdealState> idealStates = cache.getIdealStates(); Map<String, ResourceGroup> resourceGroupMap = new LinkedHashMap<String, ResourceGroup>(); if (idealStates != null && idealStates.size() > 0) { for (IdealState idealState : idealStates.values()) { Set<String> resourceSet = idealState.getResourceKeySet(); String resourceGroupName = idealState.getResourceGroup(); for (String resourceKey : resourceSet) { addResource(resourceKey, resourceGroupName, resourceGroupMap); ResourceGroup resourceGroup = resourceGroupMap .get(resourceGroupName); resourceGroup.setStateModelDefRef(idealState.getStateModelDefRef()); } } } // It's important to get resourceKeys from CurrentState as well since the // idealState might be removed. Map<String, LiveInstance> availableInstances = cache.getLiveInstances(); if (availableInstances != null && availableInstances.size() > 0) { for (LiveInstance instance : availableInstances.values()) { String instanceName = instance.getInstanceName(); String clientSessionId = instance.getSessionId(); Map<String, CurrentState> currentStateMap = cache.getCurrentState(instanceName, clientSessionId); if (currentStateMap == null || currentStateMap.size() == 0) { continue; } for (CurrentState currentState : currentStateMap.values()) { String resourceGroupName = currentState.getResourceGroupName(); Map<String, String> resourceStateMap = currentState.getResourceKeyStateMap(); for (String resourceKey : resourceStateMap.keySet()) { addResource(resourceKey, resourceGroupName, resourceGroupMap); ResourceGroup resourceGroup = resourceGroupMap .get(resourceGroupName); resourceGroup.setStateModelDefRef(currentState.getStateModelDefRef()); } } } } event.addAttribute(AttributeName.RESOURCE_GROUPS.toString(), resourceGroupMap); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void process(ClusterEvent event) throws Exception { ClusterDataCache cache = event.getAttribute("ClusterDataCache"); if (cache == null) { throw new StageException("Missing attributes in event:" + event + ". Requires DataCache"); } Map<String, LiveInstance> liveInstances = cache.getLiveInstances(); CurrentStateOutput currentStateOutput = new CurrentStateOutput(); Map<String, ResourceGroup> resourceGroupMap = event .getAttribute(AttributeName.RESOURCE_GROUPS.toString()); for (LiveInstance instance : liveInstances.values()) { String instanceName = instance.getInstanceName(); List<Message> instanceMessages; instanceMessages = cache.getMessages(instanceName); for (Message message : instanceMessages) { if (!MessageType.STATE_TRANSITION.toString().equalsIgnoreCase( message.getMsgType())) { continue; } if (!instance.getSessionId().equals(message.getTgtSessionId())) { continue; } String resourceGroupName = message.getResourceGroupName(); ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); if (resourceGroup == null) { continue; } ResourceKey resourceKey = resourceGroup.getResourceKey(message .getResourceKey()); if (resourceKey != null) { currentStateOutput.setPendingState(resourceGroupName, resourceKey, instanceName, message.getToState()); } else { // log } } } for (LiveInstance instance : liveInstances.values()) { String instanceName = instance.getInstanceName(); String clientSessionId = instance.getSessionId(); Map<String, CurrentState> currentStateMap = cache.getCurrentState(instanceName, clientSessionId); for (CurrentState currentState : currentStateMap.values()) { if (!instance.getSessionId().equals(currentState.getSessionId())) { continue; } String resourceGroupName = currentState.getResourceGroupName(); String stateModelDefName = currentState.getStateModelDefRef(); ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); if (resourceGroup == null) { continue; } if (stateModelDefName != null) { currentStateOutput.setResourceGroupStateModelDef(resourceGroupName, stateModelDefName); } Map<String, String> resourceKeyStateMap = currentState .getResourceKeyStateMap(); for (String resourceKeyStr : resourceKeyStateMap.keySet()) { ResourceKey resourceKey = resourceGroup .getResourceKey(resourceKeyStr); if (resourceKey != null) { currentStateOutput.setCurrentState(resourceGroupName, resourceKey, instanceName, currentState.getState(resourceKeyStr)); } else { // log } } } } event.addAttribute(AttributeName.CURRENT_STATE.toString(), currentStateOutput); }
#vulnerable code @Override public void process(ClusterEvent event) throws Exception { ClusterDataCache cache = event.getAttribute("ClusterDataCache"); Map<String, LiveInstance> liveInstances = cache.getLiveInstances(); CurrentStateOutput currentStateOutput = new CurrentStateOutput(); Map<String, ResourceGroup> resourceGroupMap = event .getAttribute(AttributeName.RESOURCE_GROUPS.toString()); for (LiveInstance instance : liveInstances.values()) { String instanceName = instance.getInstanceName(); List<Message> instanceMessages; instanceMessages = cache.getMessages(instanceName); for (Message message : instanceMessages) { if (!MessageType.STATE_TRANSITION.toString().equalsIgnoreCase( message.getMsgType())) { continue; } if (!instance.getSessionId().equals(message.getTgtSessionId())) { continue; } String resourceGroupName = message.getResourceGroupName(); ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); if (resourceGroup == null) { continue; } ResourceKey resourceKey = resourceGroup.getResourceKey(message .getResourceKey()); if (resourceKey != null) { currentStateOutput.setPendingState(resourceGroupName, resourceKey, instanceName, message.getToState()); } else { // log } } } for (LiveInstance instance : liveInstances.values()) { String instanceName = instance.getInstanceName(); String clientSessionId = instance.getSessionId(); Map<String, CurrentState> currentStateMap = cache.getCurrentState(instanceName, clientSessionId); for (CurrentState currentState : currentStateMap.values()) { if (!instance.getSessionId().equals(currentState.getSessionId())) { continue; } String resourceGroupName = currentState.getResourceGroupName(); String stateModelDefName = currentState.getStateModelDefRef(); ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); if (resourceGroup == null) { continue; } if (stateModelDefName != null) { currentStateOutput.setResourceGroupStateModelDef(resourceGroupName, stateModelDefName); } Map<String, String> resourceKeyStateMap = currentState .getResourceKeyStateMap(); for (String resourceKeyStr : resourceKeyStateMap.keySet()) { ResourceKey resourceKey = resourceGroup .getResourceKey(resourceKeyStr); if (resourceKey != null) { currentStateOutput.setCurrentState(resourceGroupName, resourceKey, instanceName, currentState.getState(resourceKeyStr)); } else { // log } } } } event.addAttribute(AttributeName.CURRENT_STATE.toString(), currentStateOutput); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void scheduleSingleJob(String jobResource, JobConfig jobConfig) { HelixAdmin admin = _manager.getClusterManagmentTool(); IdealState jobIS = admin.getResourceIdealState(_manager.getClusterName(), jobResource); if (jobIS != null) { LOG.info("Job " + jobResource + " idealstate already exists!"); return; } // Set up job resource based on partitions from target resource int numIndependentTasks = jobConfig.getTaskConfigMap().size(); int numPartitions = numIndependentTasks; if (numPartitions == 0) { IdealState targetIs = admin.getResourceIdealState(_manager.getClusterName(), jobConfig.getTargetResource()); if (targetIs == null) { LOG.warn("Target resource does not exist for job " + jobResource); // do not need to fail here, the job will be marked as failure immediately when job starts running. } else { numPartitions = targetIs.getPartitionSet().size(); } } admin.addResource(_manager.getClusterName(), jobResource, numPartitions, TaskConstants.STATE_MODEL_NAME); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); // Set the job configuration PropertyKey.Builder keyBuilder = accessor.keyBuilder(); HelixProperty resourceConfig = new HelixProperty(jobResource); resourceConfig.getRecord().getSimpleFields().putAll(jobConfig.getResourceConfigMap()); Map<String, TaskConfig> taskConfigMap = jobConfig.getTaskConfigMap(); if (taskConfigMap != null) { for (TaskConfig taskConfig : taskConfigMap.values()) { resourceConfig.getRecord().setMapField(taskConfig.getId(), taskConfig.getConfigMap()); } } accessor.setProperty(keyBuilder.resourceConfig(jobResource), resourceConfig); // Push out new ideal state based on number of target partitions CustomModeISBuilder builder = new CustomModeISBuilder(jobResource); builder.setRebalancerMode(IdealState.RebalanceMode.TASK); builder.setNumReplica(1); builder.setNumPartitions(numPartitions); builder.setStateModel(TaskConstants.STATE_MODEL_NAME); if (jobConfig.isDisableExternalView()) { builder.setDisableExternalView(true); } jobIS = builder.build(); for (int i = 0; i < numPartitions; i++) { jobIS.getRecord().setListField(jobResource + "_" + i, new ArrayList<String>()); jobIS.getRecord().setMapField(jobResource + "_" + i, new HashMap<String, String>()); } jobIS.setRebalancerClassName(JobRebalancer.class.getName()); admin.setResourceIdealState(_manager.getClusterName(), jobResource, jobIS); }
#vulnerable code private void scheduleSingleJob(String jobResource, JobConfig jobConfig) { HelixAdmin admin = _manager.getClusterManagmentTool(); IdealState jobIS = admin.getResourceIdealState(_manager.getClusterName(), jobResource); if (jobIS != null) { LOG.info("Job " + jobResource + " idealstate already exists!"); return; } // Set up job resource based on partitions from target resource int numIndependentTasks = jobConfig.getTaskConfigMap().size(); int numPartitions = (numIndependentTasks > 0) ? numIndependentTasks : admin.getResourceIdealState(_manager.getClusterName(), jobConfig.getTargetResource()) .getPartitionSet().size(); admin.addResource(_manager.getClusterName(), jobResource, numPartitions, TaskConstants.STATE_MODEL_NAME); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); // Set the job configuration PropertyKey.Builder keyBuilder = accessor.keyBuilder(); HelixProperty resourceConfig = new HelixProperty(jobResource); resourceConfig.getRecord().getSimpleFields().putAll(jobConfig.getResourceConfigMap()); Map<String, TaskConfig> taskConfigMap = jobConfig.getTaskConfigMap(); if (taskConfigMap != null) { for (TaskConfig taskConfig : taskConfigMap.values()) { resourceConfig.getRecord().setMapField(taskConfig.getId(), taskConfig.getConfigMap()); } } accessor.setProperty(keyBuilder.resourceConfig(jobResource), resourceConfig); // Push out new ideal state based on number of target partitions CustomModeISBuilder builder = new CustomModeISBuilder(jobResource); builder.setRebalancerMode(IdealState.RebalanceMode.TASK); builder.setNumReplica(1); builder.setNumPartitions(numPartitions); builder.setStateModel(TaskConstants.STATE_MODEL_NAME); if (jobConfig.isDisableExternalView()) { builder.setDisableExternalView(true); } jobIS = builder.build(); for (int i = 0; i < numPartitions; i++) { jobIS.getRecord().setListField(jobResource + "_" + i, new ArrayList<String>()); jobIS.getRecord().setMapField(jobResource + "_" + i, new HashMap<String, String>()); } jobIS.setRebalancerClassName(JobRebalancer.class.getName()); admin.setResourceIdealState(_manager.getClusterName(), jobResource, jobIS); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static int numberOfListeners(String zkAddr, String path) throws Exception { Map<String, Set<String>> listenerMap = getListenersByZkPath(zkAddr); if (listenerMap.containsKey(path)) { return listenerMap.get(path).size(); } return 0; }
#vulnerable code public static int numberOfListeners(String zkAddr, String path) throws Exception { int count = 0; String splits[] = zkAddr.split(":"); Socket sock = new Socket(splits[0], Integer.parseInt(splits[1])); PrintWriter out = new PrintWriter(sock.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream())); out.println("wchp"); String line = in.readLine(); while (line != null) { // System.out.println(line); if (line.equals(path)) { // System.out.println("match: " + line); String nextLine = in.readLine(); if (nextLine == null) { break; } // System.out.println(nextLine); while (nextLine.startsWith("\t0x")) { count++; nextLine = in.readLine(); if (nextLine == null) { break; } } } line = in.readLine(); } sock.close(); return count; } #location 38 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void disconnect() { if (!isConnected()) { logger.error("ClusterManager " + _instanceName + " already disconnected"); return; } disconnectInternal(); }
#vulnerable code @Override public void disconnect() { if (!isConnected()) { logger.warn("ClusterManager " + _instanceName + " already disconnected"); return; } logger.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName); /** * shutdown thread pool first to avoid reset() being invoked in the middle of state * transition */ _messagingService.getExecutor().shutDown(); resetHandlers(); _helixAccessor.shutdown(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(); } if (_participantHealthCheckInfoCollector != null) { _participantHealthCheckInfoCollector.stop(); } if (_timer != null) { _timer.cancel(); _timer = null; } if (_instanceType == InstanceType.CONTROLLER) { stopTimerTasks(); } // unsubscribe accessor from controllerChange _zkClient.unsubscribeAll(); _zkClient.close(); // HACK seems that zkClient is not sending DISCONNECT event _zkStateChangeListener.disconnect(); logger.info("Cluster manager: " + _instanceName + " disconnected"); } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void handleChildChange(String parentPath, List<String> currentChilds) { if (_zkClientForRoutingDataListener == null || _zkClientForRoutingDataListener.isClosed()) { return; } // Resubscribe _zkClientForRoutingDataListener.unsubscribeAll(); _zkClientForRoutingDataListener.subscribeRoutingDataChanges(this, this); resetZkResources(); }
#vulnerable code @Override public void handleChildChange(String parentPath, List<String> currentChilds) { if (_zkClientForListener == null || _zkClientForListener.isClosed()) { return; } // Resubscribe _zkClientForListener.unsubscribeAll(); _zkClientForListener.subscribeRoutingDataChanges(this, this); resetZkResources(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected static Set<String> getExpiredJobs(HelixDataAccessor dataAccessor, HelixPropertyStore propertyStore, WorkflowConfig workflowConfig, WorkflowContext workflowContext) { Set<String> expiredJobs = new HashSet<String>(); if (workflowContext != null) { Map<String, TaskState> jobStates = workflowContext.getJobStates(); for (String job : workflowConfig.getJobDag().getAllNodes()) { JobConfig jobConfig = TaskUtil.getJobConfig(dataAccessor, job); JobContext jobContext = TaskUtil.getJobContext(propertyStore, job); if (jobConfig == null) { LOG.error(String.format("Job %s exists in JobDAG but JobConfig is missing!", job)); continue; } long expiry = jobConfig.getExpiry(); if (expiry == workflowConfig.DEFAULT_EXPIRY || expiry < 0) { expiry = workflowConfig.getExpiry(); } if (jobContext != null && jobStates.get(job) == TaskState.COMPLETED) { if (System.currentTimeMillis() >= jobContext.getFinishTime() + expiry) { expiredJobs.add(job); } } } } return expiredJobs; }
#vulnerable code protected static Set<String> getExpiredJobs(HelixDataAccessor dataAccessor, HelixPropertyStore propertyStore, WorkflowConfig workflowConfig, WorkflowContext workflowContext) { Set<String> expiredJobs = new HashSet<String>(); if (workflowContext != null) { Map<String, TaskState> jobStates = workflowContext.getJobStates(); for (String job : workflowConfig.getJobDag().getAllNodes()) { JobConfig jobConfig = TaskUtil.getJobConfig(dataAccessor, job); JobContext jobContext = TaskUtil.getJobContext(propertyStore, job); long expiry = jobConfig.getExpiry(); if (expiry == workflowConfig.DEFAULT_EXPIRY || expiry < 0) { expiry = workflowConfig.getExpiry(); } if (jobContext != null && jobStates.get(job) == TaskState.COMPLETED) { if (System.currentTimeMillis() >= jobContext.getFinishTime() + expiry) { expiredJobs.add(job); } } } } return expiredJobs; } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override @PreFetch(enabled = false) public void onIdealStateChange(List<IdealState> idealStates, NotificationContext changeContext) { logger.info( "START: Generic GenericClusterController.onIdealStateChange() for cluster " + _clusterName); if (changeContext == null || changeContext.getType() != Type.CALLBACK) { _cache.requireFullRefresh(); _taskCache.requireFullRefresh(); } else { _cache.updateDataChange(ChangeType.IDEAL_STATE); _taskCache.updateDataChange(ChangeType.IDEAL_STATE); } ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.IdealStateChange); event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); event.addAttribute(AttributeName.changeContext.name(), changeContext); _eventQueue.put(event); _taskEventQueue.put(event.clone()); if (changeContext.getType() != Type.FINALIZE) { checkRebalancingTimer(changeContext.getManager(), idealStates, _cache.getClusterConfig()); } logger.info("END: GenericClusterController.onIdealStateChange() for cluster " + _clusterName); }
#vulnerable code @Override @PreFetch(enabled = false) public void onIdealStateChange(List<IdealState> idealStates, NotificationContext changeContext) { logger.info( "START: Generic GenericClusterController.onIdealStateChange() for cluster " + _clusterName); if (changeContext == null || changeContext.getType() != Type.CALLBACK) { _cache.requireFullRefresh(); } else { _cache.updateDataChange(ChangeType.IDEAL_STATE); } ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.IdealStateChange); event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); event.addAttribute(AttributeName.changeContext.name(), changeContext); _eventQueue.put(event); if (changeContext.getType() != Type.FINALIZE) { checkRebalancingTimer(changeContext.getManager(), idealStates, _cache.getClusterConfig()); } logger.info("END: GenericClusterController.onIdealStateChange() for cluster " + _clusterName); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onControllerChange(NotificationContext changeContext) { logger.info("START: GenericClusterController.onControllerChange() for cluster " + _clusterName); _cache.requireFullRefresh(); if (changeContext != null && changeContext.getType() == Type.FINALIZE) { logger.info("GenericClusterController.onControllerChange() FINALIZE for cluster " + _clusterName); return; } HelixDataAccessor accessor = changeContext.getManager().getHelixDataAccessor(); // double check if this controller is the leader Builder keyBuilder = accessor.keyBuilder(); LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader()); if (leader == null) { logger .warn("No controller exists for cluster:" + changeContext.getManager().getClusterName()); return; } else { String leaderName = leader.getInstanceName(); String instanceName = changeContext.getManager().getInstanceName(); if (leaderName == null || !leaderName.equals(instanceName)) { logger.warn("leader name does NOT match, my name: " + instanceName + ", leader: " + leader); return; } } PauseSignal pauseSignal = accessor.getProperty(keyBuilder.pause()); if (pauseSignal != null) { if (!_paused) { _paused = true; logger.info("controller is now paused"); } } else { if (_paused) { _paused = false; logger.info("controller is now resumed"); ClusterEvent event = new ClusterEvent("resume"); event.addAttribute("changeContext", changeContext); event.addAttribute("helixmanager", changeContext.getManager()); event.addAttribute("eventData", pauseSignal); _eventQueue.put(event); } } if (_clusterStatusMonitor == null) { _clusterStatusMonitor = new ClusterStatusMonitor(changeContext.getManager().getClusterName()); } _clusterStatusMonitor.setEnabled(!_paused); logger.info("END: GenericClusterController.onControllerChange() for cluster " + _clusterName); }
#vulnerable code @Override public void onControllerChange(NotificationContext changeContext) { logger.info("START: GenericClusterController.onControllerChange() for cluster " + _clusterName); _cache.requireFullRefresh(); if (changeContext != null && changeContext.getType() == Type.FINALIZE) { logger.info("GenericClusterController.onControllerChange() FINALIZE for cluster " + _clusterName); return; } HelixDataAccessor accessor = changeContext.getManager().getHelixDataAccessor(); // double check if this controller is the leader Builder keyBuilder = accessor.keyBuilder(); LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader()); if (leader == null) { logger .warn("No controller exists for cluster:" + changeContext.getManager().getClusterName()); return; } else { String leaderName = leader.getInstanceName(); String instanceName = changeContext.getManager().getInstanceName(); if (leaderName == null || !leaderName.equals(instanceName)) { logger.warn("leader name does NOT match, my name: " + instanceName + ", leader: " + leader); return; } } PauseSignal pauseSignal = accessor.getProperty(keyBuilder.pause()); if (pauseSignal != null) { if (!_paused) { _paused = true; logger.info("controller is now paused"); } } else { if (_paused) { _paused = false; logger.info("controller is now resumed"); ClusterEvent event = new ClusterEvent("resume"); event.addAttribute("changeContext", changeContext); event.addAttribute("helixmanager", changeContext.getManager()); event.addAttribute("eventData", pauseSignal); _eventQueue.put(event); } } if (_clusterStatusMonitor == null) { _clusterStatusMonitor = new ClusterStatusMonitor(changeContext.getManager().getClusterName()); } List<IdealState> idealStates = Collections.emptyList(); if (_cache.getIdealStates() != null) { idealStates = new ArrayList<>(_cache.getIdealStates().values()); } checkRebalancingTimer(changeContext.getManager(), idealStates, _cache.getClusterConfig()); _clusterStatusMonitor.setEnabled(!_paused); logger.info("END: GenericClusterController.onControllerChange() for cluster " + _clusterName); } #location 52 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public int send(final Criteria recipientCriteria, final Message message, AsyncCallback callbackOnReply) { Map<InstanceType, List<Message>> generateMessage = generateMessage( recipientCriteria, message); int totalMessageCount = 0; String correlationId = null; if (callbackOnReply != null) { correlationId = UUID.randomUUID().toString(); for (List<Message> messages : generateMessage.values()) { totalMessageCount += messages.size(); callbackOnReply.setMessagesSent(messages); } _asyncCallbackService.registerAsyncCallback(correlationId, callbackOnReply); } for (InstanceType receiverType : generateMessage.keySet()) { List<Message> list = generateMessage.get(receiverType); for (Message tempMessage : list) { if(correlationId != null) { tempMessage.setCorrelationId(correlationId); } if (receiverType == InstanceType.CONTROLLER) { _manager.getDataAccessor().setControllerProperty(ControllerPropertyType.MESSAGES, tempMessage.getRecord(), CreateMode.PERSISTENT); } if (receiverType == InstanceType.PARTICIPANT) { _manager.getDataAccessor().setInstanceProperty(message.getTgtName(), InstancePropertyType.MESSAGES, tempMessage.getId(), tempMessage.getRecord()); } } } return totalMessageCount; }
#vulnerable code @Override public int send(final Criteria recipientCriteria, final Message message, AsyncCallback callbackOnReply) { Map<InstanceType, List<Message>> generateMessage = generateMessage( recipientCriteria, message); int totalMessageCount = 0; String correlationId = null; if (callbackOnReply != null) { correlationId = UUID.randomUUID().toString(); for (List<Message> messages : generateMessage.values()) { totalMessageCount += messages.size(); callbackOnReply.setMessagesSent(messages); } _asyncCallbackService.registerAsyncCallback(correlationId, callbackOnReply); } for (InstanceType receiverType : generateMessage.keySet()) { List<Message> list = generateMessage.get(receiverType); for (Message tempMessage : list) { tempMessage.setId(UUID.randomUUID().toString()); if(correlationId != null) { tempMessage.setCorrelationId(correlationId); } if (receiverType == InstanceType.CONTROLLER) { _dataAccessor.setControllerProperty(ControllerPropertyType.MESSAGES, tempMessage.getRecord(), CreateMode.PERSISTENT); } if (receiverType == InstanceType.PARTICIPANT) { _dataAccessor.setInstanceProperty(message.getTgtName(), InstancePropertyType.MESSAGES, tempMessage.getId(), tempMessage.getRecord()); } } } return totalMessageCount; } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void shutdown() throws InterruptedException { stopRebalancingTimer(); terminateEventThread(_eventThread); terminateEventThread(_taskEventThread); _asyncTasksThreadPool.shutdown(); }
#vulnerable code public void shutdown() throws InterruptedException { stopRebalancingTimer(); while (_eventThread.isAlive()) { _eventThread.interrupt(); _eventThread.join(EVENT_THREAD_JOIN_TIMEOUT); } _asyncTasksThreadPool.shutdown(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void scheduleSingleJob(String jobResource, JobConfig jobConfig) { HelixAdmin admin = _manager.getClusterManagmentTool(); IdealState jobIS = admin.getResourceIdealState(_manager.getClusterName(), jobResource); if (jobIS != null) { LOG.info("Job " + jobResource + " idealstate already exists!"); return; } // Set up job resource based on partitions from target resource int numIndependentTasks = jobConfig.getTaskConfigMap().size(); int numPartitions = numIndependentTasks; if (numPartitions == 0) { IdealState targetIs = admin.getResourceIdealState(_manager.getClusterName(), jobConfig.getTargetResource()); if (targetIs == null) { LOG.warn("Target resource does not exist for job " + jobResource); // do not need to fail here, the job will be marked as failure immediately when job starts running. } else { numPartitions = targetIs.getPartitionSet().size(); } } admin.addResource(_manager.getClusterName(), jobResource, numPartitions, TaskConstants.STATE_MODEL_NAME); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); // Set the job configuration PropertyKey.Builder keyBuilder = accessor.keyBuilder(); HelixProperty resourceConfig = new HelixProperty(jobResource); resourceConfig.getRecord().getSimpleFields().putAll(jobConfig.getResourceConfigMap()); Map<String, TaskConfig> taskConfigMap = jobConfig.getTaskConfigMap(); if (taskConfigMap != null) { for (TaskConfig taskConfig : taskConfigMap.values()) { resourceConfig.getRecord().setMapField(taskConfig.getId(), taskConfig.getConfigMap()); } } accessor.setProperty(keyBuilder.resourceConfig(jobResource), resourceConfig); // Push out new ideal state based on number of target partitions CustomModeISBuilder builder = new CustomModeISBuilder(jobResource); builder.setRebalancerMode(IdealState.RebalanceMode.TASK); builder.setNumReplica(1); builder.setNumPartitions(numPartitions); builder.setStateModel(TaskConstants.STATE_MODEL_NAME); if (jobConfig.isDisableExternalView()) { builder.disableExternalView(); } jobIS = builder.build(); for (int i = 0; i < numPartitions; i++) { jobIS.getRecord().setListField(jobResource + "_" + i, new ArrayList<String>()); jobIS.getRecord().setMapField(jobResource + "_" + i, new HashMap<String, String>()); } jobIS.setRebalancerClassName(JobRebalancer.class.getName()); admin.setResourceIdealState(_manager.getClusterName(), jobResource, jobIS); }
#vulnerable code private void scheduleSingleJob(String jobResource, JobConfig jobConfig) { HelixAdmin admin = _manager.getClusterManagmentTool(); IdealState jobIS = admin.getResourceIdealState(_manager.getClusterName(), jobResource); if (jobIS != null) { LOG.info("Job " + jobResource + " idealstate already exists!"); return; } // Set up job resource based on partitions from target resource int numIndependentTasks = jobConfig.getTaskConfigMap().size(); int numPartitions = (numIndependentTasks > 0) ? numIndependentTasks : admin.getResourceIdealState(_manager.getClusterName(), jobConfig.getTargetResource()) .getPartitionSet().size(); admin.addResource(_manager.getClusterName(), jobResource, numPartitions, TaskConstants.STATE_MODEL_NAME); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); // Set the job configuration PropertyKey.Builder keyBuilder = accessor.keyBuilder(); HelixProperty resourceConfig = new HelixProperty(jobResource); resourceConfig.getRecord().getSimpleFields().putAll(jobConfig.getResourceConfigMap()); Map<String, TaskConfig> taskConfigMap = jobConfig.getTaskConfigMap(); if (taskConfigMap != null) { for (TaskConfig taskConfig : taskConfigMap.values()) { resourceConfig.getRecord().setMapField(taskConfig.getId(), taskConfig.getConfigMap()); } } accessor.setProperty(keyBuilder.resourceConfig(jobResource), resourceConfig); // Push out new ideal state based on number of target partitions CustomModeISBuilder builder = new CustomModeISBuilder(jobResource); builder.setRebalancerMode(IdealState.RebalanceMode.TASK); builder.setNumReplica(1); builder.setNumPartitions(numPartitions); builder.setStateModel(TaskConstants.STATE_MODEL_NAME); if (jobConfig.isDisableExternalView()) { builder.disableExternalView(); } jobIS = builder.build(); for (int i = 0; i < numPartitions; i++) { jobIS.getRecord().setListField(jobResource + "_" + i, new ArrayList<String>()); jobIS.getRecord().setMapField(jobResource + "_" + i, new HashMap<String, String>()); } jobIS.setRebalancerClassName(JobRebalancer.class.getName()); admin.setResourceIdealState(_manager.getClusterName(), jobResource, jobIS); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void disconnect() { if (_zkclient == null || _zkclient.isClosed()) { LOG.info("instanceName: " + _instanceName + " already disconnected"); return; } LOG.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName); try { /** * stop all timer tasks */ stopTimerTasks(); /** * shutdown thread pool first to avoid reset() being invoked in the middle of state * transition */ _messagingService.getExecutor().shutdown(); if (!cleanupCallbackHandlers()) { LOG.warn( "The callback handler cleanup has been cleanly done. " + "Some callback handlers might not be reset properly. " + "Continue to finish the other Helix Mananger disconnect tasks."); } } finally { GenericHelixController controller = _controller; if (controller != null) { try { controller.shutdown(); } catch (InterruptedException e) { LOG.info("Interrupted shutting down GenericHelixController", e); } } for (HelixCallbackMonitor callbackMonitor : _callbackMonitors.values()) { callbackMonitor.unregister(); } _helixPropertyStore = null; synchronized (this) { if (_controller != null) { _controller = null; _leaderElectionHandler = null; } if (_participantManager != null) { _participantManager = null; } if (_zkclient != null) { _zkclient.close(); } } _sessionStartTime = null; LOG.info("Cluster manager: " + _instanceName + " disconnected"); } }
#vulnerable code @Override public void disconnect() { if (_zkclient == null || _zkclient.isClosed()) { LOG.info("instanceName: " + _instanceName + " already disconnected"); return; } LOG.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName); try { /** * stop all timer tasks */ stopTimerTasks(); /** * shutdown thread pool first to avoid reset() being invoked in the middle of state * transition */ _messagingService.getExecutor().shutdown(); // TODO reset user defined handlers only // TODO Fix the issue that when connection disconnected, reset handlers will be blocked. -- JJ // This is because reset logic contains ZK operations. resetHandlers(true); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(true); } } finally { GenericHelixController controller = _controller; if (controller != null) { try { controller.shutdown(); } catch (InterruptedException e) { LOG.info("Interrupted shutting down GenericHelixController", e); } } ParticipantManager participantManager = _participantManager; if (participantManager != null) { participantManager.disconnect(); } for (HelixCallbackMonitor callbackMonitor : _callbackMonitors.values()) { callbackMonitor.unregister(); } _helixPropertyStore = null; synchronized (this) { if (_controller != null) { _controller = null; _leaderElectionHandler = null; } if (_participantManager != null) { _participantManager = null; } if (_zkclient != null) { _zkclient.close(); } } _sessionStartTime = null; LOG.info("Cluster manager: " + _instanceName + " disconnected"); } } #location 28 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void process(ClusterEvent event) throws Exception { ClusterManager manager = event.getAttribute("clustermanager"); ClusterDataCache cache = event.getAttribute("ClusterDataCache"); Map<String, ResourceGroup> resourceGroupMap = event .getAttribute(AttributeName.RESOURCE_GROUPS.toString()); CurrentStateOutput currentStateOutput = event .getAttribute(AttributeName.CURRENT_STATE.toString()); BestPossibleStateOutput bestPossibleStateOutput = event .getAttribute(AttributeName.BEST_POSSIBLE_STATE.toString()); if (manager == null || cache == null || resourceGroupMap == null || currentStateOutput == null || bestPossibleStateOutput == null) { throw new StageException("Missing attributes in event:" + event + ". Requires ClusterManager|DataCache|RESOURCE_GROUPS|CURRENT_STATE|BEST_POSSIBLE_STATE"); } Map<String, LiveInstance> liveInstances = cache.getLiveInstances(); Map<String, String> sessionIdMap = new HashMap<String, String>(); for (LiveInstance liveInstance : liveInstances.values()) { sessionIdMap.put(liveInstance.getInstanceName(), liveInstance.getSessionId()); } MessageGenerationOutput output = new MessageGenerationOutput(); for (String resourceGroupName : resourceGroupMap.keySet()) { ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); StateModelDefinition stateModelDef = cache.getStateModelDef(resourceGroup.getStateModelDefRef()); for (ResourceKey resource : resourceGroup.getResourceKeys()) { Map<String, String> instanceStateMap = bestPossibleStateOutput .getInstanceStateMap(resourceGroupName, resource); for (String instanceName : instanceStateMap.keySet()) { String desiredState = instanceStateMap.get(instanceName); String currentState = currentStateOutput.getCurrentState( resourceGroupName, resource, instanceName); if (currentState == null) { currentState = stateModelDef.getInitialState(); } String pendingState = currentStateOutput.getPendingState( resourceGroupName, resource, instanceName); String nextState; nextState = stateModelDef.getNextStateForTransition(currentState, desiredState); if (!desiredState.equalsIgnoreCase(currentState)) { if (nextState != null) { if (pendingState != null && nextState.equalsIgnoreCase(pendingState)) { if (logger.isDebugEnabled()) { logger.debug("Message already exists at" + instanceName + " to transition"+ resource.getResourceKeyName() +" from " + currentState + " to " + nextState ); } } else { Message message = createMessage(manager,resourceGroupName, resource.getResourceKeyName(), instanceName, currentState, nextState, sessionIdMap.get(instanceName), stateModelDef.getId()); output.addMessage(resourceGroupName, resource, message); } } else { logger .warn("Unable to find a next state from stateModelDefinition" + stateModelDef.getClass() + " from:" + currentState + " to:" + desiredState); } } } } } event.addAttribute(AttributeName.MESSAGES_ALL.toString(), output); }
#vulnerable code @Override public void process(ClusterEvent event) throws Exception { ClusterManager manager = event.getAttribute("clustermanager"); if (manager == null) { throw new StageException("ClusterManager attribute value is null"); } ClusterDataCache cache = event.getAttribute("ClusterDataCache"); Map<String, ResourceGroup> resourceGroupMap = event .getAttribute(AttributeName.RESOURCE_GROUPS.toString()); CurrentStateOutput currentStateOutput = event .getAttribute(AttributeName.CURRENT_STATE.toString()); BestPossibleStateOutput bestPossibleStateOutput = event .getAttribute(AttributeName.BEST_POSSIBLE_STATE.toString()); Map<String, LiveInstance> liveInstances = cache.getLiveInstances(); Map<String, String> sessionIdMap = new HashMap<String, String>(); for (LiveInstance liveInstance : liveInstances.values()) { sessionIdMap.put(liveInstance.getInstanceName(), liveInstance.getSessionId()); } MessageGenerationOutput output = new MessageGenerationOutput(); for (String resourceGroupName : resourceGroupMap.keySet()) { ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); StateModelDefinition stateModelDef = cache.getStateModelDef(resourceGroup.getStateModelDefRef()); for (ResourceKey resource : resourceGroup.getResourceKeys()) { Map<String, String> instanceStateMap = bestPossibleStateOutput .getInstanceStateMap(resourceGroupName, resource); for (String instanceName : instanceStateMap.keySet()) { String desiredState = instanceStateMap.get(instanceName); String currentState = currentStateOutput.getCurrentState( resourceGroupName, resource, instanceName); if (currentState == null) { currentState = stateModelDef.getInitialState(); } String pendingState = currentStateOutput.getPendingState( resourceGroupName, resource, instanceName); String nextState; nextState = stateModelDef.getNextStateForTransition(currentState, desiredState); if (!desiredState.equalsIgnoreCase(currentState)) { if (nextState != null) { if (pendingState != null && nextState.equalsIgnoreCase(pendingState)) { if (logger.isDebugEnabled()) { logger.debug("Message already exists at" + instanceName + " to transition"+ resource.getResourceKeyName() +" from " + currentState + " to " + nextState ); } } else { Message message = createMessage(manager,resourceGroupName, resource.getResourceKeyName(), instanceName, currentState, nextState, sessionIdMap.get(instanceName), stateModelDef.getId()); output.addMessage(resourceGroupName, resource, message); } } else { logger .warn("Unable to find a next state from stateModelDefinition" + stateModelDef.getClass() + " from:" + currentState + " to:" + desiredState); } } } } } event.addAttribute(AttributeName.MESSAGES_ALL.toString(), output); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCreateFailZkCacheBaseDataAccessor() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); // init zkCacheDataAccessor String curStatePath = PropertyPathBuilder.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901"); ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); ZkCacheBaseDataAccessor<ZNRecord> accessor = new ZkCacheBaseDataAccessor<ZNRecord>(baseAccessor, null, Arrays.asList(curStatePath), null); // create 10 current states for (int i = 0; i < 10; i++) { String path = PropertyPathBuilder.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901", "session_1", "TestDB" + i); boolean success = accessor.create(path, new ZNRecord("TestDB" + i), AccessOption.PERSISTENT); Assert.assertTrue(success, "Should succeed in create: " + path); } // create same 10 current states again, should fail for (int i = 0; i < 10; i++) { String path = PropertyPathBuilder.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901", "session_1", "TestDB" + i); boolean success = accessor.create(path, new ZNRecord("TestDB" + i), AccessOption.PERSISTENT); Assert.assertFalse(success, "Should fail in create due to NodeExists: " + path); } System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); }
#vulnerable code @Test public void testCreateFailZkCacheBaseDataAccessor() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); // init zkCacheDataAccessor String curStatePath = PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901"); ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); ZkCacheBaseDataAccessor<ZNRecord> accessor = new ZkCacheBaseDataAccessor<ZNRecord>(baseAccessor, null, Arrays.asList(curStatePath), null); // create 10 current states for (int i = 0; i < 10; i++) { String path = PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901", "session_1", "TestDB" + i); boolean success = accessor.create(path, new ZNRecord("TestDB" + i), AccessOption.PERSISTENT); Assert.assertTrue(success, "Should succeed in create: " + path); } // create same 10 current states again, should fail for (int i = 0; i < 10; i++) { String path = PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901", "session_1", "TestDB" + i); boolean success = accessor.create(path, new ZNRecord("TestDB" + i), AccessOption.PERSISTENT); Assert.assertFalse(success, "Should fail in create due to NodeExists: " + path); } System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void handleNewSession() throws Exception { LOG.info( "Handle new session, instance: " + _instanceName + ", type: " + _instanceType); waitUntilConnected(); /** * stop all timer tasks, reset all handlers, make sure cleanup completed for previous session * disconnect if fail to cleanup */ stopTimerTasks(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(false); } resetHandlers(false); /** * clean up write-through cache */ _baseDataAccessor.reset(); /** * from here on, we are dealing with new session */ if (!ZKUtil.isClusterSetup(_clusterName, _zkclient)) { throw new HelixException("Cluster structure is not set up for cluster: " + _clusterName); } _sessionStartTime = System.currentTimeMillis(); switch (_instanceType) { case PARTICIPANT: handleNewSessionAsParticipant(); break; case CONTROLLER: handleNewSessionAsController(); break; case CONTROLLER_PARTICIPANT: handleNewSessionAsParticipant(); handleNewSessionAsController(); break; case ADMINISTRATOR: case SPECTATOR: default: break; } startTimerTasks(); /** * init handlers * ok to init message handler and data-accessor twice * the second init will be skipped (see CallbackHandler) */ initHandlers(_handlers); if (_stateListener != null) { try { _stateListener.onConnected(this); } catch (Exception e) { LOG.warn("stateListener.onConnected callback fails", e); } } }
#vulnerable code @Override public void handleNewSession() throws Exception { LOG.info( "Handle new session, instance: " + _instanceName + ", type: " + _instanceType); waitUntilConnected(); /** * stop all timer tasks, reset all handlers, make sure cleanup completed for previous session * disconnect if fail to cleanup */ stopTimerTasks(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(); } resetHandlers(); /** * clean up write-through cache */ _baseDataAccessor.reset(); /** * from here on, we are dealing with new session */ if (!ZKUtil.isClusterSetup(_clusterName, _zkclient)) { throw new HelixException("Cluster structure is not set up for cluster: " + _clusterName); } _sessionStartTime = System.currentTimeMillis(); switch (_instanceType) { case PARTICIPANT: handleNewSessionAsParticipant(); break; case CONTROLLER: handleNewSessionAsController(); break; case CONTROLLER_PARTICIPANT: handleNewSessionAsParticipant(); handleNewSessionAsController(); break; case ADMINISTRATOR: case SPECTATOR: default: break; } startTimerTasks(); /** * init handlers * ok to init message handler and data-accessor twice * the second init will be skipped (see CallbackHandler) */ initHandlers(_handlers); if (_stateListener != null) { try { _stateListener.onConnected(this); } catch (Exception e) { LOG.warn("stateListener.onConnected callback fails", e); } } } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private BestPossibleStateOutput compute(ClusterEvent event, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { ClusterDataCache cache = event.getAttribute(AttributeName.ClusterDataCache.name()); BestPossibleStateOutput output = new BestPossibleStateOutput(); HelixManager helixManager = event.getAttribute(AttributeName.helixmanager.name()); ClusterStatusMonitor clusterStatusMonitor = event.getAttribute(AttributeName.clusterStatusMonitor.name()); // Check whether the offline/disabled instance count in the cluster reaches the set limit, // if yes, pause the rebalancer. boolean isValid = validateOfflineInstancesLimit(cache, (HelixManager) event.getAttribute(AttributeName.helixmanager.name())); final List<String> failureResources = new ArrayList<>(); Iterator<Resource> itr = resourceMap.values().iterator(); while (itr.hasNext()) { Resource resource = itr.next(); boolean result = false; try { result = computeResourceBestPossibleState(event, cache, currentStateOutput, resource, output); } catch (HelixException ex) { LogUtil.logError(logger, _eventId, "Exception when calculating best possible states for " + resource.getResourceName(), ex); } if (!result) { failureResources.add(resource.getResourceName()); LogUtil.logWarn(logger, _eventId, "Failed to calculate best possible states for " + resource.getResourceName()); } } // Check and report if resource rebalance has failure updateRebalanceStatus(!isValid || !failureResources.isEmpty(), failureResources, helixManager, cache, clusterStatusMonitor, "Failed to calculate best possible states for " + failureResources.size() + " resources."); return output; }
#vulnerable code private BestPossibleStateOutput compute(ClusterEvent event, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { ClusterDataCache cache = event.getAttribute(AttributeName.ClusterDataCache.name()); BestPossibleStateOutput output = new BestPossibleStateOutput(); HelixManager helixManager = event.getAttribute(AttributeName.helixmanager.name()); final List<String> failureResources = new ArrayList<>(); Iterator<Resource> itr = resourceMap.values().iterator(); while (itr.hasNext()) { Resource resource = itr.next(); boolean result = false; try { result = computeResourceBestPossibleState(event, cache, currentStateOutput, resource, output); } catch (HelixException ex) { LogUtil.logError(logger, _eventId, "Exception when calculating best possible states for " + resource.getResourceName(), ex); } if (!result) { failureResources.add(resource.getResourceName()); LogUtil.logWarn(logger, _eventId, "Failed to calculate best possible states for " + resource.getResourceName()); } } // Check and report if resource rebalance has failure ClusterStatusMonitor clusterStatusMonitor = event.getAttribute(AttributeName.clusterStatusMonitor.name()); updateRebalanceStatus(!failureResources.isEmpty(), helixManager, cache, clusterStatusMonitor, "Failed to calculate best possible states for " + failureResources.size() + " resources."); return output; } #location 31 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void startRebalancingTimer(long period, HelixManager manager) { if (period != _timerPeriod) { logger.info("Controller starting timer at period " + period); if (_rebalanceTimer != null) { _rebalanceTimer.cancel(); } _rebalanceTimer = new Timer(true); _timerPeriod = period; _rebalanceTimer .scheduleAtFixedRate(new RebalanceTask(manager), _timerPeriod, _timerPeriod); } else { logger.info("Controller already has timer at period " + _timerPeriod); } }
#vulnerable code void stopRebalancingTimer() { if (_rebalanceTimer != null) { _rebalanceTimer.cancel(); _rebalanceTimer = null; } _timerPeriod = Integer.MAX_VALUE; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onControllerChange(NotificationContext changeContext) { logger.info("START: GenericClusterController.onControllerChange() for cluster " + _clusterName); _cache.requireFullRefresh(); _taskCache.requireFullRefresh(); if (changeContext != null && changeContext.getType() == Type.FINALIZE) { logger.info("GenericClusterController.onControllerChange() FINALIZE for cluster " + _clusterName); return; } HelixDataAccessor accessor = changeContext.getManager().getHelixDataAccessor(); // double check if this controller is the leader Builder keyBuilder = accessor.keyBuilder(); LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader()); if (leader == null) { logger .warn("No controller exists for cluster:" + changeContext.getManager().getClusterName()); return; } else { String leaderName = leader.getInstanceName(); String instanceName = changeContext.getManager().getInstanceName(); if (leaderName == null || !leaderName.equals(instanceName)) { logger.warn("leader name does NOT match, my name: " + instanceName + ", leader: " + leader); return; } } PauseSignal pauseSignal = accessor.getProperty(keyBuilder.pause()); if (pauseSignal != null) { if (!_paused) { _paused = true; logger.info("controller is now paused"); } } else { if (_paused) { _paused = false; logger.info("controller is now resumed"); ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.Resume); event.addAttribute(AttributeName.changeContext.name(), changeContext); event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); event.addAttribute(AttributeName.eventData.name(), pauseSignal); _eventQueue.put(event); _taskEventQueue.put(event.clone()); } } if (_clusterStatusMonitor == null) { _clusterStatusMonitor = new ClusterStatusMonitor(changeContext.getManager().getClusterName()); } _clusterStatusMonitor.setEnabled(!_paused); logger.info("END: GenericClusterController.onControllerChange() for cluster " + _clusterName); }
#vulnerable code @Override public void onControllerChange(NotificationContext changeContext) { logger.info("START: GenericClusterController.onControllerChange() for cluster " + _clusterName); _cache.requireFullRefresh(); if (changeContext != null && changeContext.getType() == Type.FINALIZE) { logger.info("GenericClusterController.onControllerChange() FINALIZE for cluster " + _clusterName); return; } HelixDataAccessor accessor = changeContext.getManager().getHelixDataAccessor(); // double check if this controller is the leader Builder keyBuilder = accessor.keyBuilder(); LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader()); if (leader == null) { logger .warn("No controller exists for cluster:" + changeContext.getManager().getClusterName()); return; } else { String leaderName = leader.getInstanceName(); String instanceName = changeContext.getManager().getInstanceName(); if (leaderName == null || !leaderName.equals(instanceName)) { logger.warn("leader name does NOT match, my name: " + instanceName + ", leader: " + leader); return; } } PauseSignal pauseSignal = accessor.getProperty(keyBuilder.pause()); if (pauseSignal != null) { if (!_paused) { _paused = true; logger.info("controller is now paused"); } } else { if (_paused) { _paused = false; logger.info("controller is now resumed"); ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.Resume); event.addAttribute(AttributeName.changeContext.name(), changeContext); event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); event.addAttribute(AttributeName.eventData.name(), pauseSignal); _eventQueue.put(event); } } if (_clusterStatusMonitor == null) { _clusterStatusMonitor = new ClusterStatusMonitor(changeContext.getManager().getClusterName()); } _clusterStatusMonitor.setEnabled(!_paused); logger.info("END: GenericClusterController.onControllerChange() for cluster " + _clusterName); } #location 48 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean getExistsLiveInstanceOrCurrentStateChange() { return _existsLiveInstanceOrCurrentStateChange; }
#vulnerable code public boolean getExistsLiveInstanceOrCurrentStateChange() { boolean change = _existsLiveInstanceOrCurrentStateChange; _existsLiveInstanceOrCurrentStateChange = false; return change; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean tryUpdateController(ClusterManager manager) { try { String instanceName = manager.getInstanceName(); String clusterName = manager.getClusterName(); final ZNRecord leaderRecord = new ZNRecord(ControllerPropertyType.LEADER.toString()); leaderRecord.setSimpleField(ControllerPropertyType.LEADER.toString(), manager.getInstanceName()); ClusterDataAccessor dataAccessor = manager.getDataAccessor(); ZNRecord currentleader = dataAccessor .getControllerProperty(ControllerPropertyType.LEADER); if (currentleader == null) { dataAccessor.createControllerProperty(ControllerPropertyType.LEADER, leaderRecord, CreateMode.EPHEMERAL); // set controller history ZNRecord histRecord = dataAccessor .getControllerProperty(ControllerPropertyType.HISTORY, "HISTORY"); List<String> list = histRecord.getListField(clusterName); list.add(instanceName); dataAccessor.setControllerProperty(ControllerPropertyType.HISTORY, histRecord, CreateMode.PERSISTENT); return true; } else { logger.info("Leader exists for cluster:" + clusterName + " currentLeader:" + currentleader.getId()); } } catch (ZkNodeExistsException e) { logger.warn("Ignorable exception. Found that leader already exists, " + e.getMessage()); } return false; }
#vulnerable code private boolean tryUpdateController(ClusterManager manager) { try { String instanceName = manager.getInstanceName(); String clusterName = manager.getClusterName(); final ZNRecord leaderRecord = new ZNRecord(ControllerPropertyType.LEADER.toString()); leaderRecord.setSimpleField(ControllerPropertyType.LEADER.toString(), manager.getInstanceName()); ClusterDataAccessor dataAccessor = manager.getDataAccessor(); ZNRecord currentleader = dataAccessor .getControllerProperty(ControllerPropertyType.LEADER); if (currentleader == null) { dataAccessor.createControllerProperty(ControllerPropertyType.LEADER, leaderRecord, CreateMode.EPHEMERAL); // set controller history ZNRecord histRecord = dataAccessor .getControllerProperty(ControllerPropertyType.HISTORY); List<String> list = histRecord.getListField(clusterName); list.add(instanceName); dataAccessor.setControllerProperty(ControllerPropertyType.HISTORY, histRecord, CreateMode.PERSISTENT); return true; } else { logger.info("Leader exists for cluster:" + clusterName + " currentLeader:" + currentleader.getId()); } } catch (ZkNodeExistsException e) { logger.warn("Ignorable exception. Found that leader already exists, " + e.getMessage()); } return false; } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private BestPossibleStateOutput compute(ClusterEvent event, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { ClusterDataCache cache = event.getAttribute(AttributeName.ClusterDataCache.name()); BestPossibleStateOutput output = new BestPossibleStateOutput(); HelixManager helixManager = event.getAttribute(AttributeName.helixmanager.name()); final List<String> failureResources = new ArrayList<>(); Iterator<Resource> itr = resourceMap.values().iterator(); while (itr.hasNext()) { Resource resource = itr.next(); if (!computeResourceBestPossibleState(event, cache, currentStateOutput, resource, output)) { failureResources.add(resource.getResourceName()); LogUtil.logWarn(logger, _eventId, "Failed to calculate best possible states for " + resource.getResourceName()); } } // Check and report if resource rebalance has failure ClusterStatusMonitor clusterStatusMonitor = event.getAttribute(AttributeName.clusterStatusMonitor.name()); updateRebalanceStatus(!failureResources.isEmpty(), helixManager, cache, clusterStatusMonitor, "Failed to calculate best possible states for " + failureResources.size() + " resources."); return output; }
#vulnerable code private BestPossibleStateOutput compute(ClusterEvent event, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { ClusterDataCache cache = event.getAttribute(AttributeName.ClusterDataCache.name()); BestPossibleStateOutput output = new BestPossibleStateOutput(); PriorityQueue<ResourcePriority> resourcePriorityQueue = new PriorityQueue<>(); TaskDriver taskDriver = null; HelixManager helixManager = event.getAttribute(AttributeName.helixmanager.name()); if (helixManager != null) { taskDriver = new TaskDriver(helixManager); } for (Resource resource : resourceMap.values()) { resourcePriorityQueue.add(new ResourcePriority(resource, cache.getIdealState(resource.getResourceName()), taskDriver)); } final List<String> failureResources = new ArrayList<>(); Iterator<ResourcePriority> itr = resourcePriorityQueue.iterator(); while (itr.hasNext()) { Resource resource = itr.next().getResource(); if (!computeResourceBestPossibleState(event, cache, currentStateOutput, resource, output)) { failureResources.add(resource.getResourceName()); LogUtil.logWarn(logger, _eventId, "Failed to calculate best possible states for " + resource.getResourceName()); } } // Check and report if resource rebalance has failure if (!cache.isTaskCache()) { ClusterStatusMonitor clusterStatusMonitor = event.getAttribute(AttributeName.clusterStatusMonitor.name()); updateRebalanceStatus(!failureResources.isEmpty(), helixManager, cache, clusterStatusMonitor, "Failed to calculate best possible states for " + failureResources.size() + " resources."); } return output; } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void handleNewSession() { boolean isConnected = _zkClient.waitUntilConnected(CONNECTIONTIMEOUT, TimeUnit.MILLISECONDS); while (!isConnected) { logger.error("Could NOT connect to zk server in " + CONNECTIONTIMEOUT + "ms. zkServer: " + _zkConnectString + ", expiredSessionId: " + _sessionId + ", clusterName: " + _clusterName); isConnected = _zkClient.waitUntilConnected(CONNECTIONTIMEOUT, TimeUnit.MILLISECONDS); } ZkConnection zkConnection = ((ZkConnection) _zkClient.getConnection()); synchronized (this) { _sessionId = Long.toHexString(zkConnection.getZookeeper().getSessionId()); } _baseDataAccessor.reset(); // reset all handlers so they have a chance to unsubscribe zk changes from zkclient // abandon all callback-handlers added in expired session resetHandlers(); logger.info("Handling new session, session id:" + _sessionId + ", instance:" + _instanceName + ", instanceTye: " + _instanceType + ", cluster: " + _clusterName); logger.info(zkConnection.getZookeeper()); if (!ZKUtil.isClusterSetup(_clusterName, _zkClient)) { throw new HelixException("Initial cluster structure is not set up for cluster:" + _clusterName); } // Read cluster config and see if instance can auto join the cluster boolean autoJoin = false; try { ConfigScope scope = new ConfigScopeBuilder().forCluster(getClusterName()) .build(); autoJoin = Boolean.parseBoolean(getConfigAccessor().get(scope, ALLOW_PARTICIPANT_AUTO_JOIN)); logger.info("Auto joining " + _clusterName +" is true"); } catch(Exception e) { } if (!ZKUtil.isInstanceSetup(_zkClient, _clusterName, _instanceName, _instanceType)) { if(!autoJoin) { throw new HelixException("Initial cluster structure is not set up for instance:" + _instanceName + " instanceType:" + _instanceType); } else { logger.info("Auto joining instance " + _instanceName); InstanceConfig instanceConfig = new InstanceConfig(_instanceName); String hostName = _instanceName; String port = ""; int lastPos = _instanceName.lastIndexOf("_"); if (lastPos > 0) { hostName = _instanceName.substring(0, lastPos); port = _instanceName.substring(lastPos + 1); } instanceConfig.setHostName(hostName); instanceConfig.setPort(port); instanceConfig.setInstanceEnabled(true); getClusterManagmentTool().addInstance(_clusterName, instanceConfig); } } if (_instanceType == InstanceType.PARTICIPANT || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { handleNewSessionAsParticipant(); } if (_instanceType == InstanceType.CONTROLLER || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { addControllerMessageListener(_messagingService.getExecutor()); MessageHandlerFactory defaultControllerMsgHandlerFactory = new DefaultControllerMessageHandlerFactory(); _messagingService.getExecutor() .registerMessageHandlerFactory(defaultControllerMsgHandlerFactory.getMessageType(), defaultControllerMsgHandlerFactory); MessageHandlerFactory defaultSchedulerMsgHandlerFactory = new DefaultSchedulerMessageHandlerFactory(this); _messagingService.getExecutor() .registerMessageHandlerFactory(defaultSchedulerMsgHandlerFactory.getMessageType(), defaultSchedulerMsgHandlerFactory); MessageHandlerFactory defaultParticipantErrorMessageHandlerFactory = new DefaultParticipantErrorMessageHandlerFactory(this); _messagingService.getExecutor() .registerMessageHandlerFactory(defaultParticipantErrorMessageHandlerFactory.getMessageType(), defaultParticipantErrorMessageHandlerFactory); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(); _leaderElectionHandler.init(); } else { _leaderElectionHandler = createCallBackHandler(new Builder(_clusterName).controller(), new DistClusterControllerElection(_zkConnectString), new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, ChangeType.CONTROLLER); } } if (_instanceType == InstanceType.PARTICIPANT || _instanceType == InstanceType.CONTROLLER_PARTICIPANT || (_instanceType == InstanceType.CONTROLLER && isLeader())) { initHandlers(); } }
#vulnerable code protected void handleNewSession() { boolean isConnected = _zkClient.waitUntilConnected(CONNECTIONTIMEOUT, TimeUnit.MILLISECONDS); while (!isConnected) { logger.error("Could NOT connect to zk server in " + CONNECTIONTIMEOUT + "ms. zkServer: " + _zkConnectString + ", expiredSessionId: " + _sessionId + ", clusterName: " + _clusterName); isConnected = _zkClient.waitUntilConnected(CONNECTIONTIMEOUT, TimeUnit.MILLISECONDS); } ZkConnection zkConnection = ((ZkConnection) _zkClient.getConnection()); synchronized (this) { _sessionId = Long.toHexString(zkConnection.getZookeeper().getSessionId()); } _baseDataAccessor.reset(); // reset all handlers so they have a chance to unsubscribe zk changes from zkclient // abandon all callback-handlers added in expired session resetHandlers(); _handlers = new ArrayList<CallbackHandler>(); logger.info("Handling new session, session id:" + _sessionId + ", instance:" + _instanceName + ", instanceTye: " + _instanceType + ", cluster: " + _clusterName); logger.info(zkConnection.getZookeeper()); if (!ZKUtil.isClusterSetup(_clusterName, _zkClient)) { throw new HelixException("Initial cluster structure is not set up for cluster:" + _clusterName); } // Read cluster config and see if instance can auto join the cluster boolean autoJoin = false; try { ConfigScope scope = new ConfigScopeBuilder().forCluster(getClusterName()) .build(); autoJoin = Boolean.parseBoolean(getConfigAccessor().get(scope, ALLOW_PARTICIPANT_AUTO_JOIN)); logger.info("Auto joining " + _clusterName +" is true"); } catch(Exception e) { } if (!ZKUtil.isInstanceSetup(_zkClient, _clusterName, _instanceName, _instanceType)) { if(!autoJoin) { throw new HelixException("Initial cluster structure is not set up for instance:" + _instanceName + " instanceType:" + _instanceType); } else { logger.info("Auto joining instance " + _instanceName); InstanceConfig instanceConfig = new InstanceConfig(_instanceName); String hostName = _instanceName; String port = ""; int lastPos = _instanceName.lastIndexOf("_"); if (lastPos > 0) { hostName = _instanceName.substring(0, lastPos); port = _instanceName.substring(lastPos + 1); } instanceConfig.setHostName(hostName); instanceConfig.setPort(port); instanceConfig.setInstanceEnabled(true); getClusterManagmentTool().addInstance(_clusterName, instanceConfig); } } if (_instanceType == InstanceType.PARTICIPANT || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { handleNewSessionAsParticipant(); } if (_instanceType == InstanceType.CONTROLLER || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { addControllerMessageListener(_messagingService.getExecutor()); MessageHandlerFactory defaultControllerMsgHandlerFactory = new DefaultControllerMessageHandlerFactory(); _messagingService.getExecutor() .registerMessageHandlerFactory(defaultControllerMsgHandlerFactory.getMessageType(), defaultControllerMsgHandlerFactory); MessageHandlerFactory defaultSchedulerMsgHandlerFactory = new DefaultSchedulerMessageHandlerFactory(this); _messagingService.getExecutor() .registerMessageHandlerFactory(defaultSchedulerMsgHandlerFactory.getMessageType(), defaultSchedulerMsgHandlerFactory); MessageHandlerFactory defaultParticipantErrorMessageHandlerFactory = new DefaultParticipantErrorMessageHandlerFactory(this); _messagingService.getExecutor() .registerMessageHandlerFactory(defaultParticipantErrorMessageHandlerFactory.getMessageType(), defaultParticipantErrorMessageHandlerFactory); // create a new leader-election handler for a new session if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(); } _leaderElectionHandler = createCallBackHandler(new Builder(_clusterName).controller(), new DistClusterControllerElection(_zkConnectString), new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, ChangeType.CONTROLLER); } if (_instanceType == InstanceType.PARTICIPANT || _instanceType == InstanceType.CONTROLLER_PARTICIPANT || (_instanceType == InstanceType.CONTROLLER && isLeader())) { initHandlers(); } } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(MAX_PARALLEL_TASKS); Future<CMTaskResult> future; // pool.shutdown(); // pool.awaitTermination(5, TimeUnit.SECONDS); future = pool.submit(new Callable<CMTaskResult>() { @Override public CMTaskResult call() throws Exception { System.out .println("CMTaskExecutor.main(...).new Callable() {...}.call()"); return null; } }); future = pool.submit(new CMTask(null, null, null, null)); Thread.currentThread().join(); System.out.println(future.isDone()); }
#vulnerable code public static void main(String[] args) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(MAX_PARALLEL_TASKS); Future<CMTaskResult> future; // pool.shutdown(); // pool.awaitTermination(5, TimeUnit.SECONDS); future = pool.submit(new Callable<CMTaskResult>() { @Override public CMTaskResult call() throws Exception { System.out .println("CMTaskExecutor.main(...).new Callable() {...}.call()"); return null; } }); future = pool.submit(new CMTaskHandler(null, null, null, null)); Thread.currentThread().join(); System.out.println(future.isDone()); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void handleStateChanged(Watcher.Event.KeeperState state) { if (_zkClientForRoutingDataListener == null || _zkClientForRoutingDataListener.isClosed()) { return; } // Resubscribe _zkClientForRoutingDataListener.unsubscribeAll(); _zkClientForRoutingDataListener.subscribeRoutingDataChanges(this, this); resetZkResources(); }
#vulnerable code @Override public void handleStateChanged(Watcher.Event.KeeperState state) { if (_zkClientForListener == null || _zkClientForListener.isClosed()) { return; } // Resubscribe _zkClientForListener.unsubscribeAll(); _zkClientForListener.subscribeRoutingDataChanges(this, this); resetZkResources(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void sendData() { ConcurrentHashMap<String, ZNRecordUpdate> updateCache = null; synchronized(_dataBufferRef) { updateCache = _dataBufferRef.getAndSet(new ConcurrentHashMap<String, ZNRecordUpdate>()); } if(updateCache != null) { List<String> paths = new ArrayList<String>(); List<DataUpdater<ZNRecord>> updaters = new ArrayList<DataUpdater<ZNRecord>>(); List<ZNRecord> vals = new ArrayList<ZNRecord>(); for(ZNRecordUpdate holder : updateCache.values()) { paths.add(holder.getPath()); updaters.add(holder.getZNRecordUpdater()); vals.add(holder.getRecord()); } // Batch write the accumulated updates into zookeeper if(paths.size() > 0) { _accessor.updateChildren(paths, updaters, BaseDataAccessor.Option.PERSISTENT); } LOG.info("Updating " + vals.size() + " records"); } else { LOG.warn("null _dataQueueRef. Should be in the beginning only"); } }
#vulnerable code void sendData() { ConcurrentHashMap<String, ZNRecordUpdate> updateCache = null; synchronized(_dataBufferRef) { updateCache = _dataBufferRef.getAndSet(new ConcurrentHashMap<String, ZNRecordUpdate>()); } if(updateCache != null) { List<String> paths = new ArrayList<String>(); List<DataUpdater<ZNRecord>> updaters = new ArrayList<DataUpdater<ZNRecord>>(); List<ZNRecord> vals = new ArrayList<ZNRecord>(); for(ZNRecordUpdate holder : updateCache.values()) { paths.add(holder.getPath()); updaters.add(holder.getZNRecordUpdater()); vals.add(holder.getRecord()); } // Batch write the accumulated updates into zookeeper if(paths.size() > 0) { _manager.getHelixDataAccessor().updateChildren(paths, updaters, BaseDataAccessor.Option.PERSISTENT); } LOG.info("Updating " + vals.size() + " records"); } else { LOG.warn("null _dataQueueRef. Should be in the beginning only"); } } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION