output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } /* * Alternatives: * - "NSGAII" * - "SteadyStateNSGAII" */ String nsgaIIVersion = "NSGAII" ; /* * Alternatives: * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII * - evaluator = new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII */ SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAIITemplate.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build(nsgaIIVersion) ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } }
#vulnerable code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } /* * Alternatives: * - "NSGAII" * - "SteadyStateNSGAII" */ String nsgaIIVersion = "NSGAII" ; /* * Alternatives: * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII * - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII */ SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAIITemplate.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build(nsgaIIVersion) ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } } #location 85 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public SolutionSet execute() throws JMException, ClassNotFoundException { initParams(); success_ = false; // Step 1 Create the initial population and evaluate for (int i = 0; i < swarmSize_; i++) { Solution particle = new Solution(problem_); problem_.evaluate(particle); evaluations_ ++ ; swarm_.add(particle); } //-> Step2. Initialize the speed_ of each particle for (int i = 0; i < swarmSize_; i++) { XReal particle = new XReal(swarm_.get(i)) ; for (int j = 0; j < problem_.getNumberOfVariables(); j++) { speed_[i][j] = PseudoRandom.randDouble(problem_.getLowerLimit(j)- particle.getValue(i), problem_.getUpperLimit(j)- particle.getValue(i)) ; } } //-> Step 6. Initialize the memory of each particle for (int i = 0; i < swarm_.size(); i++) { Solution particle = new Solution(swarm_.get(i)); localBest_[i] = particle; neighborhoodBest_[i] = getNeighbourWithMinimumFitness(i) ; } //-> Step 7. Iterations .. while (iteration_ < maxIterations_) { //Compute the speed_ computeSpeed() ; //Compute the new positions for the swarm_ computeNewPositions(); //Evaluate the new swarm_ in new positions for (int i = 0; i < swarm_.size(); i++) { Solution particle = swarm_.get(i); problem_.evaluate(particle); evaluations_ ++ ; } //Actualize the memory of this particle for (int i = 0; i < swarm_.size(); i++) { //int flag = comparator_.compare(swarm_.get(i), localBest_[i]); //if (flag < 0) { // the new particle is best_ than the older remember if ((swarm_.get(i).getObjective(0) < localBest_[i].getObjective(0))) { Solution particle = new Solution(swarm_.get(i)); localBest_[i] = particle; } // if if ((swarm_.get(i).getObjective(0) < neighborhoodBest_[i].getObjective(0))) { Solution particle = new Solution(swarm_.get(i)); neighborhoodBest_[i] = particle; } // if } iteration_++; } // Return a population with the best individual SolutionSet resultPopulation = new SolutionSet(1) ; resultPopulation.add(swarm_.get((Integer)findBestSolution_.execute(swarm_))) ; return resultPopulation ; }
#vulnerable code public SolutionSet execute() throws JMException, ClassNotFoundException { initParams(); success_ = false; globalBest_ = null ; //->Step 1 (and 3) Create the initial population and evaluate for (int i = 0; i < swarmSize_; i++) { Solution particle = new Solution(problem_); problem_.evaluate(particle); evaluations_ ++ ; swarm_.add(particle); if ((globalBest_ == null) || (particle.getObjective(0) < globalBest_.getObjective(0))) globalBest_ = new Solution(particle) ; } //-> Step2. Initialize the speed_ of each particle to 0 for (int i = 0; i < swarmSize_; i++) { for (int j = 0; j < problem_.getNumberOfVariables(); j++) { speed_[i][j] = 0.0; } } //-> Step 6. Initialize the memory of each particle for (int i = 0; i < swarm_.size(); i++) { Solution particle = new Solution(swarm_.get(i)); localBest_[i] = particle; } //-> Step 7. Iterations .. while (iteration_ < maxIterations_) { int bestIndividual = (Integer)findBestSolution_.execute(swarm_) ; try { //Compute the speed_ computeSpeed(iteration_, maxIterations_); } catch (IOException ex) { Logger.getLogger(StandardPSO2011.class.getName()).log(Level.SEVERE, null, ex); } //Compute the new positions for the swarm_ computeNewPositions(); //Mutate the swarm_ //mopsoMutation(iteration_, maxIterations_); //Evaluate the new swarm_ in new positions for (int i = 0; i < swarm_.size(); i++) { Solution particle = swarm_.get(i); problem_.evaluate(particle); evaluations_ ++ ; } //Actualize the memory of this particle for (int i = 0; i < swarm_.size(); i++) { //int flag = comparator_.compare(swarm_.get(i), localBest_[i]); //if (flag < 0) { // the new particle is best_ than the older remember if ((swarm_.get(i).getObjective(0) < localBest_[i].getObjective(0))) { Solution particle = new Solution(swarm_.get(i)); localBest_[i] = particle; } // if if ((swarm_.get(i).getObjective(0) < globalBest_.getObjective(0))) { Solution particle = new Solution(swarm_.get(i)); globalBest_ = particle; } // if } iteration_++; } // Return a population with the best individual SolutionSet resultPopulation = new SolutionSet(1) ; resultPopulation.add(swarm_.get((Integer)findBestSolution_.execute(swarm_))) ; return resultPopulation ; } #location 60 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } /* * Alternatives: * - "NSGAII" * - "SteadyStateNSGAII" */ String nsgaIIVersion = "NSGAII" ; /* * Alternatives: * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII * - evaluator = new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII */ SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAIITemplate.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build(nsgaIIVersion) ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } }
#vulnerable code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } /* * Alternatives: * - "NSGAII" * - "SteadyStateNSGAII" */ String nsgaIIVersion = "NSGAII" ; /* * Alternatives: * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII * - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII */ SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAIITemplate.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build(nsgaIIVersion) ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } } #location 84 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void loadInstance() throws IOException { File archivo = new File(fileName_); FileReader fr = null; BufferedReader br = null; fr = new FileReader(archivo); br = new BufferedReader(fr); // File reading String line; int lineCnt = 0; line = br.readLine(); // reading the first line (special case) while (line != null) { StringTokenizer st = new StringTokenizer(line); try { Point auxPoint = new Point(dimensions_); for (int i = 0; i < dimensions_; i++) { auxPoint.vector_[i] = new Double(st.nextToken()); } add(auxPoint); line = br.readLine(); lineCnt++; } catch (NumberFormatException e) { Configuration.logger_.log( Level.WARNING, "Number in a wrong format in line " + lineCnt + "\n" + line, e); line = br.readLine(); lineCnt++; } catch (NoSuchElementException e2) { Configuration.logger_.log( Level.WARNING, "Line " + lineCnt + " does not have the right number of objectives\n" + line, e2); line = br.readLine(); lineCnt++; } } br.close(); }
#vulnerable code public void loadInstance() { try { File archivo = new File(fileName_); FileReader fr = null; BufferedReader br = null; fr = new FileReader(archivo); br = new BufferedReader(fr); // File reading String line; int lineCnt = 0; line = br.readLine(); // reading the first line (special case) while (line != null) { StringTokenizer st = new StringTokenizer(line); try { Point auxPoint = new Point(dimensions_); for (int i = 0; i < dimensions_; i++) { auxPoint.vector_[i] = new Double(st.nextToken()); } add(auxPoint); line = br.readLine(); lineCnt++; } catch (NumberFormatException e) { Configuration.logger_.log( Level.WARNING, "Number in a wrong format in line " + lineCnt + "\n" + line, e); line = br.readLine(); lineCnt++; } catch (NoSuchElementException e2) { Configuration.logger_.log( Level.WARNING, "Line " + lineCnt + " does not have the right number of objectives\n" + line, e2); line = br.readLine(); lineCnt++; } } br.close(); } catch (FileNotFoundException e3) { Configuration.logger_ .log(Level.SEVERE, "The file " + fileName_ + " has not been found in your file system", e3); } catch (IOException e3) { Configuration.logger_ .log(Level.SEVERE, "The file " + fileName_ + " has not been found in your file system", e3); } } #location 41 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } /* * Alternatives: * - "NSGAII" * - "SteadyStateNSGAII" */ String nsgaIIVersion = "NSGAII" ; /* * Alternatives: * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII * - evaluator = new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII */ SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAIITemplate.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build(nsgaIIVersion) ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } }
#vulnerable code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } /* * Alternatives: * - "NSGAII" * - "SteadyStateNSGAII" */ String nsgaIIVersion = "NSGAII" ; /* * Alternatives: * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII * - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII */ SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAIITemplate.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build(nsgaIIVersion) ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } } #location 83 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { neighborhood_ = parentThread_.neighborhood_; problem_ = parentThread_.problem_; lambda_ = parentThread_.lambda_; population_ = parentThread_.population_; z_ = parentThread_.z_; indArray_ = parentThread_.indArray_; barrier_ = parentThread_.barrier_; int partitions = parentThread_.populationSize_ / parentThread_.numberOfThreads_; evaluations_ = 0; maxEvaluations_ = parentThread_.maxEvaluations_ / parentThread_.numberOfThreads_; try { //Configuration.logger_.info("en espera: " + barrier_.getNumberWaiting()) ; barrier_.await(); //Configuration.logger_.info("Running: " + id_ ) ; } catch (InterruptedException e) { Configuration.logger_.log(Level.SEVERE, "Error", e); } catch (BrokenBarrierException e) { Configuration.logger_.log(Level.SEVERE, "Error", e); } int first; int last; first = partitions * id_; if (id_ == (parentThread_.numberOfThreads_ - 1)) { last = parentThread_.populationSize_ - 1; } else { last = first + partitions - 1; } Configuration.logger_.info("Id: " + id_ + " Partitions: " + partitions + " First: " + first + " Last: " + last); do { for (int i = first; i <= last; i++) { int n = i; int type; double rnd = PseudoRandom.randDouble(); // STEP 2.1. Mating selection based on probability if (rnd < parentThread_.delta_) { // neighborhood type = 1; } else { // whole population type = 2; } Vector<Integer> p = new Vector<Integer>(); this.matingSelection(p, n, 2, type); // STEP 2.2. Reproduction Solution child = null; Solution[] parents = new Solution[3]; try { synchronized (parentThread_) { parents[0] = parentThread_.population_.get(p.get(0)); parents[1] = parentThread_.population_.get(p.get(1)); parents[2] = parentThread_.population_.get(n); // Apply DE crossover child = (Solution) parentThread_.crossover_ .execute(new Object[] {parentThread_.population_.get(n), parents}); } // Apply mutation parentThread_.mutation_.execute(child); // Evaluation parentThread_.problem_.evaluate(child); } catch (JMetalException ex) { Logger.getLogger(pMOEAD.class.getName()).log(Level.SEVERE, null, ex); } evaluations_++; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update idealPoint updateReference(child); // STEP 2.5. Update of solutions try { updateOfSolutions(child, n, type); } catch (JMetalException e) { Configuration.logger_.log(Level.SEVERE, "Error", e); } } } while (evaluations_ < maxEvaluations_); long estimatedTime = System.currentTimeMillis() - parentThread_.initTime_; Configuration.logger_.info("Time thread " + id_ + ": " + estimatedTime); }
#vulnerable code public void run() { neighborhood_ = parentThread_.neighborhood_; problem_ = parentThread_.problem_; lambda_ = parentThread_.lambda_; population_ = parentThread_.population_; z_ = parentThread_.z_; indArray_ = parentThread_.indArray_; barrier_ = parentThread_.barrier_; int partitions = parentThread_.populationSize_ / parentThread_.numberOfThreads_; evaluations_ = 0; maxEvaluations_ = parentThread_.maxEvaluations_ / parentThread_.numberOfThreads_; try { //Configuration.logger_.info("en espera: " + barrier_.getNumberWaiting()) ; barrier_.await(); //Configuration.logger_.info("Running: " + id_ ) ; } catch (InterruptedException e) { Configuration.logger_.log(Level.SEVERE, "Error", e); } catch (BrokenBarrierException e) { Configuration.logger_.log(Level.SEVERE, "Error", e); } int first; int last; first = partitions * id_; if (id_ == (parentThread_.numberOfThreads_ - 1)) { last = parentThread_.populationSize_ - 1; } else { last = first + partitions - 1; } Configuration.logger_.info("Id: " + id_ + " Partitions: " + partitions + " First: " + first + " Last: " + last); do { for (int i = first; i <= last; i++) { int n = i; int type; double rnd = PseudoRandom.randDouble(); // STEP 2.1. Mating selection based on probability if (rnd < parentThread_.delta_) { // neighborhood type = 1; } else { // whole population type = 2; } Vector<Integer> p = new Vector<Integer>(); this.matingSelection(p, n, 2, type); // STEP 2.2. Reproduction Solution child = null; Solution[] parents = new Solution[3]; try { synchronized (parentThread_) { parents[0] = parentThread_.population_.get(p.get(0)); parents[1] = parentThread_.population_.get(p.get(1)); parents[2] = parentThread_.population_.get(n); // Apply DE crossover child = (Solution) parentThread_.crossover_ .execute(new Object[] {parentThread_.population_.get(n), parents}); } // Apply mutation parentThread_.mutation_.execute(child); // Evaluation parentThread_.problem_.evaluate(child); } catch (JMetalException ex) { Logger.getLogger(pMOEAD.class.getName()).log(Level.SEVERE, null, ex); } evaluations_++; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ updateReference(child); // STEP 2.5. Update of solutions try { updateOfSolutions(child, n, type); } catch (JMetalException e) { Configuration.logger_.log(Level.SEVERE, "Error", e); } } } while (evaluations_ < maxEvaluations_); long estimatedTime = System.currentTimeMillis() - parentThread_.initTime_; Configuration.logger_.info("Time thread " + id_ + ": " + estimatedTime); } #location 42 #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 JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } /* * Alternatives: * - "NSGAII" * - "SteadyStateNSGAII" */ String nsgaIIVersion = "NSGAII" ; /* * Alternatives: * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII * - evaluator = new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII */ SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAIITemplate.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build(nsgaIIVersion) ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } }
#vulnerable code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } /* * Alternatives: * - "NSGAII" * - "SteadyStateNSGAII" */ String nsgaIIVersion = "NSGAII" ; /* * Alternatives: * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII * - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII */ SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAIITemplate.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build(nsgaIIVersion) ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } } #location 85 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static public void loadColumnVectorFromFile(String file, int rows, double[] column) throws JMetalException { try { BufferedReader brSrc = new BufferedReader( new InputStreamReader(new FileInputStream(ClassLoader.getSystemResource(file).getPath()))) ; //BufferedReader brSrc = new BufferedReader(new FileReader(file)); loadColumnVector(brSrc, rows, column); brSrc.close(); } catch (Exception e) { JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); throw new JMetalException("Error in Benchmark.java"); } }
#vulnerable code static public void loadColumnVectorFromFile(String file, int rows, double[] column) throws JMetalException { try { BufferedReader brSrc = new BufferedReader(new FileReader(file)); loadColumnVector(brSrc, rows, column); brSrc.close(); } catch (Exception e) { JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); throw new JMetalException("Error in Benchmark.java"); } } #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 testConfigure2() throws Exception { double epsilon = 0.000000000000001 ; Settings smsemoaSettings = new SMSEMOASettings("Fonseca"); SMSEMOA algorithm = (SMSEMOA) smsemoaSettings.configure(configuration) ; Problem problem = new Fonseca("Real") ; SBXCrossover crossover = (SBXCrossover) algorithm.getCrossoverOperator() ; double pc = crossover.getCrossoverProbability() ; double dic = crossover.getDistributionIndex() ; PolynomialMutation mutation = (PolynomialMutation)algorithm.getMutationOperator() ; double pm = mutation.getMutationProbability() ; double dim = mutation.getDistributionIndex() ; double offset = algorithm.getOffset() ; assertEquals(100, algorithm.getPopulationSize()); assertEquals(25000, algorithm.getMaxEvaluations()); assertEquals(0.9, pc, epsilon); assertEquals(20.0, dic, epsilon); assertEquals(1.0/problem.getNumberOfVariables(), pm, epsilon); assertEquals(20.0, dim, epsilon); assertEquals(100.0, offset, epsilon); }
#vulnerable code @Test public void testConfigure2() throws Exception { double epsilon = 0.000000000000001 ; Settings smsemoaSettings = new SMSEMOASettings("Fonseca"); Algorithm algorithm = smsemoaSettings.configure(configuration_) ; Problem problem = new Fonseca("Real") ; SBXCrossover crossover = (SBXCrossover)algorithm.getOperator("crossover") ; double pc = (Double)crossover.getParameter("probability") ; double dic = (Double)crossover.getParameter("distributionIndex") ; PolynomialMutation mutation = (PolynomialMutation)algorithm.getOperator("mutation") ; double pm = (Double)mutation.getParameter("probability") ; double dim = (Double)mutation.getParameter("distributionIndex") ; assertEquals("SMSEMOA_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue()); assertEquals("SMSEMOA_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue()); assertEquals("SMSEMOA_SettingsTest", 0.9, pc, epsilon); assertEquals("SMSEMOA_SettingsTest", 20.0, dic, epsilon); assertEquals("SMSEMOA_SettingsTest", 1.0/problem.getNumberOfVariables(), pm, epsilon); assertEquals("SMSEMOA_SettingsTest", 20.0, dim, epsilon); assertEquals("SMSEMOA_SettingsTest", 100.0, ((Double)algorithm.getInputParameter("offset")).doubleValue(), epsilon); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConfigure() throws Exception { double epsilon = 0.000000000000001 ; Settings nsgaIISettings = new NSGAIIBinarySettings("ZDT5"); NSGAII algorithm = (NSGAII)nsgaIISettings.configure() ; Problem problem = new ZDT5("Binary") ; SinglePointCrossover crossover = (SinglePointCrossover) algorithm.getCrossoverOperator() ; double pc = crossover.getCrossoverProbability() ; BitFlipMutation mutation = (BitFlipMutation)algorithm.getMutationOperator() ; double pm = mutation.getMutationProbability() ; assertEquals("NSGAIIBinary_SettingsTest", 100, algorithm.getPopulationSize()); assertEquals("NSGAIIBinary_SettingsTest", 25000, algorithm.getMaxEvaluations()) ; assertEquals("NSGAIIBinary_SettingsTest", 0.9, pc, epsilon); assertEquals("NSGAIIBinary_SettingsTest", 1.0/problem.getNumberOfBits(), pm, epsilon); }
#vulnerable code @Test public void testConfigure() throws Exception { double epsilon = 0.000000000000001 ; Settings nsgaIISettings = new NSGAIIBinarySettings("ZDT5"); Algorithm algorithm = nsgaIISettings.configure() ; Problem problem = new ZDT5("Binary") ; SinglePointCrossover crossover = (SinglePointCrossover)algorithm.getOperator("crossover") ; double pc = (Double)crossover.getParameter("probability") ; BitFlipMutation mutation = (BitFlipMutation)algorithm.getOperator("mutation") ; double pm = (Double)mutation.getParameter("probability") ; assertEquals("NSGAIIBinary_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue()); assertEquals("NSGAIIBinary_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue()); assertEquals("NSGAIIBinary_SettingsTest", 0.9, pc, epsilon); assertEquals("NSGAIIBinary_SettingsTest", 1.0/problem.getNumberOfBits(), pm, epsilon); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); //problem = new Kursawe("BinaryReal", 3); //problem = new Water("Real"); //problem = new ZDT3("ArrayReal", 30); //problem = new ConstrEx("Real"); //problem = new DTLZ1("Real"); //problem = new OKA2("Real") ; } //Injector injector = Guice.createInjector(new ExecutorModule()) ; //Executor executor = injector.getInstance(Executor.class) ; SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator(); //SolutionSetEvaluator executor = new MultithreadedSolutionSetEvaluator(4, problem) ; algorithm = new NSGAIIE(problem, evaluator); // Algorithm parameters algorithm.setInputParameter("populationSize", 100); algorithm.setInputParameter("maxEvaluations", 25000); // Mutation and Crossover for Real codification HashMap<String, Object> crossoverParameters = new HashMap<String, Object>(); crossoverParameters.put("probability", 0.9); crossoverParameters.put("distributionIndex", 20.0); crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", crossoverParameters); HashMap<String, Object> mutationParameters = new HashMap<String, Object>(); mutationParameters.put("probability", 1.0 / problem.getNumberOfVariables()); mutationParameters.put("distributionIndex", 20.0); mutation = MutationFactory.getMutationOperator("PolynomialMutation", mutationParameters); // Selection Operator HashMap<String, Object> selectionParameters = new HashMap<String, Object>() ; selection = SelectionFactory.getSelectionOperator("BinaryTournament2", selectionParameters); // Add the operators to the algorithm algorithm.addOperator("crossover", crossover); algorithm.addOperator("mutation", mutation); algorithm.addOperator("selection", selection); // Add the indicator object to the algorithm algorithm.setInputParameter("indicators", indicators); // Execute the Algorithm long initTime = System.currentTimeMillis(); SolutionSet population = algorithm.execute(); long estimatedTime = System.currentTimeMillis() - initTime; logger_.info("Total execution time: " + estimatedTime + "ms"); // Result messages FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ; fileContext.setSeparator("\t"); logger_.info("Variables values have been writen to file VAR.tsv"); SolutionSetOutput.printVariablesToFile(fileContext, population) ; fileContext = new DefaultFileOutputContext("FUN.tsv"); fileContext.setSeparator("\t"); SolutionSetOutput.printObjectivesToFile(fileContext, population); //population.printObjectivesToFile("FUN"); //logger_.info("Objectives values have been written to file FUN"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); int evaluations = (Integer) algorithm.getOutputParameter("evaluations"); logger_.info("Speed : " + evaluations + " evaluations"); } evaluator.shutdown(); }
#vulnerable code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { //problem = new Kursawe("Real", 3); //problem = new Kursawe("BinaryReal", 3); //problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); //problem = new ConstrEx("Real"); //problem = new DTLZ1("Real"); //problem = new OKA2("Real") ; } //Injector injector = Guice.createInjector(new ExecutorModule()) ; //Executor executor = injector.getInstance(Executor.class) ; SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator(); //SolutionSetEvaluator executor = new MultithreadedSolutionSetEvaluator(4, problem) ; algorithm = new NSGAIIE(problem, evaluator); // Algorithm parameters algorithm.setInputParameter("populationSize", 100); algorithm.setInputParameter("maxEvaluations", 25000); // Mutation and Crossover for Real codification HashMap<String, Object> crossoverParameters = new HashMap<String, Object>(); crossoverParameters.put("probability", 0.9); crossoverParameters.put("distributionIndex", 20.0); crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", crossoverParameters); HashMap<String, Object> mutationParameters = new HashMap<String, Object>(); mutationParameters.put("probability", 1.0 / problem.getNumberOfVariables()); mutationParameters.put("distributionIndex", 20.0); mutation = MutationFactory.getMutationOperator("PolynomialMutation", mutationParameters); // Selection Operator HashMap<String, Object> selectionParameters = null; // FIXME: why we are passing null? selection = SelectionFactory.getSelectionOperator("BinaryTournament2", selectionParameters); // Add the operators to the algorithm algorithm.addOperator("crossover", crossover); algorithm.addOperator("mutation", mutation); algorithm.addOperator("selection", selection); // Add the indicator object to the algorithm algorithm.setInputParameter("indicators", indicators); // Execute the Algorithm long initTime = System.currentTimeMillis(); SolutionSet population = algorithm.execute(); long estimatedTime = System.currentTimeMillis() - initTime; logger_.info("Total execution time: " + estimatedTime + "ms"); // Result messages FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ; fileContext.setSeparator("\t"); logger_.info("Variables values have been writen to file VAR.tsv"); SolutionSetOutput.printVariablesToFile(fileContext, population) ; fileContext = new DefaultFileOutputContext("FUN.tsv"); fileContext.setSeparator("\t"); SolutionSetOutput.printObjectivesToFile(fileContext, population); //population.printObjectivesToFile("FUN"); //logger_.info("Objectives values have been written to file FUN"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); int evaluations = (Integer) algorithm.getOutputParameter("evaluations"); logger_.info("Speed : " + evaluations + " evaluations"); } evaluator.shutdown(); } #location 87 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static public void loadMatrixFromFile(String file, int rows, int columns, double[][] matrix) throws JMetalException { try { BufferedReader brSrc = new BufferedReader( new InputStreamReader(new FileInputStream(ClassLoader.getSystemResource(file).getPath()))) ; //BufferedReader brSrc = new BufferedReader(new FileReader(file)); loadMatrix(brSrc, rows, columns, matrix); brSrc.close(); } catch (Exception e) { throw new JMetalException("Error in Benchmark.java", e); } }
#vulnerable code static public void loadMatrixFromFile(String file, int rows, int columns, double[][] matrix) throws JMetalException { try { BufferedReader brSrc = new BufferedReader(new FileReader(file)); loadMatrix(brSrc, rows, columns, matrix); brSrc.close(); } catch (Exception e) { JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); throw new JMetalException("Error in Benchmark.java"); } } #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 testConfigure2() throws Exception { double epsilon = 0.000000000000001 ; Settings fastSMEEMOASettings = new FastSMSEMOASettings("Fonseca"); FastSMSEMOA algorithm = (FastSMSEMOA) fastSMEEMOASettings.configure(configuration) ; Problem problem = new Fonseca("Real") ; SBXCrossover crossover = (SBXCrossover) algorithm.getCrossoverOperator() ; double pc = crossover.getCrossoverProbability() ; double dic = crossover.getDistributionIndex() ; PolynomialMutation mutation = (PolynomialMutation)algorithm.getMutationOperator() ; double pm = mutation.getMutationProbability() ; double dim = mutation.getDistributionIndex() ; double offset = algorithm.getOffset() ; assertEquals(100, algorithm.getPopulationSize()); assertEquals(25000, algorithm.getMaxEvaluations()); assertEquals(0.9, pc, epsilon); assertEquals(20.0, dic, epsilon); assertEquals(1.0 / problem.getNumberOfVariables(), pm, epsilon); assertEquals(20.0, dim, epsilon); assertEquals(100.0, offset, epsilon); }
#vulnerable code @Test public void testConfigure2() throws Exception { double epsilon = 0.000000000000001 ; Settings smsemoaSettings = new FastSMSEMOASettings("Fonseca"); Algorithm algorithm = smsemoaSettings.configure(configuration_) ; Problem problem = new Fonseca("Real") ; SBXCrossover crossover = (SBXCrossover)algorithm.getOperator("crossover") ; double pc = (Double)crossover.getParameter("probability") ; double dic = (Double)crossover.getParameter("distributionIndex") ; PolynomialMutation mutation = (PolynomialMutation)algorithm.getOperator("mutation") ; double pm = (Double)mutation.getParameter("probability") ; double dim = (Double)mutation.getParameter("distributionIndex") ; Assert.assertEquals("SMSEMOA_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue()); Assert.assertEquals("SMSEMOA_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue()); Assert.assertEquals("SMSEMOA_SettingsTest", 0.9, pc, epsilon); Assert.assertEquals("SMSEMOA_SettingsTest", 20.0, dic, epsilon); Assert.assertEquals("SMSEMOA_SettingsTest", 1.0/problem.getNumberOfVariables(), pm, epsilon); Assert.assertEquals("SMSEMOA_SettingsTest", 20.0, dim, epsilon); Assert.assertEquals("SMSEMOA_SettingsTest", 100.0, ((Double)algorithm.getInputParameter("offset")).doubleValue(), epsilon); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test() throws JMException { double epsilon = 0.000000000000001; GDE3_Settings GDE3Settings = new GDE3_Settings("Fonseca"); GDE3 algorithm = (GDE3) GDE3Settings.configure(); DifferentialEvolutionCrossover crossover = (DifferentialEvolutionCrossover) algorithm.getCrossoverOperator(); Assert.assertEquals("GDE3_SettingsTest", 100, algorithm.getPopulationSize()); Assert.assertEquals("GDE3_SettingsTest", 250, algorithm.getMaxIterations()); Assert.assertEquals("GDE3_SettingsTest", 0.5, crossover.getCr(), epsilon); Assert.assertEquals("GDE3_SettingsTest", 0.5, crossover.getF(), epsilon); }
#vulnerable code @Test public void test() throws JMException { double epsilon = 0.000000000000001; Settings GDE3Settings = new GDE3_Settings("Fonseca"); Algorithm algorithm = GDE3Settings.configure(); //Problem problem = new Fonseca("Real"); DifferentialEvolutionCrossover crossover = (DifferentialEvolutionCrossover)algorithm.getOperator("crossover") ; double CR = (Double)crossover.getParameter("CR") ; double F = (Double)crossover.getParameter("F") ; Assert.assertEquals("GDE3_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue()); Assert.assertEquals("GDE3_SettingsTest", 250, ((Integer)algorithm.getInputParameter("maxIterations")).intValue()); Assert.assertEquals("GDE3_SettingsTest", 0.5, CR, epsilon); Assert.assertEquals("GDE3_SettingsTest", 0.5, F, epsilon); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConfigure2() throws Exception { double epsilon = 0.000000000000001 ; Settings nsgaIISettings = new NSGAIIBinarySettings("ZDT5"); NSGAII algorithm = (NSGAII)nsgaIISettings.configure(configuration_) ; Problem problem = new ZDT5("Binary") ; SinglePointCrossover crossover = (SinglePointCrossover) algorithm.getCrossoverOperator() ; double pc = crossover.getCrossoverProbability() ; BitFlipMutation mutation = (BitFlipMutation)algorithm.getMutationOperator() ; double pm = mutation.getMutationProbability() ; assertEquals("NSGAIIBinary_SettingsTest", 100, algorithm.getPopulationSize()); assertEquals("NSGAIIBinary_SettingsTest", 25000, algorithm.getMaxEvaluations()) ; assertEquals("NSGAIIBinary_SettingsTest", 0.9, pc, epsilon); assertEquals("NSGAIIBinary_SettingsTest", 1.0/problem.getNumberOfBits(), pm, epsilon); }
#vulnerable code @Test public void testConfigure2() throws Exception { double epsilon = 0.000000000000001 ; Settings nsgaIISettings = new NSGAIIBinarySettings("ZDT5"); Algorithm algorithm = nsgaIISettings.configure(configuration_) ; Problem problem = new ZDT5("Binary") ; SinglePointCrossover crossover = (SinglePointCrossover)algorithm.getOperator("crossover") ; double pc = (Double)crossover.getParameter("probability") ; BitFlipMutation mutation = (BitFlipMutation)algorithm.getOperator("mutation") ; double pm = (Double)mutation.getParameter("probability") ; assertEquals("NSGAIIBinary_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue()); assertEquals("NSGAIIBinary_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue()); assertEquals("NSGAIIBinary_SettingsTest", 0.9, pc, epsilon); assertEquals("NSGAIIBinary_SettingsTest", 1.0/problem.getNumberOfBits(), pm, epsilon); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } /* * Alternatives: * - "NSGAII" * - "SteadyStateNSGAII" */ String nsgaIIVersion = "NSGAII" ; /* * Alternatives: * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII * - evaluator = new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII */ SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAIITemplate.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build(nsgaIIVersion) ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } }
#vulnerable code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } /* * Alternatives: * - "NSGAII" * - "SteadyStateNSGAII" */ String nsgaIIVersion = "NSGAII" ; /* * Alternatives: * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII * - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII */ SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAIITemplate.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build(nsgaIIVersion) ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } } #location 81 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public int compare(Solution solution1, Solution solution2) { if (solution1 == null) { return 1; } else if (solution2 == null) { return -1; } if (NSGAIIAttr.getAttributes(solution1).getRank() < NSGAIIAttr.getAttributes(solution2).getRank()) { return -1; } if (NSGAIIAttr.getAttributes(solution1).getRank() > NSGAIIAttr.getAttributes(solution2).getRank()) { return 1; } return 0; }
#vulnerable code @Override public int compare(Solution solution1, Solution solution2) { if (solution1 == null) { return 1; } else if (solution2 == null) { return -1; } if ((int)solution1.getAlgorithmAttributes().getAttribute("Rank") < (int)solution2.getAlgorithmAttributes().getAttribute("Rank")) { return -1; } if ((int)solution1.getAlgorithmAttributes().getAttribute("Rank") > (int)solution2.getAlgorithmAttributes().getAttribute("Rank")) { return 1; } return 0; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static public void loadNMatrixFromFile(String file, int N, int rows, int columns, double[][][] matrix) throws JMetalException { try { BufferedReader brSrc = new BufferedReader( new InputStreamReader(new FileInputStream(ClassLoader.getSystemResource(file).getPath()))) ; //BufferedReader brSrc = new BufferedReader(new FileReader(file)); for (int i = 0; i < N; i++) { loadMatrix(brSrc, rows, columns, matrix[i]); } brSrc.close(); } catch (Exception e) { throw new JMetalException("Error in Benchmark.java", e); } }
#vulnerable code static public void loadNMatrixFromFile(String file, int N, int rows, int columns, double[][][] matrix) throws JMetalException { try { BufferedReader brSrc = new BufferedReader(new FileReader(file)); for (int i = 0; i < N; i++) { loadMatrix(brSrc, rows, columns, matrix[i]); } brSrc.close(); } catch (Exception e) { JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); throw new JMetalException("Error in Benchmark.java"); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); //problem = new Kursawe("BinaryReal", 3); //problem = new Water("Real"); //problem = new ZDT3("ArrayReal", 30); //problem = new ConstrEx("Real"); //problem = new DTLZ1("Real"); //problem = new OKA2("Real") ; } //Injector injector = Guice.createInjector(new ExecutorModule()) ; //Executor executor = injector.getInstance(Executor.class) ; SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator(); //SolutionSetEvaluator executor = new MultithreadedSolutionSetEvaluator(4, problem) ; algorithm = new NSGAIIE(problem, evaluator); // Algorithm parameters algorithm.setInputParameter("populationSize", 100); algorithm.setInputParameter("maxEvaluations", 25000); // Mutation and Crossover for Real codification HashMap<String, Object> crossoverParameters = new HashMap<String, Object>(); crossoverParameters.put("probability", 0.9); crossoverParameters.put("distributionIndex", 20.0); crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", crossoverParameters); HashMap<String, Object> mutationParameters = new HashMap<String, Object>(); mutationParameters.put("probability", 1.0 / problem.getNumberOfVariables()); mutationParameters.put("distributionIndex", 20.0); mutation = MutationFactory.getMutationOperator("PolynomialMutation", mutationParameters); // Selection Operator HashMap<String, Object> selectionParameters = new HashMap<String, Object>() ; selection = SelectionFactory.getSelectionOperator("BinaryTournament2", selectionParameters); // Add the operators to the algorithm algorithm.addOperator("crossover", crossover); algorithm.addOperator("mutation", mutation); algorithm.addOperator("selection", selection); // Add the indicator object to the algorithm algorithm.setInputParameter("indicators", indicators); // Execute the Algorithm long initTime = System.currentTimeMillis(); SolutionSet population = algorithm.execute(); long estimatedTime = System.currentTimeMillis() - initTime; logger_.info("Total execution time: " + estimatedTime + "ms"); // Result messages FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ; fileContext.setSeparator("\t"); logger_.info("Variables values have been writen to file VAR.tsv"); SolutionSetOutput.printVariablesToFile(fileContext, population) ; fileContext = new DefaultFileOutputContext("FUN.tsv"); fileContext.setSeparator("\t"); SolutionSetOutput.printObjectivesToFile(fileContext, population); //population.printObjectivesToFile("FUN"); //logger_.info("Objectives values have been written to file FUN"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); int evaluations = (Integer) algorithm.getOutputParameter("evaluations"); logger_.info("Speed : " + evaluations + " evaluations"); } evaluator.shutdown(); }
#vulnerable code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { //problem = new Kursawe("Real", 3); //problem = new Kursawe("BinaryReal", 3); //problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); //problem = new ConstrEx("Real"); //problem = new DTLZ1("Real"); //problem = new OKA2("Real") ; } //Injector injector = Guice.createInjector(new ExecutorModule()) ; //Executor executor = injector.getInstance(Executor.class) ; SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator(); //SolutionSetEvaluator executor = new MultithreadedSolutionSetEvaluator(4, problem) ; algorithm = new NSGAIIE(problem, evaluator); // Algorithm parameters algorithm.setInputParameter("populationSize", 100); algorithm.setInputParameter("maxEvaluations", 25000); // Mutation and Crossover for Real codification HashMap<String, Object> crossoverParameters = new HashMap<String, Object>(); crossoverParameters.put("probability", 0.9); crossoverParameters.put("distributionIndex", 20.0); crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", crossoverParameters); HashMap<String, Object> mutationParameters = new HashMap<String, Object>(); mutationParameters.put("probability", 1.0 / problem.getNumberOfVariables()); mutationParameters.put("distributionIndex", 20.0); mutation = MutationFactory.getMutationOperator("PolynomialMutation", mutationParameters); // Selection Operator HashMap<String, Object> selectionParameters = null; // FIXME: why we are passing null? selection = SelectionFactory.getSelectionOperator("BinaryTournament2", selectionParameters); // Add the operators to the algorithm algorithm.addOperator("crossover", crossover); algorithm.addOperator("mutation", mutation); algorithm.addOperator("selection", selection); // Add the indicator object to the algorithm algorithm.setInputParameter("indicators", indicators); // Execute the Algorithm long initTime = System.currentTimeMillis(); SolutionSet population = algorithm.execute(); long estimatedTime = System.currentTimeMillis() - initTime; logger_.info("Total execution time: " + estimatedTime + "ms"); // Result messages FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ; fileContext.setSeparator("\t"); logger_.info("Variables values have been writen to file VAR.tsv"); SolutionSetOutput.printVariablesToFile(fileContext, population) ; fileContext = new DefaultFileOutputContext("FUN.tsv"); fileContext.setSeparator("\t"); SolutionSetOutput.printObjectivesToFile(fileContext, population); //population.printObjectivesToFile("FUN"); //logger_.info("Objectives values have been written to file FUN"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); int evaluations = (Integer) algorithm.getOutputParameter("evaluations"); logger_.info("Speed : " + evaluations + " evaluations"); } evaluator.shutdown(); } #location 82 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConfigure() throws Exception { double epsilon = 0.000000000000001 ; Settings fastSMEEMOASettings = new FastSMSEMOASettings("Fonseca"); FastSMSEMOA algorithm = (FastSMSEMOA) fastSMEEMOASettings.configure() ; Problem problem = new Fonseca("Real") ; SBXCrossover crossover = (SBXCrossover) algorithm.getCrossoverOperator() ; double pc = crossover.getCrossoverProbability() ; double dic = crossover.getDistributionIndex() ; PolynomialMutation mutation = (PolynomialMutation)algorithm.getMutationOperator() ; double pm = mutation.getMutationProbability() ; double dim = mutation.getDistributionIndex() ; double offset = algorithm.getOffset() ; assertEquals(100, algorithm.getPopulationSize()); assertEquals(25000, algorithm.getMaxEvaluations()); assertEquals(0.9, pc, epsilon); assertEquals(20.0, dic, epsilon); assertEquals(1.0/problem.getNumberOfVariables(), pm, epsilon); assertEquals(20.0, dim, epsilon); assertEquals(100.0, offset, epsilon); }
#vulnerable code @Test public void testConfigure() throws Exception { double epsilon = 0.000000000000001 ; Settings smsemoaSettings = new FastSMSEMOASettings("Fonseca"); Algorithm algorithm = smsemoaSettings.configure() ; Problem problem = new Fonseca("Real") ; SBXCrossover crossover = (SBXCrossover)algorithm.getOperator("crossover") ; double pc = (Double)crossover.getParameter("probability") ; double dic = (Double)crossover.getParameter("distributionIndex") ; PolynomialMutation mutation = (PolynomialMutation)algorithm.getOperator("mutation") ; double pm = (Double)mutation.getParameter("probability") ; double dim = (Double)mutation.getParameter("distributionIndex") ; Assert.assertEquals("SMSEMOA_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue()); Assert.assertEquals("SMSEMOA_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue()); Assert.assertEquals("SMSEMOA_SettingsTest", 0.9, pc, epsilon); Assert.assertEquals("SMSEMOA_SettingsTest", 20.0, dic, epsilon); Assert.assertEquals("SMSEMOA_SettingsTest", 1.0/problem.getNumberOfVariables(), pm, epsilon); Assert.assertEquals("SMSEMOA_SettingsTest", 20.0, dim, epsilon); Assert.assertEquals("SMSEMOA_SettingsTest", 100.0, ((Double)algorithm.getInputParameter("offset")).doubleValue(), epsilon); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test2() throws JMException { double epsilon = 0.000000000000001; Settings GDE3Settings = new GDE3_Settings("Fonseca"); GDE3 algorithm = (GDE3) GDE3Settings.configure(configuration_); DifferentialEvolutionCrossover crossover = (DifferentialEvolutionCrossover) algorithm.getCrossoverOperator(); Assert.assertEquals("GDE3_SettingsTest", 100, algorithm.getPopulationSize()); Assert.assertEquals("GDE3_SettingsTest", 250, algorithm.getMaxIterations()); Assert.assertEquals("GDE3_SettingsTest", 0.5, crossover.getCr(), epsilon); Assert.assertEquals("GDE3_SettingsTest", 0.5, crossover.getF(), epsilon); }
#vulnerable code @Test public void test2() throws JMException { double epsilon = 0.000000000000001; Settings GDE3Settings = new GDE3_Settings("Fonseca"); Algorithm algorithm = GDE3Settings.configure(configuration_); //Problem problem = new Fonseca("Real"); DifferentialEvolutionCrossover crossover = (DifferentialEvolutionCrossover)algorithm.getOperator("crossover") ; double CR = (Double)crossover.getParameter("CR") ; double F = (Double)crossover.getParameter("F") ; Assert.assertEquals("GDE3_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue()); Assert.assertEquals("GDE3_SettingsTest", 250, ((Integer)algorithm.getInputParameter("maxIterations")).intValue()); Assert.assertEquals("GDE3_SettingsTest", 0.5, CR, epsilon); Assert.assertEquals("GDE3_SettingsTest", 0.5, F, epsilon); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Kursawe("BinaryReal", 3); problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } SolutionSetEvaluator evaluator = new MultithreadedSolutionSetEvaluator(4, problem) ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAII.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build() ; AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) .execute() ; SolutionSet population = algorithmRunner.getSolutionSet() ; long computingTime = algorithmRunner.getComputingTime() ; new SolutionSetOutput.Printer(population) .separator("\t") .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); logger_.info("Total execution time: " + computingTime + "ms"); logger_.info("Objectives values have been written to file FUN.tsv"); logger_.info("Variables values have been written to file VAR.tsv"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } }
#vulnerable code public static void main(String[] args) throws JMException, SecurityException, IOException, ClassNotFoundException { Problem problem; Algorithm algorithm; Operator crossover; Operator mutation; Operator selection; QualityIndicator indicators; // Logger object and file to store log messages logger_ = Configuration.logger_; fileHandler_ = new FileHandler("NSGAII_main.log"); logger_.addHandler(fileHandler_); indicators = null; if (args.length == 1) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); } else if (args.length == 2) { Object[] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0], params); indicators = new QualityIndicator(problem, args[1]); } else { problem = new Kursawe("Real", 3); /* Examples: problem = new Kursawe("BinaryReal", 3); problem = new Water("Real"); problem = new ZDT3("ArrayReal", 30); problem = new ConstrEx("Real"); problem = new DTLZ1("Real"); problem = new OKA2("Real") */ } SolutionSetEvaluator evaluator = new MultithreadedSolutionSetEvaluator(4, problem) ; crossover = new SBXCrossover.Builder() .distributionIndex(20.0) .probability(0.9) .build() ; mutation = new PolynomialMutation.Builder() .distributionIndex(20.0) .probability(1.0/problem.getNumberOfVariables()) .build(); selection = new BinaryTournament2.Builder() .build(); algorithm = new NSGAII.Builder(problem, evaluator) .crossover(crossover) .mutation(mutation) .selection(selection) .maxEvaluations(25000) .populationSize(100) .build() ; // Execute the Algorithm long initTime = System.currentTimeMillis(); SolutionSet population = algorithm.execute(); long estimatedTime = System.currentTimeMillis() - initTime; logger_.info("Total execution time: " + estimatedTime + "ms"); // Result messages FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ; fileContext.setSeparator("\t"); logger_.info("Variables values have been writen to file VAR.tsv"); SolutionSetOutput.printVariablesToFile(fileContext, population) ; fileContext = new DefaultFileOutputContext("FUN.tsv"); fileContext.setSeparator("\t"); SolutionSetOutput.printObjectivesToFile(fileContext, population); logger_.info("Objectives values have been written to file FUN"); if (indicators != null) { logger_.info("Quality indicators"); logger_.info("Hypervolume: " + indicators.getHypervolume(population)); logger_.info("GD : " + indicators.getGD(population)); logger_.info("IGD : " + indicators.getIGD(population)); logger_.info("Spread : " + indicators.getSpread(population)); logger_.info("Epsilon : " + indicators.getEpsilon(population)); } } #location 65 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws JMetalException, IOException { ExperimentData experimentData = new ExperimentData.Builder("Experiment2") .algorithmNameList(new String[]{"NSGAII", "SMPSO", "MOCell"}) .problemList(new String[]{"ZDT1", "ZDT2", "ZDT3", "ZDT4"}) .experimentBaseDirectory("/Users/antelverde/Softw/jMetal/jMetalGitHub/pruebas") .outputParetoFrontFileName("FUN") .outputParetoSetFileName("VAR") .independentRuns(20) .build() ; AlgorithmExecution algorithmExecution = new AlgorithmExecution.Builder(experimentData) .numberOfThreads(8) .paretoSetFileName("VAR") .paretoFrontFileName("FUN") //.useAlgorithmConfigurationFiles() .build() ; ParetoFrontsGeneration paretoFrontsGeneration = new ParetoFrontsGeneration.Builder(experimentData) .build() ; String[] indicatorList = new String[]{"HV", "IGD", "EPSILON", "SPREAD", "GD"} ; QualityIndicatorGeneration qualityIndicatorGeneration = new QualityIndicatorGeneration.Builder(experimentData) .paretoFrontDirectory("/Users/antelverde/Softw/pruebas/data/paretoFronts") .paretoFrontFiles(new String[]{"ZDT1.pf","ZDT2.pf", "ZDT3.pf", "ZDT4.pf"}) .qualityIndicatorList(indicatorList) .build() ; SetCoverageTableGeneration setCoverageTables = new SetCoverageTableGeneration.Builder(experimentData) .build() ; BoxplotGeneration boxplotGeneration = new BoxplotGeneration.Builder(experimentData) .indicatorList(indicatorList) .numberOfRows(2) .numberOfColumns(2) .build() ; WilcoxonTestTableGeneration wilcoxonTestTableGeneration = new WilcoxonTestTableGeneration.Builder(experimentData) .indicatorList(indicatorList) .build() ; Experiment2 experiment = new Experiment2.Builder(experimentData) //.addExperimentOutput(algorithmExecution) //.addExperimentOutput(paretoFrontsGeneration) //.addExperimentOutput(qualityIndicatorGeneration) //.addExperimentOutput(setCoverageTables) //.addExperimentOutput(boxplotGeneration) .addExperimentOutput(wilcoxonTestTableGeneration) .build() ; experiment.run(); }
#vulnerable code public static void main(String[] args) throws JMetalException, IOException { ExperimentData experimentData = new ExperimentData.Builder("Experiment2") .algorithmNameList(new String[]{"NSGAII", "SMPSO", "MOCell"}) .problemList(new String[]{"ZDT1", "ZDT2", "ZDT3", "ZDT4"}) .experimentBaseDirectory("/Users/antelverde/Softw/jMetal/jMetalGitHub/pruebas") .outputParetoFrontFileName("FUN") .outputParetoSetFileName("VAR") .independentRuns(20) .build() ; AlgorithmExecution algorithmExecution = new AlgorithmExecution.Builder(experimentData) .numberOfThreads(8) .paretoSetFileName("VAR") .paretoFrontFileName("FUN") //.useAlgorithmConfigurationFiles() .build() ; ParetoFrontsGeneration paretoFrontsGeneration = new ParetoFrontsGeneration.Builder(experimentData) .build() ; String[] indicatorList = new String[]{"HV", "IGD", "EPSILON", "SPREAD", "GD"} ; QualityIndicatorGeneration qualityIndicatorGeneration = new QualityIndicatorGeneration.Builder(experimentData) .paretoFrontDirectory("/Users/antelverde/Softw/pruebas/data/paretoFronts") .paretoFrontFiles(new String[]{"ZDT1.pf","ZDT2.pf", "ZDT3.pf", "ZDT4.pf"}) .qualityIndicatorList(indicatorList) .build() ; SetCoverageTables setCoverageTables = new SetCoverageTables.Builder(experimentData) .build() ; BoxplotGeneration boxplotGeneration = new BoxplotGeneration.Builder(experimentData) .indicatorList(indicatorList) .numberOfRows(2) .numberOfColumns(2) .build() ; Experiment2 experiment = new Experiment2.Builder(experimentData) .addExperimentOutput(algorithmExecution) .addExperimentOutput(paretoFrontsGeneration) .addExperimentOutput(qualityIndicatorGeneration) .addExperimentOutput(setCoverageTables) .addExperimentOutput(boxplotGeneration) .build() ; experiment.run(); } #location 46 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static public void loadRowVectorFromFile(String file, int columns, double[] row) throws JMetalException { try { BufferedReader brSrc = new BufferedReader( new InputStreamReader(new FileInputStream(ClassLoader.getSystemResource(file).getPath()))) ; //BufferedReader brSrc = new BufferedReader(new FileReader(file)); loadRowVector(brSrc, columns, row); brSrc.close(); } catch (Exception e) { JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); throw new JMetalException("Error in Benchmark.java"); } }
#vulnerable code static public void loadRowVectorFromFile(String file, int columns, double[] row) throws JMetalException { try { BufferedReader brSrc = new BufferedReader(new FileReader(file)); loadRowVector(brSrc, columns, row); brSrc.close(); } catch (Exception e) { JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); throw new JMetalException("Error in Benchmark.java"); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void initIdealPoint() throws JMException, ClassNotFoundException { for (int i = 0; i < problem_.getNumberOfObjectives(); i++) { z_[i] = 1.0e+30; indArray_[i] = new Solution(problem_); problem_.evaluate(indArray_[i]); evaluations_++; } // for for (int i = 0; i < populationSize_; i++) { updateReference(population_.get(i)); } // for }
#vulnerable code void updateOfSolutions(Solution indiv, int id, int type) { // indiv: child solution // id: the id of current subproblem // type: update solutions in - neighborhood (1) or whole population (otherwise) int size; int time; time = 0; if (type == 1) { size = parentThread_.neighborhood_[id].length; } else { size = parentThread_.population_.size(); } int[] perm = new int[size]; Utils.randomPermutation(perm, size); for (int i = 0; i < size; i++) { int k; if (type == 1) { k = parentThread_.neighborhood_[id][perm[i]]; } else { k = perm[i]; // calculate the values of objective function regarding the current subproblem } double f1, f2; f2 = fitnessFunction(indiv, parentThread_.lambda_[k]); synchronized (parentThread_) { f1 = fitnessFunction(parentThread_.population_.get(k), parentThread_.lambda_[k]); if (f2 < f1) { parentThread_.population_.replace(k, new Solution(indiv)); //population[k].indiv = indiv; time++; } } // the maximal number of solutions updated is not allowed to exceed 'limit' if (time >= parentThread_.nr_) { return; } } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static LoggedInStatus webappLogin(HttpServletRequest request, HttpServletResponse response, boolean requiresAdminRights) throws IOException { // check if there a session and a login information attached to it //HttpSession session = request.getSession(true); //LoggedIn login = getUserLoggedIn(session); /*if (login != null) { // check if this request needs admin rights and the user has them if (requiresAdminRights && (! login.isAdmin())) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return new LoggedInStatus(null, LoggedInStatus.S_UNAUTHORIZEDACCESS); } return new LoggedInStatus(login, LoggedInStatus.S_ALREADYLOGGEDIN); }*/ // since the above failed, check if there is valid login information on the request parameters String username = request.getParameter("username"); String password = request.getParameter("password"); LoggedIn login = getSuccessfulLogin(username, password); if (login != null) { // check if this request needs admin rights and the user has them if (requiresAdminRights && (! login.isAdmin())) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return new LoggedInStatus(null, LoggedInStatus.S_UNAUTHORIZEDACCESS); } // add the login information to the session HttpSession session = request.getSession(true); // force the creation of a new session if there is none session.setAttribute("login", login); return new LoggedInStatus(login, LoggedInStatus.S_VALIDLOGIN); } // both situations failed if ((username == null) && (password == null)) return new LoggedInStatus(null, LoggedInStatus.S_NOINFORMATION); else return new LoggedInStatus(null, LoggedInStatus.S_INVALIDCREDENTIALS); }
#vulnerable code public static LoggedInStatus webappLogin(HttpServletRequest request, HttpServletResponse response, boolean requiresAdminRights) throws IOException { // check if there a session and a login information attached to it HttpSession session = request.getSession(true); LoggedIn login = getUserLoggedIn(session); /*if (login != null) { // check if this request needs admin rights and the user has them if (requiresAdminRights && (! login.isAdmin())) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return new LoggedInStatus(null, LoggedInStatus.S_UNAUTHORIZEDACCESS); } return new LoggedInStatus(login, LoggedInStatus.S_ALREADYLOGGEDIN); }*/ // since the above failed, check if there is valid login information on the request parameters String username = request.getParameter("username"); String password = request.getParameter("password"); login = getSuccessfulLogin(username, password); if (login != null) { // check if this request needs admin rights and the user has them if (requiresAdminRights && (! login.isAdmin())) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return new LoggedInStatus(null, LoggedInStatus.S_UNAUTHORIZEDACCESS); } // add the login information to the session session = request.getSession(true); // force the creation of a new session if there is none session.setAttribute("login", login); return new LoggedInStatus(login, LoggedInStatus.S_VALIDLOGIN); } // both situations failed if (! request.getRequestURI().equalsIgnoreCase("/login.jsp")) response.sendRedirect("/login.jsp"); if ((username == null) && (password == null)) return new LoggedInStatus(null, LoggedInStatus.S_NOINFORMATION); else return new LoggedInStatus(null, LoggedInStatus.S_INVALIDCREDENTIALS); } #location 33 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void printLine(SearchResult result){ StringBuilder builder = new StringBuilder(); HashMap<String, Object> extraFields = result.getExtraData(); for (String tag : tagsOrder) { Object temp1 = extraFields.get(tag); final String s = (temp1 != null) ? temp1.toString().trim() : ""; if (s.length() > 0) { String temp = StringUtils.replaceEach(s, searchChars, replaceChars); builder.append('\"').append(temp).append("\";"); } else { builder.append(";"); } } log.trace("Printing Line: ", builder.toString()); nLines++; this.writter.println(builder.toString()); }
#vulnerable code private void printLine(SearchResult result){ StringBuilder builder = new StringBuilder(); HashMap<String, Object> extraFields = result.getExtraData(); for (String tag : tagsOrder) { Object temp1 = extraFields.get(tag); String temp1String = temp1.toString(); if(NumberUtils.isNumber(temp1String)){ temp1String = NumberUtils.createBigDecimal(temp1String).toPlainString(); } String s = (temp1 != null) ? StringUtils.trimToEmpty(temp1String) : ""; if (s.length() > 0) { String temp = StringUtils.replaceEach(s, searchChars, replaceChars); builder.append('\"').append(temp).append("\";"); } else { builder.append(";"); } } log.debug("Printing Line: ", builder.toString()); nLines++; this.writter.println(builder.toString()); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void printLine(SearchResult result){ StringBuilder builder = new StringBuilder(); HashMap<String, Object> extraFields = result.getExtraData(); for (String tag : tagsOrder) { Object temp1 = extraFields.get(tag); String s = (temp1 != null) ? StringUtils.trimToEmpty(temp1.toString()) : ""; if (s.length() > 0) { String temp = StringUtils.replaceEach(s, searchChars, replaceChars); builder.append(temp).append(";"); } else { builder.append(";"); } } log.debug("Printing Line: ", builder.toString()); nLines++; this.writter.println(builder.toString()); }
#vulnerable code private void printLine(SearchResult result){ StringBuilder builder = new StringBuilder(); HashMap<String, Object> extraFields = result.getExtraData(); for (String tag : tagsOrder) { Object temp1 = extraFields.get(tag); String s = StringUtils.trimToEmpty(temp1.toString()); if (s.length() > 0) { String temp = StringUtils.replaceEach(s, searchChars, replaceChars); builder.append(temp).append(";"); } else { builder.append(";"); } } log.debug("Printing Line: ", builder.toString()); nLines++; this.writter.println(builder.toString()); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void doGetExportCvs(HttpServletRequest req, HttpServletResponse resp) throws IOException{ resp.setHeader("Content-disposition","attachment; filename=QueryResultsExport.csv"); String queryString = req.getParameter("query"); String[] fields = req.getParameterValues("fields"); String[] providers = req.getParameterValues("providers"); boolean keyword = Boolean.parseBoolean(req.getParameter("keyword")); logger.debug("queryString: {}", queryString); logger.debug("fields: {}", Arrays.asList(fields)); logger.debug("keyword: {}", keyword); if(queryString == null) resp.sendError(401, "Query Parameters not found"); if(fields == null || fields.length==0) resp.sendError(402, "Fields Parameters not found"); if (!keyword) { QueryExpressionBuilder q = new QueryExpressionBuilder(queryString); queryString = q.getQueryString(); } List<String> fieldList = Arrays.asList(fields); Map<String, String> fieldsMap = new HashMap<>(); for(String f : fields){ fieldsMap.put(f, f); } ExportToCSVQueryTask task = new ExportToCSVQueryTask( fieldList, resp.getOutputStream()); if(providers == null || providers.length == 0) { PluginController.getInstance().queryAll(task, queryString, fieldsMap); } else { List<String> providersList = Arrays.asList(providers); PluginController.getInstance().query(task, providersList, queryString, fieldsMap); } task.await(); }
#vulnerable code private void doGetExportCvs(HttpServletRequest req, HttpServletResponse resp) throws IOException{ resp.setHeader("Content-disposition","attachment; filename=QueryResultsExport.csv"); String queryString = req.getParameter("query"); String[] fields = req.getParameterValues("fields"); String[] providers = req.getParameterValues("providers"); boolean keyword = Boolean.parseBoolean(req.getParameter("keyword")); System.out.println("queryString: "+ queryString); for(String field: fields) System.out.println("field: "+ field); System.out.println("keyword: "+ keyword); if(queryString == null) resp.sendError(401, "Query Parameters not found"); if(fields == null || fields.length==0) resp.sendError(402, "Fields Parameters not found"); if (!keyword) { QueryExpressionBuilder q = new QueryExpressionBuilder(queryString); queryString = q.getQueryString(); } List<String> fieldList = new ArrayList<>(fields.length); Map<String, String> fieldsMap = new HashMap<>(); for(String f : fields){ fieldList.add(f); fieldsMap.put(f, f); } ExportToCSVQueryTask task = new ExportToCSVQueryTask( fieldList, resp.getOutputStream()); if(providers == null || providers.length == 0) { PluginController.getInstance().queryAll(task, queryString, fieldsMap); } else { List<String> providersList = new ArrayList<>(); for (String f : providers) { providersList.add(f); } PluginController.getInstance().query(task, providersList, queryString, fieldsMap); } task.await(); } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void printFile(byte[] bytes) throws IOException { if (encrypt) { byte[] encryptedBytes = new byte[0]; try { cipher.init(Cipher.ENCRYPT_MODE, key); encryptedBytes = cipher.doFinal(bytes); } catch (BadPaddingException e) { logger.error("Invalid Key to decrypt users file.", e); } catch (IllegalBlockSizeException e) { logger.error("Users file \"{}\" is corrupted.", filename, e); } catch (InvalidKeyException e) { logger.error("Invalid Key to decrypt users file.", e); } printFileAux(encryptedBytes); } else { printFileAux(bytes); } }
#vulnerable code public void printFile(byte[] bytes) throws Exception { InputStream in; if(encrypt){ cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptedBytes = cipher.doFinal(bytes); in = new ByteArrayInputStream(encryptedBytes); } else in = new ByteArrayInputStream(bytes); FileOutputStream out = new FileOutputStream(filename); byte[] input = new byte[1024]; int bytesRead; while ((bytesRead = in.read(input)) != -1) { out.write(input, 0, bytesRead); out.flush(); } out.close(); in.close(); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String token = req.getHeader("Authorization"); User user = Authentication.getInstance().getUsername(token); if(user == null) { resp.sendError(401); return; } JSONObject json_resp = new JSONObject(); json_resp.put("user", user.getUsername()); json_resp.put("admin", user.isAdmin()); JSONArray rolesObj = new JSONArray(); for (Role r : user.getRoles()) { rolesObj.add(r.getName()); } json_resp.put("roles", rolesObj); //Set response content type resp.setContentType("application/json"); //Write response json_resp.write(resp.getWriter()); }
#vulnerable code @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //resp.addHeader("Access-Control-Allow-Origin", "*"); HttpSession session = req.getSession(false); LoggedIn mLoggedIn = Session.getUserLoggedIn(session); if(mLoggedIn == null){ resp.sendError(401); return; } JSONObject json_resp = new JSONObject(); json_resp.put("user", mLoggedIn.getUserName()); json_resp.put("admin", mLoggedIn.isAdmin()); User u = UsersStruct.getInstance().getUser(mLoggedIn.getUserName()); JSONArray rolesObj = new JSONArray(); for (Role r : u.getRoles()) { rolesObj.add(r.getName()); } json_resp.put("roles", rolesObj); //Set response content type resp.setContentType("application/json"); //Write response json_resp.write(resp.getWriter()); } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public JSONResource json(URI anUri) throws IOException { return doGET(anUri, new JSONResource()); }
#vulnerable code public JSONResource json(URI anUri) throws IOException, MalformedURLException { JSONObject json = JSONObject.class.cast(anUri.toURL().openConnection().getContent()); return new JSONResource(json); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public JSONResource json(URI anUri) throws IOException { return doGET(anUri, new JSONResource()); }
#vulnerable code public JSONResource json(URI anUri) throws IOException, MalformedURLException { JSONObject json = JSONObject.class.cast(anUri.toURL().openConnection().getContent()); return new JSONResource(json); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public HWDiskStore[] getDisks() { List<HWDiskStore> result; result = new ArrayList<>(); readMap.clear(); writeMap.clear(); populateReadWriteMaps(); Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_DiskDrive", "Name,Manufacturer,Model,SerialNumber,Size,Index", null, DRIVE_TYPES); for (int i = 0; i < vals.get("Name").size(); i++) { HWDiskStore ds = new HWDiskStore(); ds.setName((String) vals.get("Name").get(i)); ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim()); // Most vendors store serial # as a hex string; convert ds.setSerial(ParseUtil.hexStringToString((String) vals.get("SerialNumber").get(i))); String index = vals.get("Index").get(i).toString(); if (readMap.containsKey(index)) { ds.setReads(readMap.get(index)); } if (writeMap.containsKey(index)) { ds.setWrites(writeMap.get(index)); } // If successful this line is the desired value try { ds.setSize(Long.parseLong((String) vals.get("Size").get(i))); } catch (NumberFormatException e) { // If we failed to parse, give up // This is expected for an empty string on some drives ds.setSize(0L); } result.add(ds); } return result.toArray(new HWDiskStore[result.size()]); }
#vulnerable code @Override public HWDiskStore[] getDisks() { List<HWDiskStore> result; result = new ArrayList<>(); Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "Name,Manufacturer,Model,SerialNumber,Size", null); for (int i = 0; i < vals.get("Name").size(); i++) { HWDiskStore ds = new HWDiskStore(); ds.setName(vals.get("Name").get(i)); ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim()); // Most vendors store serial # as a hex string; convert ds.setSerial(ParseUtil.hexStringToString(vals.get("SerialNumber").get(i))); // If successful this line is the desired value try { ds.setSize(Long.parseLong(vals.get("Size").get(i))); } catch (NumberFormatException e) { // If we failed to parse, give up // This is expected for an empty string on some drives ds.setSize(0L); } result.add(ds); } return result.toArray(new HWDiskStore[result.size()]); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Display[] getDisplays() { List<Display> displays = new ArrayList<Display>(); ArrayList<String> xrandr = ExecutingCommand.runNative("xrandr --verbose"); if (xrandr != null) { boolean foundEdid = false; StringBuilder sb = new StringBuilder(); for (String s : xrandr) { if (s.contains("EDID")) { foundEdid = true; sb = new StringBuilder(); continue; } if (foundEdid) { sb.append(s.trim()); if (sb.length() >= 256) { String edidStr = sb.toString(); LOG.debug("Parsed EDID: {}", edidStr); Display display = new LinuxDisplay(ParseUtil.hexStringToByteArray(edidStr)); displays.add(display); foundEdid = false; } } } } return displays.toArray(new Display[displays.size()]); }
#vulnerable code public static Display[] getDisplays() { List<Display> displays = new ArrayList<Display>(); ArrayList<String> xrandr = ExecutingCommand.runNative("xrandr --verbose"); boolean foundEdid = false; StringBuilder sb = new StringBuilder(); for (String s : xrandr) { if (s.contains("EDID")) { foundEdid = true; sb = new StringBuilder(); continue; } if (foundEdid) { sb.append(s.trim()); if (sb.length() >= 256) { String edidStr = sb.toString(); LOG.debug("Parsed EDID: {}", edidStr); Display display = new LinuxDisplay(ParseUtil.hexStringToByteArray(edidStr)); displays.add(display); foundEdid = false; } } } return displays.toArray(new Display[displays.size()]); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Map<Integer, PerfCounterBlock> buildProcessMapFromPerfCounters(Collection<Integer> pids) { Map<Integer, PerfCounterBlock> processMap = new HashMap<>(); Pair<List<String>, Map<ProcessPerformanceProperty, List<Long>>> instanceValues = ProcessInformation .queryProcessCounters(); long now = System.currentTimeMillis(); // 1970 epoch List<String> instances = instanceValues.getA(); Map<ProcessPerformanceProperty, List<Long>> valueMap = instanceValues.getB(); List<Long> pidList = valueMap.get(ProcessPerformanceProperty.PROCESSID); List<Long> ppidList = valueMap.get(ProcessPerformanceProperty.PARENTPROCESSID); List<Long> priorityList = valueMap.get(ProcessPerformanceProperty.PRIORITY); List<Long> ioReadList = valueMap.get(ProcessPerformanceProperty.READTRANSFERCOUNT); List<Long> ioWriteList = valueMap.get(ProcessPerformanceProperty.WRITETRANSFERCOUNT); List<Long> workingSetSizeList = valueMap.get(ProcessPerformanceProperty.PRIVATEPAGECOUNT); List<Long> creationTimeList = valueMap.get(ProcessPerformanceProperty.CREATIONDATE); List<Long> pageFaultsList = valueMap.get(ProcessPerformanceProperty.PAGEFAULTSPERSEC); for (int inst = 0; inst < instances.size(); inst++) { int pid = pidList.get(inst).intValue(); if (pids == null || pids.contains(pid)) { // if creation time value is less than current millis, it's in 1970 epoch, // otherwise it's 1601 epoch and we must convert long ctime = creationTimeList.get(inst); if (ctime > now) { ctime = WinBase.FILETIME.filetimeToDate((int) (ctime >> 32), (int) (ctime & 0xffffffffL)).getTime(); } processMap.put(pid, new PerfCounterBlock(instances.get(inst), ppidList.get(inst).intValue(), priorityList.get(inst).intValue(), workingSetSizeList.get(inst), ctime, now - ctime, ioReadList.get(inst), ioWriteList.get(inst), pageFaultsList.get(inst).intValue())); } } return processMap; }
#vulnerable code public static Map<Integer, PerfCounterBlock> buildProcessMapFromPerfCounters(Collection<Integer> pids) { Map<Integer, PerfCounterBlock> processMap = new HashMap<>(); Pair<List<String>, Map<ProcessPerformanceProperty, List<Long>>> instanceValues = ProcessInformation .queryProcessCounters(); long now = System.currentTimeMillis(); // 1970 epoch List<String> instances = instanceValues.getA(); Map<ProcessPerformanceProperty, List<Long>> valueMap = instanceValues.getB(); List<Long> pidList = valueMap.get(ProcessPerformanceProperty.PROCESSID); List<Long> ppidList = valueMap.get(ProcessPerformanceProperty.PARENTPROCESSID); List<Long> priorityList = valueMap.get(ProcessPerformanceProperty.PRIORITY); List<Long> ioReadList = valueMap.get(ProcessPerformanceProperty.READTRANSFERCOUNT); List<Long> ioWriteList = valueMap.get(ProcessPerformanceProperty.WRITETRANSFERCOUNT); List<Long> workingSetSizeList = valueMap.get(ProcessPerformanceProperty.PRIVATEPAGECOUNT); List<Long> creationTimeList = valueMap.get(ProcessPerformanceProperty.CREATIONDATE); for (int inst = 0; inst < instances.size(); inst++) { int pid = pidList.get(inst).intValue(); if (pids == null || pids.contains(pid)) { // if creation time value is less than current millis, it's in 1970 epoch, // otherwise it's 1601 epoch and we must convert long ctime = creationTimeList.get(inst); if (ctime > now) { ctime = WinBase.FILETIME.filetimeToDate((int) (ctime >> 32), (int) (ctime & 0xffffffffL)).getTime(); } processMap.put(pid, new PerfCounterBlock(instances.get(inst), ppidList.get(inst).intValue(), priorityList.get(inst).intValue(), workingSetSizeList.get(inst), ctime, now - ctime, ioReadList.get(inst), ioWriteList.get(inst))); } } return processMap; } #location 4 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public float getProcessorLoad() { Scanner in = null; try { in = new Scanner(new FileReader("/proc/stat")); } catch (FileNotFoundException e) { System.err.println("Problem with: /proc/stat"); System.err.println(e.getMessage()); return -1; } in.useDelimiter("\n"); String[] result = in.next().split(" "); ArrayList<Float> loads = new ArrayList<Float>(); for (String load : result) { if (load.matches("-?\\d+(\\.\\d+)?")) { loads.add(Float.valueOf(load)); } } // ((Total-PrevTotal)-(Idle-PrevIdle))/(Total-PrevTotal) - see http://stackoverflow.com/a/23376195/4359897 float totalCpuLoad = (loads.get(0) + loads.get(2))*100 / (loads.get(0) + loads.get(2) + loads.get(3)); return FormatUtil.round(totalCpuLoad, 2); }
#vulnerable code public float getProcessorLoad() { // should be same as on Mac. Not tested. ArrayList<String> topResult = ExecutingCommand.runNative("top -l 1 -R -F -n1"); // cpu load is in [3] String[] idle = topResult.get(3).split(" "); // idle value is in [6] return 100 - Float.valueOf(idle[6].replace("%", "")); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getAvailable() { long availableMemory = 0; List<String> memInfo = null; try { memInfo = FileUtil.readFile("/proc/meminfo"); } catch (IOException e) { System.err.println("Problem with: /proc/meminfo"); System.err.println(e.getMessage()); return availableMemory; } for (String checkLine : memInfo) { // If we have MemAvailable, it trumps all. See code in // https://git.kernel.org/cgit/linux/kernel/git/torvalds/ // linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773 if (checkLine.startsWith("MemAvailable:")) { String[] memorySplit = checkLine.split("\\s+"); availableMemory = parseMeminfo(memorySplit); break; } else // Otherwise we combine MemFree + Active(file), Inactive(file), and // SReclaimable. Free+cached is no longer appropriate. MemAvailable // reduces these values using watermarks to estimate when swapping // is prevented, omitted here for simplicity (assuming 0 swap). if (checkLine.startsWith("MemFree:")) { String[] memorySplit = checkLine.split("\\s+"); availableMemory += parseMeminfo(memorySplit); } else if (checkLine.startsWith("Active(file):")) { String[] memorySplit = checkLine.split("\\s+"); availableMemory += parseMeminfo(memorySplit); } else if (checkLine.startsWith("Inactive(file):")) { String[] memorySplit = checkLine.split("\\s+"); availableMemory += parseMeminfo(memorySplit); } else if (checkLine.startsWith("SReclaimable:")) { String[] memorySplit = checkLine.split("\\s+"); availableMemory += parseMeminfo(memorySplit); } } return availableMemory; }
#vulnerable code public long getAvailable() { long returnCurrentUsageMemory = 0; Scanner in = null; try { in = new Scanner(new FileReader("/proc/meminfo")); } catch (FileNotFoundException e) { return returnCurrentUsageMemory; } in.useDelimiter("\n"); while (in.hasNext()) { String checkLine = in.next(); if (checkLine.startsWith("MemAvailable:")) { String[] memorySplit = checkLine.split("\\s+"); returnCurrentUsageMemory = parseMeminfo(memorySplit); break; } else if (checkLine.startsWith("MemFree:")) { String[] memorySplit = checkLine.split("\\s+"); returnCurrentUsageMemory += parseMeminfo(memorySplit); } else if (checkLine.startsWith("Inactive:")) { String[] memorySplit = checkLine.split("\\s+"); returnCurrentUsageMemory += parseMeminfo(memorySplit); } } in.close(); return returnCurrentUsageMemory; } #location 24 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static ArrayList<String> runNative(String cmdToRun) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRun); //p.waitFor(); } catch (IOException e) { return null; } BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line = ""; ArrayList<String> sa = new ArrayList<String>(); try { while ((line = reader.readLine()) != null) { sa.add(line); } } catch (IOException e) { return null; } p.destroy(); return sa; }
#vulnerable code public static ArrayList<String> runNative(String cmdToRun) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRun); p.waitFor(); } catch (IOException e) { return null; } catch (InterruptedException e) { return null; } BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line = ""; ArrayList<String> sa = new ArrayList<String>(); try { while ((line = reader.readLine()) != null) { sa.add(line); } } catch (IOException e) { return null; } return sa; } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public double getCpuVoltage() { // Initialize double volts = 0d; // If we couldn't get through normal WMI go directly to OHM if (this.voltIdentifierStr != null) { double[] vals = wmiGetValuesForKeys("/namespace:\\\\root\\OpenHardwareMonitor PATH Sensor", this.voltIdentifierStr, "Voltage", "Identifier,SensorType,Value"); if (vals.length > 0) { // Return the first voltage reading volts = vals[0]; } return volts; } // This branch is used the first time and all subsequent times if // successful (voltIdenifierStr == null) // Try to get value // Try to get value using initial or updated successful values int decivolts = 0; if (this.wmiVoltPath == null) { this.wmiVoltPath = "CPU"; this.wmiVoltProperty = "CurrentVoltage"; decivolts = wmiGetValue(this.wmiVoltPath, this.wmiVoltProperty); if (decivolts < 0) { this.wmiVoltPath = "/namespace:\\\\root\\cimv2 PATH Win32_Processor"; decivolts = wmiGetValue(this.wmiVoltPath, this.wmiVoltProperty); } // If the eighth bit is set, bits 0-6 contain the voltage // multiplied by 10. If the eighth bit is not set, then the bit // setting in VoltageCaps represents the voltage value. if ((decivolts & 0x80) == 0 && decivolts > 0) { this.wmiVoltProperty = "VoltageCaps"; // really a bit setting, not decivolts, test later decivolts = wmiGetValue(this.wmiVoltPath, this.wmiVoltProperty); } } else { // We've successfully read a previous time, or failed both here and // with OHM decivolts = wmiGetValue(this.wmiVoltPath, this.wmiVoltProperty); } // Convert dV to V and return result if (decivolts > 0) { if (this.wmiVoltProperty.equals("VoltageCaps")) { // decivolts are bits if ((decivolts & 0x1) > 0) { volts = 5.0; } else if ((decivolts & 0x2) > 0) { volts = 3.3; } else if ((decivolts & 0x4) > 0) { volts = 2.9; } } else { // Value from bits 0-6 volts = (decivolts & 0x7F) / 10d; } } if (volts <= 0d) { // Unable to get voltage via WMI. Future attempts will be // attempted via Open Hardware Monitor WMI if successful String[] voltIdentifiers = wmiGetStrValuesForKey("/namespace:\\\\root\\OpenHardwareMonitor PATH Hardware", "Voltage", "SensorType,Identifier"); // Look for identifier containing "cpu" for (String id : voltIdentifiers) { if (id.toLowerCase().contains("cpu")) { this.voltIdentifierStr = id; break; } } // If none contain cpu just grab the first one if (voltIdentifiers.length > 0) { this.voltIdentifierStr = voltIdentifiers[0]; } // If not null, recurse and get value via OHM if (this.voltIdentifierStr != null) { return getCpuVoltage(); } } return volts; }
#vulnerable code @Override public double getCpuVoltage() { ArrayList<String> hwInfo = ExecutingCommand.runNative("wmic cpu get CurrentVoltage"); for (String checkLine : hwInfo) { if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentvoltage")) { continue; } else { // If successful this line is in tenths of volts try { int decivolts = Integer.parseInt(checkLine.trim()); if (decivolts > 0) { return decivolts / 10d; } } catch (NumberFormatException e) { // If we failed to parse, give up } break; } } // Above query failed, try something else hwInfo = ExecutingCommand.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Processor get CurrentVoltage"); for (String checkLine : hwInfo) { if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { continue; } else { // If successful: // If the eighth bit is set, bits 0-6 contain the voltage // multiplied by 10. If the eighth bit is not set, then the bit // setting in VoltageCaps represents the voltage value. try { int decivolts = Integer.parseInt(checkLine.trim()); // Check if 8th bit (of 16 bit number) is set if ((decivolts & 0x80) > 0 && decivolts > 0) { return decivolts / 10d; } } catch (NumberFormatException e) { // If we failed to parse, give up } break; } } // Above query failed, try something else hwInfo = ExecutingCommand.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Processor get VoltageCaps"); for (String checkLine : hwInfo) { if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { continue; } else { // If successful: // Bits 0-3 of the field represent specific voltages that the // processor socket can accept. try { int voltagebits = Integer.parseInt(checkLine.trim()); // Return appropriate voltage if ((voltagebits & 0x1) > 0) { return 5.0; } else if ((voltagebits & 0x2) > 0) { return 3.3; } else if ((voltagebits & 0x4) > 0) { return 2.9; } } catch (NumberFormatException e) { // If we failed to parse, give up } break; } } return 0d; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void populateReadWriteMaps() { // Although the field names say "PerSec" this is the Raw Data from which // the associated fields are populated in the Formatted Data class, so // in fact this is the data we want Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk", "Name,DiskReadsPerSec,DiskReadBytesPerSec,DiskWritesPerSec,DiskWriteBytesPerSec,PercentDiskTime", null, READ_WRITE_TYPES); for (int i = 0; i < vals.get("Name").size(); i++) { String index = ((String) vals.get("Name").get(i)).split("\\s+")[0]; readMap.put(index, (long) vals.get("DiskReadsPerSec").get(i)); readByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskReadBytesPerSec").get(i), 0L)); writeMap.put(index, (long) vals.get("DiskWritesPerSec").get(i)); writeByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskWriteBytesPerSec").get(i), 0L)); // Units are 100-ns, divide to get ms xferTimeMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("PercentDiskTime").get(i), 0L) / 10000L); } }
#vulnerable code private void populateReadWriteMaps() { // Although the field names say "PerSec" this is the Raw Data from which // the associated fields are populated in the Formatted Data class, so // in fact this is the data we want Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk", "Name,DiskReadBytesPerSec,DiskWriteBytesPerSec", null); for (int i = 0; i < vals.get("Name").size(); i++) { String index = vals.get("Name").get(i).split("\\s+")[0]; readMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskReadBytesPerSec").get(i), 0L)); writeMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskWriteBytesPerSec").get(i), 0L)); } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean updateAttributes() { try { File ifDir = new File(String.format("/sys/class/net/%s/statistics", getName())); if (!ifDir.isDirectory()) { return false; } } catch (SecurityException e) { return false; } String ifTypePath = String.format("/sys/class/net/%s/type", getName()); String carrierPath = String.format("/sys/class/net/%s/carrier", getName()); String txBytesPath = String.format("/sys/class/net/%s/statistics/tx_bytes", getName()); String rxBytesPath = String.format("/sys/class/net/%s/statistics/rx_bytes", getName()); String txPacketsPath = String.format("/sys/class/net/%s/statistics/tx_packets", getName()); String rxPacketsPath = String.format("/sys/class/net/%s/statistics/rx_packets", getName()); String txErrorsPath = String.format("/sys/class/net/%s/statistics/tx_errors", getName()); String rxErrorsPath = String.format("/sys/class/net/%s/statistics/rx_errors", getName()); String collisionsPath = String.format("/sys/class/net/%s/statistics/collisions", getName()); String rxDropsPath = String.format("/sys/class/net/%s/statistics/rx_dropped", getName()); String ifSpeed = String.format("/sys/class/net/%s/speed", getName()); this.timeStamp = System.currentTimeMillis(); this.ifType = FileUtil.getIntFromFile(ifTypePath); this.connectorPresent = FileUtil.getIntFromFile(carrierPath) > 0; this.bytesSent = FileUtil.getUnsignedLongFromFile(txBytesPath); this.bytesRecv = FileUtil.getUnsignedLongFromFile(rxBytesPath); this.packetsSent = FileUtil.getUnsignedLongFromFile(txPacketsPath); this.packetsRecv = FileUtil.getUnsignedLongFromFile(rxPacketsPath); this.outErrors = FileUtil.getUnsignedLongFromFile(txErrorsPath); this.inErrors = FileUtil.getUnsignedLongFromFile(rxErrorsPath); this.collisions = FileUtil.getUnsignedLongFromFile(collisionsPath); this.inDrops = FileUtil.getUnsignedLongFromFile(rxDropsPath); long speedMiB = FileUtil.getUnsignedLongFromFile(ifSpeed); // speed may be -1 from file. this.speed = speedMiB < 0 ? 0 : speedMiB << 20; return true; }
#vulnerable code @Override public boolean updateAttributes() { try { File ifDir = new File(String.format("/sys/class/net/%s/statistics", getName())); if (!ifDir.isDirectory()) { return false; } } catch (SecurityException e) { return false; } String ifTypePath = String.format("/sys/class/net/%s/type", getName()); String carrierPath = String.format("/sys/class/net/%s/carrier", getName()); String txBytesPath = String.format("/sys/class/net/%s/statistics/tx_bytes", getName()); String rxBytesPath = String.format("/sys/class/net/%s/statistics/rx_bytes", getName()); String txPacketsPath = String.format("/sys/class/net/%s/statistics/tx_packets", getName()); String rxPacketsPath = String.format("/sys/class/net/%s/statistics/rx_packets", getName()); String txErrorsPath = String.format("/sys/class/net/%s/statistics/tx_errors", getName()); String rxErrorsPath = String.format("/sys/class/net/%s/statistics/rx_errors", getName()); String collisionsPath = String.format("/sys/class/net/%s/statistics/collisions", getName()); String rxDropsPath = String.format("/sys/class/net/%s/statistics/rx_dropped", getName()); String ifSpeed = String.format("/sys/class/net/%s/speed", getName()); this.timeStamp = System.currentTimeMillis(); this.ifType = FileUtil.getIntFromFile(ifTypePath); this.connectorPresent = FileUtil.getIntFromFile(carrierPath) > 0; this.bytesSent = FileUtil.getUnsignedLongFromFile(txBytesPath); this.bytesRecv = FileUtil.getUnsignedLongFromFile(rxBytesPath); this.packetsSent = FileUtil.getUnsignedLongFromFile(txPacketsPath); this.packetsRecv = FileUtil.getUnsignedLongFromFile(rxPacketsPath); this.outErrors = FileUtil.getUnsignedLongFromFile(txErrorsPath); this.inErrors = FileUtil.getUnsignedLongFromFile(rxErrorsPath); this.collisions = FileUtil.getUnsignedLongFromFile(collisionsPath); this.inDrops = FileUtil.getUnsignedLongFromFile(rxDropsPath); // speed may be negative from file. Convert to MiB. this.speed = FileUtil.getUnsignedLongFromFile(ifSpeed); this.speed = this.speed < 0 ? 0 : this.speed << 20; return true; } #location 35 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void populateReadWriteMaps() { // Although the field names say "PerSec" this is the Raw Data from which // the associated fields are populated in the Formatted Data class, so // in fact this is the data we want Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk", "Name,DiskReadsPerSec,DiskReadBytesPerSec,DiskWritesPerSec,DiskWriteBytesPerSec,PercentDiskTime", null, READ_WRITE_TYPES); for (int i = 0; i < vals.get("Name").size(); i++) { String index = ((String) vals.get("Name").get(i)).split("\\s+")[0]; readMap.put(index, (long) vals.get("DiskReadsPerSec").get(i)); readByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskReadBytesPerSec").get(i), 0L)); writeMap.put(index, (long) vals.get("DiskWritesPerSec").get(i)); writeByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskWriteBytesPerSec").get(i), 0L)); // Units are 100-ns, divide to get ms xferTimeMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("PercentDiskTime").get(i), 0L) / 10000L); } }
#vulnerable code private void populateReadWriteMaps() { // Although the field names say "PerSec" this is the Raw Data from which // the associated fields are populated in the Formatted Data class, so // in fact this is the data we want Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk", "Name,DiskReadBytesPerSec,DiskWriteBytesPerSec", null); for (int i = 0; i < vals.get("Name").size(); i++) { String index = vals.get("Name").get(i).split("\\s+")[0]; readMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskReadBytesPerSec").get(i), 0L)); writeMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskWriteBytesPerSec").get(i), 0L)); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public long[] querySystemCpuLoadTicks() { // To get load in processor group scenario, we need perfmon counters, but the // _Total instance is an average rather than total (scaled) number of ticks // which matches GetSystemTimes() results. We can just query the per-processor // ticks and add them up. Calling the get() method gains the benefit of // synchronizing this output with the memoized result of per-processor ticks as // well. long[] ticks = new long[TickType.values().length]; // Sum processor ticks long[][] procTicks = getProcessorCpuLoadTicks(); for (int i = 0; i < ticks.length; i++) { for (long[] procTick : procTicks) { ticks[i] += procTick[i]; } } return ticks; }
#vulnerable code @Override public long[] querySystemCpuLoadTicks() { long[] ticks = new long[TickType.values().length]; WinBase.FILETIME lpIdleTime = new WinBase.FILETIME(); WinBase.FILETIME lpKernelTime = new WinBase.FILETIME(); WinBase.FILETIME lpUserTime = new WinBase.FILETIME(); if (!Kernel32.INSTANCE.GetSystemTimes(lpIdleTime, lpKernelTime, lpUserTime)) { LOG.error("Failed to update system idle/kernel/user times. Error code: {}", Native.getLastError()); return ticks; } // IOwait: // Windows does not measure IOWait. // IRQ and ticks: // Percent time raw value is cumulative 100NS-ticks // Divide by 10_000 to get milliseconds Map<SystemTickCountProperty, Long> valueMap = ProcessorInformation.querySystemCounters(); ticks[TickType.IRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTINTERRUPTTIME, 0L) / 10_000L; ticks[TickType.SOFTIRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTDPCTIME, 0L) / 10_000L; ticks[TickType.IDLE.getIndex()] = lpIdleTime.toDWordLong().longValue() / 10_000L; ticks[TickType.SYSTEM.getIndex()] = lpKernelTime.toDWordLong().longValue() / 10_000L - ticks[TickType.IDLE.getIndex()]; ticks[TickType.USER.getIndex()] = lpUserTime.toDWordLong().longValue() / 10_000L; // Additional decrement to avoid double counting in the total array ticks[TickType.SYSTEM.getIndex()] -= ticks[TickType.IRQ.getIndex()] + ticks[TickType.SOFTIRQ.getIndex()]; return ticks; } #location 8 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void populatePartitionMaps() { driveToPartitionMap.clear(); partitionToLogicalDriveMap.clear(); partitionMap.clear(); // For Regexp matching DeviceIDs Matcher mAnt; Matcher mDep; // Map drives to partitions Map<String, List<Object>> partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskDriveToDiskPartition", DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES); for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) { mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i)); mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i)); if (mAnt.matches() && mDep.matches()) { MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\")) .add(mDep.group(1)); } } // Map partitions to logical disks partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDiskToPartition", DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES); for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) { mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i)); mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i)); if (mAnt.matches() && mDep.matches()) { partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\"); } } // Next, get all partitions and create objects final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition", PARTITION_STRINGS, null, PARTITION_TYPES); for (int i = 0; i < hwPartitionQueryMap.get(WmiProperty.NAME.name()).size(); i++) { String deviceID = (String) hwPartitionQueryMap.get(WmiProperty.DEVICEID.name()).get(i); String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, ""); String uuid = ""; if (!logicalDrive.isEmpty()) { // Get matching volume for UUID char[] volumeChr = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE); uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), ""); } partitionMap .put(deviceID, new HWPartition( (String) hwPartitionQueryMap .get(WmiProperty.NAME.name()).get( i), (String) hwPartitionQueryMap.get(WmiProperty.TYPE.name()).get(i), (String) hwPartitionQueryMap.get(WmiProperty.DESCRIPTION.name()).get(i), uuid, (Long) hwPartitionQueryMap.get(WmiProperty.SIZE.name()).get(i), ((Long) hwPartitionQueryMap.get(WmiProperty.DISKINDEX.name()).get(i)).intValue(), ((Long) hwPartitionQueryMap.get(WmiProperty.INDEX.name()).get(i)).intValue(), logicalDrive)); } }
#vulnerable code private void populatePartitionMaps() { driveToPartitionMap.clear(); partitionToLogicalDriveMap.clear(); partitionMap.clear(); // For Regexp matching DeviceIDs Matcher mAnt; Matcher mDep; // Map drives to partitions Map<String, List<String>> partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDriveToDiskPartition", DRIVE_TO_PARTITION_PROPERTIES, null); for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) { mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i)); mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i)); if (mAnt.matches() && mDep.matches()) { MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\")) .add(mDep.group(1)); } } // Map partitions to logical disks partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_LogicalDiskToPartition", LOGICAL_DISK_TO_PARTITION_PROPERTIES, null); for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) { mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i)); mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i)); if (mAnt.matches() && mDep.matches()) { partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\"); } } // Next, get all partitions and create objects final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition", PARTITION_PROPERTIES, null, PARTITION_TYPES); for (int i = 0; i < hwPartitionQueryMap.get(NAME_PROPERTY).size(); i++) { String deviceID = (String) hwPartitionQueryMap.get(DEVICE_ID_PROPERTY).get(i); String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, ""); String uuid = ""; if (!logicalDrive.isEmpty()) { // Get matching volume for UUID char[] volumeChr = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE); uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), ""); } partitionMap.put(deviceID, new HWPartition((String) hwPartitionQueryMap.get(NAME_PROPERTY).get(i), (String) hwPartitionQueryMap.get(TYPE_PROPERTY).get(i), (String) hwPartitionQueryMap.get(DESCRIPTION_PROPERTY).get(i), uuid, ParseUtil.parseLongOrDefault((String) hwPartitionQueryMap.get(SIZE_PROPERTY).get(i), 0L), ((Long) hwPartitionQueryMap.get(DISK_INDEX_PROPERTY).get(i)).intValue(), ((Long) hwPartitionQueryMap.get(INDEX_PROPERTY).get(i)).intValue(), logicalDrive)); } } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<OSFileStore> getWmiVolumes() { Map<String, List<Object>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES); for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) { free = (Long) drives.get(FREESPACE_PROPERTY).get(i); total = (Long) drives.get(SIZE_PROPERTY).get(i); String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i); String name = (String) drives.get(NAME_PROPERTY).get(i); long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name), (String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total)); } return fs; }
#vulnerable code private List<OSFileStore> getWmiVolumes() { Map<String, List<String>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk", "Name,Description,ProviderName,FileSystem,Freespace,Size", null); for (int i = 0; i < drives.get("Name").size(); i++) { free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L); total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L); String description = drives.get("Description").get(i); long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType", "WHERE Name = '" + drives.get("Name").get(i) + "'"); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = drives.get("ProviderName").get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume, drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)), drives.get("FileSystem").get(i), "", free, total)); } return fs; } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void removeAllCounters() { // Remove all counters from counterHandle map for (HANDLEByReference href : counterHandleMap.values()) { PerfDataUtil.removeCounter(href); } counterHandleMap.clear(); // Remove query if (this.queryHandle != null) { PerfDataUtil.closeQuery(this.queryHandle); } this.queryHandle = null; }
#vulnerable code public void removeAllCounters() { // Remove all counter handles for (HANDLEByReference href : counterHandleMap.values()) { PerfDataUtil.removeCounter(href); } counterHandleMap.clear(); // Remove all queries for (HANDLEByReference query : queryHandleMap.values()) { PerfDataUtil.closeQuery(query); } queryHandleMap.clear(); queryCounterMap.clear(); } #location 9 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void populatePartitionMaps() { driveToPartitionMap.clear(); partitionToLogicalDriveMap.clear(); partitionMap.clear(); // For Regexp matching DeviceIDs Matcher mAnt; Matcher mDep; // Map drives to partitions Map<String, List<Object>> partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskDriveToDiskPartition", DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES); for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) { mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i)); mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i)); if (mAnt.matches() && mDep.matches()) { MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\")) .add(mDep.group(1)); } } // Map partitions to logical disks partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDiskToPartition", DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES); for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) { mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i)); mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i)); if (mAnt.matches() && mDep.matches()) { partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\"); } } // Next, get all partitions and create objects final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition", PARTITION_STRINGS, null, PARTITION_TYPES); for (int i = 0; i < hwPartitionQueryMap.get(WmiProperty.NAME.name()).size(); i++) { String deviceID = (String) hwPartitionQueryMap.get(WmiProperty.DEVICEID.name()).get(i); String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, ""); String uuid = ""; if (!logicalDrive.isEmpty()) { // Get matching volume for UUID char[] volumeChr = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE); uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), ""); } partitionMap .put(deviceID, new HWPartition( (String) hwPartitionQueryMap .get(WmiProperty.NAME.name()).get( i), (String) hwPartitionQueryMap.get(WmiProperty.TYPE.name()).get(i), (String) hwPartitionQueryMap.get(WmiProperty.DESCRIPTION.name()).get(i), uuid, (Long) hwPartitionQueryMap.get(WmiProperty.SIZE.name()).get(i), ((Long) hwPartitionQueryMap.get(WmiProperty.DISKINDEX.name()).get(i)).intValue(), ((Long) hwPartitionQueryMap.get(WmiProperty.INDEX.name()).get(i)).intValue(), logicalDrive)); } }
#vulnerable code private void populatePartitionMaps() { driveToPartitionMap.clear(); partitionToLogicalDriveMap.clear(); partitionMap.clear(); // For Regexp matching DeviceIDs Matcher mAnt; Matcher mDep; // Map drives to partitions Map<String, List<String>> partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDriveToDiskPartition", DRIVE_TO_PARTITION_PROPERTIES, null); for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) { mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i)); mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i)); if (mAnt.matches() && mDep.matches()) { MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\")) .add(mDep.group(1)); } } // Map partitions to logical disks partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_LogicalDiskToPartition", LOGICAL_DISK_TO_PARTITION_PROPERTIES, null); for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) { mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i)); mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i)); if (mAnt.matches() && mDep.matches()) { partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\"); } } // Next, get all partitions and create objects final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition", PARTITION_PROPERTIES, null, PARTITION_TYPES); for (int i = 0; i < hwPartitionQueryMap.get(NAME_PROPERTY).size(); i++) { String deviceID = (String) hwPartitionQueryMap.get(DEVICE_ID_PROPERTY).get(i); String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, ""); String uuid = ""; if (!logicalDrive.isEmpty()) { // Get matching volume for UUID char[] volumeChr = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE); uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), ""); } partitionMap.put(deviceID, new HWPartition((String) hwPartitionQueryMap.get(NAME_PROPERTY).get(i), (String) hwPartitionQueryMap.get(TYPE_PROPERTY).get(i), (String) hwPartitionQueryMap.get(DESCRIPTION_PROPERTY).get(i), uuid, ParseUtil.parseLongOrDefault((String) hwPartitionQueryMap.get(SIZE_PROPERTY).get(i), 0L), ((Long) hwPartitionQueryMap.get(DISK_INDEX_PROPERTY).get(i)).intValue(), ((Long) hwPartitionQueryMap.get(INDEX_PROPERTY).get(i)).intValue(), logicalDrive)); } } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public long[] querySystemCpuLoadTicks() { // To get load in processor group scenario, we need perfmon counters, but the // _Total instance is an average rather than total (scaled) number of ticks // which matches GetSystemTimes() results. We can just query the per-processor // ticks and add them up. Calling the get() method gains the benefit of // synchronizing this output with the memoized result of per-processor ticks as // well. long[] ticks = new long[TickType.values().length]; // Sum processor ticks long[][] procTicks = getProcessorCpuLoadTicks(); for (int i = 0; i < ticks.length; i++) { for (long[] procTick : procTicks) { ticks[i] += procTick[i]; } } return ticks; }
#vulnerable code @Override public long[] querySystemCpuLoadTicks() { long[] ticks = new long[TickType.values().length]; WinBase.FILETIME lpIdleTime = new WinBase.FILETIME(); WinBase.FILETIME lpKernelTime = new WinBase.FILETIME(); WinBase.FILETIME lpUserTime = new WinBase.FILETIME(); if (!Kernel32.INSTANCE.GetSystemTimes(lpIdleTime, lpKernelTime, lpUserTime)) { LOG.error("Failed to update system idle/kernel/user times. Error code: {}", Native.getLastError()); return ticks; } // IOwait: // Windows does not measure IOWait. // IRQ and ticks: // Percent time raw value is cumulative 100NS-ticks // Divide by 10_000 to get milliseconds Map<SystemTickCountProperty, Long> valueMap = ProcessorInformation.querySystemCounters(); ticks[TickType.IRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTINTERRUPTTIME, 0L) / 10_000L; ticks[TickType.SOFTIRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTDPCTIME, 0L) / 10_000L; ticks[TickType.IDLE.getIndex()] = lpIdleTime.toDWordLong().longValue() / 10_000L; ticks[TickType.SYSTEM.getIndex()] = lpKernelTime.toDWordLong().longValue() / 10_000L - ticks[TickType.IDLE.getIndex()]; ticks[TickType.USER.getIndex()] = lpUserTime.toDWordLong().longValue() / 10_000L; // Additional decrement to avoid double counting in the total array ticks[TickType.SYSTEM.getIndex()] -= ticks[TickType.IRQ.getIndex()] + ticks[TickType.SOFTIRQ.getIndex()]; return ticks; } #location 7 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public int[] getFanSpeeds() { // Initialize int[] fanSpeeds = new int[1]; // If we couldn't get through normal WMI go directly to OHM if (!this.fanSpeedWMI) { double[] vals = wmiGetValuesForKeys("/namespace:\\\\root\\OpenHardwareMonitor PATH Sensor", null, "Fan", "Parent,SensorType,Value"); if (vals.length > 0) { fanSpeeds = new int[vals.length]; for (int i = 0; i < vals.length; i++) { fanSpeeds[i] = (int) vals[i]; } } return fanSpeeds; } // This branch is used the first time and all subsequent times if // successful (fanSpeedWMI == true) // Try to get value int rpm = wmiGetValue("/namespace:\\\\root\\cimv2 PATH Win32_Fan", "DesiredSpeed"); // Set in array and return if (rpm > 0) { fanSpeeds[0] = rpm; } else { // Fail, switch to OHM this.fanSpeedWMI = false; return getFanSpeeds(); } return fanSpeeds; }
#vulnerable code @Override public int[] getFanSpeeds() { int[] fanSpeeds = new int[1]; ArrayList<String> hwInfo = ExecutingCommand .runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Fan get DesiredSpeed"); for (String checkLine : hwInfo) { if (checkLine.length() == 0 || checkLine.toLowerCase().contains("desiredspeed")) { continue; } else { // If successful try { int rpm = Integer.parseInt(checkLine.trim()); // Check if 8th bit (of 16 bit number) is set if (rpm > 0) { fanSpeeds[0] = rpm; return fanSpeeds; } } catch (NumberFormatException e) { // If we failed to parse, give up } break; } } return fanSpeeds; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static UsbDevice[] getUsbDevices() { // Start by collecting information for all PNP devices. While in theory // these could be individually queried with a WHERE clause, grabbing // them all up front incurs minimal memory overhead in exchange for // faster access later // Clear maps nameMap.clear(); vendorMap.clear(); serialMap.clear(); // Query Win32_PnPEntity to populate the maps Map<String, List<String>> usbMap = WmiUtil.selectStringsFrom(null, "Win32_PnPEntity", "Name,Manufacturer,PnPDeviceID", null); for (int i = 0; i < usbMap.get("Name").size(); i++) { String pnpDeviceID = usbMap.get("PnPDeviceID").get(i); nameMap.put(pnpDeviceID, usbMap.get("Name").get(i)); if (usbMap.get("Manufacturer").get(i).length() > 0) { vendorMap.put(pnpDeviceID, usbMap.get("Manufacturer").get(i)); } String serialNumber = ""; // PNPDeviceID: USB\VID_203A&PID_FFF9&MI_00\6&18C4CF61&0&0000 // Split by \ to get bus type (USB), VendorID/ProductID, other info // As a temporary hack for a serial number, use last \-split field // using 2nd &-split field if 4 fields String[] idSplit = pnpDeviceID.split("\\\\"); if (idSplit.length > 2) { idSplit = idSplit[2].split("&"); if (idSplit.length > 3) { serialNumber = idSplit[1]; } } if (serialNumber.length() > 0) { serialMap.put(pnpDeviceID, serialNumber); } } // Disk drives or other physical media have a better way of getting // serial number. Grab these and overwrite the temporary serial number // assigned above if necessary usbMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "PNPDeviceID,SerialNumber", null); for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { serialMap.put(usbMap.get("PNPDeviceID").get(i), ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); } usbMap = WmiUtil.selectStringsFrom(null, "Win32_PhysicalMedia", "PNPDeviceID,SerialNumber", null); for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { serialMap.put(usbMap.get("PNPDeviceID").get(i), ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); } // Some USB Devices are hubs to which other devices connect. Knowing // which ones are hubs will help later when walking the device tree usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBHub", "PNPDeviceID", null); List<String> usbHubs = usbMap.get("PNPDeviceID"); // Now build the hub map linking USB devices with their parent hub. // At the top of the device tree are USB Controllers. All USB hubs and // devices descend from these. Because this query returns pointers it's // just not practical to try to query via COM so we use a command line // in order to get USB devices in a text format ArrayList<String> links = ExecutingCommand .runNative("wmic path Win32_USBControllerDevice GET Antecedent,Dependent"); // This iteration actually walks the device tree in order so while the // antecedent of all USB devices is its controller, we know that if a // device is not a hub that the last hub listed is its parent // Devices with PNPDeviceID containing "ROOTHUB" are special and will be // parents of the next item(s) // This won't id chained hubs (other than the root hub) but is a quick // hack rather than walking the entire device tree using the SetupDI API // and good enough since exactly how a USB device is connected is // theoretically transparent to the user hubMap.clear(); String currentHub = null; String rootHub = null; for (String s : links) { String[] split = s.split("\\s+"); if (split.length < 2) { continue; } String antecedent = getId(split[0]); String dependent = getId(split[1]); // Ensure initial defaults are sane if something goes wrong if (currentHub == null || rootHub == null) { currentHub = antecedent; rootHub = antecedent; } String parent; if (dependent.contains("ROOT_HUB")) { // This is a root hub, assign controller as parent; parent = antecedent; rootHub = dependent; currentHub = dependent; } else if (usbHubs.contains(dependent)) { // This is a hub, assign parent as root hub if (rootHub == null) { rootHub = antecedent; } parent = rootHub; currentHub = dependent; } else { // This is not a hub, assign parent as previous hub if (currentHub == null) { currentHub = antecedent; } parent = currentHub; } // Finally add the parent/child linkage to the map if (!hubMap.containsKey(parent)) { hubMap.put(parent, new ArrayList<String>()); } hubMap.get(parent).add(dependent); } // Finally we simply get the device IDs of the USB Controllers. These // will recurse downward to devices as needed usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBController", "PNPDeviceID", null); List<UsbDevice> controllerDevices = new ArrayList<UsbDevice>(); for (String controllerDeviceID : usbMap.get("PNPDeviceID")) { controllerDevices.add(getDeviceAndChildren(controllerDeviceID)); } return controllerDevices.toArray(new UsbDevice[controllerDevices.size()]); }
#vulnerable code public static UsbDevice[] getUsbDevices() { List<UsbDevice> usbDevices = new ArrayList<UsbDevice>(); // Store map of pnpID to name, Manufacturer, serial Map<String, String> nameMap = new HashMap<>(); Map<String, String> vendorMap = new HashMap<>(); Map<String, String> serialMap = new HashMap<>(); Map<String, List<String>> usbMap = WmiUtil.selectStringsFrom(null, "Win32_PnPEntity", "Name,Manufacturer,PnPDeviceID", null); for (int i = 0; i < usbMap.get("Name").size(); i++) { String pnpDeviceID = usbMap.get("PnPDeviceID").get(i); nameMap.put(pnpDeviceID, usbMap.get("Name").get(i)); if (usbMap.get("Manufacturer").get(i).length() > 0) { vendorMap.put(pnpDeviceID, usbMap.get("Manufacturer").get(i)); } String serialNumber = ""; // Format: USB\VID_203A&PID_FFF9&MI_00\6&18C4CF61&0&0000 // Split by \ to get bus type (USB), VendorID/ProductID/Model // Last field contains Serial # in hex as 2nd split by // ampersands String[] idSplit = pnpDeviceID.split("\\\\"); if (idSplit.length > 2) { idSplit = idSplit[2].split("&"); if (idSplit.length > 3) { serialNumber = idSplit[1]; } } if (serialNumber.length() > 0) { serialMap.put(pnpDeviceID, serialNumber); } } // Get serial # of disk drives (may overwrite previous, that's OK) usbMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "PNPDeviceID,SerialNumber", null); for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { serialMap.put(usbMap.get("PNPDeviceID").get(i), ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); } usbMap = WmiUtil.selectStringsFrom(null, "Win32_PhysicalMedia", "PNPDeviceID,SerialNumber", null); for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { serialMap.put(usbMap.get("PNPDeviceID").get(i), ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); } // Finally, prepare final list for output // Start with controllers usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBController", "PNPDeviceID", null); List<String> pnpDeviceIDs = usbMap.get("PNPDeviceID"); // Add any hubs usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBHub", "PNPDeviceID", null); pnpDeviceIDs.addAll(usbMap.get("PNPDeviceID")); // Add any stray USB devices in the list for (String pnpDeviceID : nameMap.keySet().stream().sorted().collect(Collectors.toList())) { if (pnpDeviceID.startsWith("USB\\") && !pnpDeviceIDs.contains(pnpDeviceID)) { pnpDeviceIDs.add(pnpDeviceID); } } for (String pnpDeviceID : pnpDeviceIDs) { usbDevices.add( new WindowsUsbDevice(nameMap.getOrDefault(pnpDeviceID, ""), vendorMap.getOrDefault(pnpDeviceID, ""), serialMap.getOrDefault(pnpDeviceID, ""), new WindowsUsbDevice[0])); } return usbDevices.toArray(new UsbDevice[usbDevices.size()]); } #location 52 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { // Enumerator will be released by calling method so no need to // release it here. return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { // WMI Longs will return as strings case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; // WMI Uint32s will return as longs case UINT32: // WinDef.LONG TODO improve in JNA 4.3 case UINT64: values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property) .add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; case BOOLEAN: // WinDef.BOOL TODO improve in JNA 4.3 values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.boolVal.booleanValue()); break; default: // Should never get here! If you get this exception you've // added something to the enum without adding it here. Tsk. throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); } clsObj.Release(); } }
#vulnerable code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { // Enumerator will be released by calling method so no need to // release it here. return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { // WMI Longs will return as strings case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; // WMI Uint32s will return as longs case UINT32: // WinDef.LONG TODO improve in JNA 4.3 values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property) .add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; case BOOLEAN: // WinDef.BOOL TODO improve in JNA 4.3 values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.boolVal.booleanValue()); break; default: // Should never get here! If you get this exception you've // added something to the enum without adding it here. Tsk. throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); } clsObj.Release(); } } #location 31 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public long getSwapUsed() { PdhFmtCounterValue phPagefileCounterValue = new PdhFmtCounterValue(); int ret = Pdh.INSTANCE.PdhGetFormattedCounterValue(pPagefile.getValue(), Pdh.PDH_FMT_LARGE | Pdh.PDH_FMT_1000, null, phPagefileCounterValue); if (ret != 0) { LOG.warn("Failed to get Pagefile % Usage counter. Error code: {}", String.format("0x%08X", ret)); return 0L; } // Returns results in 1000's of percent, e.g. 5% is 5000 // Multiply by page file size and Divide by 100 * 1000 // Putting division at end avoids need to cast division to double return getSwapTotal() * phPagefileCounterValue.value.largeValue / 100000; }
#vulnerable code @Override public long getSwapUsed() { long total; long available; if (!Kernel32.INSTANCE.GlobalMemoryStatusEx(this._memory)) { LOG.error("Failed to Initialize MemoryStatusEx. Error code: {}", Kernel32.INSTANCE.GetLastError()); this._memory = null; return 0L; } total = this.getSwapTotal(); available = this._memory.ullAvailPageFile.longValue() - this._memory.ullAvailPhys.longValue(); return total - available; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<OSFileStore> getWmiVolumes() { Map<String, List<Object>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES); for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) { free = (Long) drives.get(FREESPACE_PROPERTY).get(i); total = (Long) drives.get(SIZE_PROPERTY).get(i); String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i); String name = (String) drives.get(NAME_PROPERTY).get(i); long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name), (String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total)); } return fs; }
#vulnerable code private List<OSFileStore> getWmiVolumes() { Map<String, List<String>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk", "Name,Description,ProviderName,FileSystem,Freespace,Size", null); for (int i = 0; i < drives.get("Name").size(); i++) { free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L); total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L); String description = drives.get("Description").get(i); long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType", "WHERE Name = '" + drives.get("Name").get(i) + "'"); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = drives.get("ProviderName").get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume, drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)), drives.get("FileSystem").get(i), "", free, total)); } return fs; } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public HWDiskStore[] getDisks() { List<HWDiskStore> result; result = new ArrayList<>(); readMap.clear(); writeMap.clear(); populateReadWriteMaps(); Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_DiskDrive", "Name,Manufacturer,Model,SerialNumber,Size,Index", null, DRIVE_TYPES); for (int i = 0; i < vals.get("Name").size(); i++) { HWDiskStore ds = new HWDiskStore(); ds.setName((String) vals.get("Name").get(i)); ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim()); // Most vendors store serial # as a hex string; convert ds.setSerial(ParseUtil.hexStringToString((String) vals.get("SerialNumber").get(i))); String index = vals.get("Index").get(i).toString(); if (readMap.containsKey(index)) { ds.setReads(readMap.get(index)); } if (writeMap.containsKey(index)) { ds.setWrites(writeMap.get(index)); } // If successful this line is the desired value try { ds.setSize(Long.parseLong((String) vals.get("Size").get(i))); } catch (NumberFormatException e) { // If we failed to parse, give up // This is expected for an empty string on some drives ds.setSize(0L); } result.add(ds); } return result.toArray(new HWDiskStore[result.size()]); }
#vulnerable code @Override public HWDiskStore[] getDisks() { List<HWDiskStore> result; result = new ArrayList<>(); Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "Name,Manufacturer,Model,SerialNumber,Size", null); for (int i = 0; i < vals.get("Name").size(); i++) { HWDiskStore ds = new HWDiskStore(); ds.setName(vals.get("Name").get(i)); ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim()); // Most vendors store serial # as a hex string; convert ds.setSerial(ParseUtil.hexStringToString(vals.get("SerialNumber").get(i))); // If successful this line is the desired value try { ds.setSize(Long.parseLong(vals.get("Size").get(i))); } catch (NumberFormatException e) { // If we failed to parse, give up // This is expected for an empty string on some drives ds.setSize(0L); } result.add(ds); } return result.toArray(new HWDiskStore[result.size()]); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public HWDiskStore[] getDisks() { List<HWDiskStore> result; result = new ArrayList<>(); readMap.clear(); writeMap.clear(); populateReadWriteMaps(); Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_DiskDrive", "Name,Manufacturer,Model,SerialNumber,Size,Index", null, DRIVE_TYPES); for (int i = 0; i < vals.get("Name").size(); i++) { HWDiskStore ds = new HWDiskStore(); ds.setName((String) vals.get("Name").get(i)); ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim()); // Most vendors store serial # as a hex string; convert ds.setSerial(ParseUtil.hexStringToString((String) vals.get("SerialNumber").get(i))); String index = vals.get("Index").get(i).toString(); if (readMap.containsKey(index)) { ds.setReads(readMap.get(index)); } if (writeMap.containsKey(index)) { ds.setWrites(writeMap.get(index)); } // If successful this line is the desired value try { ds.setSize(Long.parseLong((String) vals.get("Size").get(i))); } catch (NumberFormatException e) { // If we failed to parse, give up // This is expected for an empty string on some drives ds.setSize(0L); } result.add(ds); } return result.toArray(new HWDiskStore[result.size()]); }
#vulnerable code @Override public HWDiskStore[] getDisks() { List<HWDiskStore> result; result = new ArrayList<>(); Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "Name,Manufacturer,Model,SerialNumber,Size", null); for (int i = 0; i < vals.get("Name").size(); i++) { HWDiskStore ds = new HWDiskStore(); ds.setName(vals.get("Name").get(i)); ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim()); // Most vendors store serial # as a hex string; convert ds.setSerial(ParseUtil.hexStringToString(vals.get("SerialNumber").get(i))); // If successful this line is the desired value try { ds.setSize(Long.parseLong(vals.get("Size").get(i))); } catch (NumberFormatException e) { // If we failed to parse, give up // This is expected for an empty string on some drives ds.setSize(0L); } result.add(ds); } return result.toArray(new HWDiskStore[result.size()]); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public long[] querySystemCpuLoadTicks() { // convert the Linux Jiffies to Milliseconds. long[] ticks = CpuStat.getSystemCpuLoadTicks(); // In rare cases, /proc/stat reading fails. If so, try again. if (LongStream.of(ticks).sum() == 0) { ticks = CpuStat.getSystemCpuLoadTicks(); } long hz = LinuxOperatingSystem.getHz(); for (int i = 0; i < ticks.length; i++) { ticks[i] = ticks[i] * 1000L / hz; } return ticks; }
#vulnerable code @Override public long[] querySystemCpuLoadTicks() { // convert the Linux Jiffies to Milliseconds. long[] ticks = CpuStat.getSystemCpuLoadTicks(); long hz = LinuxOperatingSystem.getHz(); for (int i = 0; i < ticks.length; i++) { ticks[i] = ticks[i] * 1000L / hz; } return ticks; } #location 4 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void removeAllCounters() { // Remove all counters from counterHandle map for (HANDLEByReference href : counterHandleMap.values()) { PerfDataUtil.removeCounter(href); } counterHandleMap.clear(); // Remove query if (this.queryHandle != null) { PerfDataUtil.closeQuery(this.queryHandle); } this.queryHandle = null; }
#vulnerable code public void removeAllCounters() { // Remove all counter handles for (HANDLEByReference href : counterHandleMap.values()) { PerfDataUtil.removeCounter(href); } counterHandleMap.clear(); // Remove all queries for (HANDLEByReference query : queryHandleMap.values()) { PerfDataUtil.closeQuery(query); } queryHandleMap.clear(); queryCounterMap.clear(); } #location 4 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static String getCardCodec(File cardDir) { String cardCodec = ""; File[] cardFiles = cardDir.listFiles(); if (cardFiles == null) { return ""; } for (File file : cardDir.listFiles()) { if (file.getName().startsWith("codec")) { cardCodec = FileUtil.getKeyValueMapFromFile(file.getPath(), ":").get("Codec"); } } return cardCodec; }
#vulnerable code private static String getCardCodec(File cardDir) { String cardCodec = ""; for (File file : cardDir.listFiles()) { if (file.getName().startsWith("codec")) { cardCodec = FileUtil.getKeyValueMapFromFile(file.getPath(), ":").get("Codec"); } } return cardCodec; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String getSystemSerialNumber() { if (this.cpuSerialNumber == null) { int service = 0; MachPort masterPort = new MachPort(); int result = IOKit.INSTANCE.IOMasterPort(0, masterPort); if (result != 0) { LOG.error(String.format("Error: IOMasterPort() = %08x", result)); this.cpuSerialNumber = "unknown"; } else { service = IOKit.INSTANCE.IOServiceGetMatchingService(masterPort.getValue(), IOKit.INSTANCE.IOServiceMatching("IOPlatformExpertDevice")); if (service == 0) { this.cpuSerialNumber = "unknown"; } else { // Fetch the serial number CFTypeRef serialNumberAsCFString = IOKit.INSTANCE.IORegistryEntryCreateCFProperty(service, CFStringRef.toCFString("IOPlatformSerialNumber"), CoreFoundation.INSTANCE.CFAllocatorGetDefault(), 0); IOKit.INSTANCE.IOObjectRelease(service); this.cpuSerialNumber = CfUtil.cfPointerToString(serialNumberAsCFString.getPointer()); } } } return this.cpuSerialNumber; }
#vulnerable code @Override public String getSystemSerialNumber() { if (this.cpuSerialNumber == null) { ArrayList<String> hwInfo = ExecutingCommand.runNative("system_profiler SPHardwareDataType"); // Mavericks and later for (String checkLine : hwInfo) { if (checkLine.contains("Serial Number (system)")) { String[] snSplit = checkLine.split("\\s+"); this.cpuSerialNumber = snSplit[snSplit.length - 1]; break; } } // Panther and later if (this.cpuSerialNumber == null) { for (String checkLine : hwInfo) { if (checkLine.contains("r (system)")) { String[] snSplit = checkLine.split("\\s+"); this.cpuSerialNumber = snSplit[snSplit.length - 1]; break; } } } if (this.cpuSerialNumber == null) { this.cpuSerialNumber = "unknown"; } } return this.cpuSerialNumber; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static ArrayList<String> runNative(String cmdToRun) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRun); } catch (IOException e) { LOG.trace("", e); return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; ArrayList<String> sa = new ArrayList<>(); try { while ((line = reader.readLine()) != null) { sa.add(line); } p.waitFor(); } catch (InterruptedException e) { LOG.trace("", e); return null; } catch (IOException e) { LOG.trace("", e); return null; } return sa; }
#vulnerable code public static ArrayList<String> runNative(String cmdToRun) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRun); p.waitFor(); } catch (IOException e) { LOG.trace("", e); return null; } catch (InterruptedException e) { LOG.trace("", e); return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; ArrayList<String> sa = new ArrayList<>(); try { while ((line = reader.readLine()) != null) { sa.add(line); } } catch (IOException e) { LOG.trace("", e); return null; } return sa; } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { // Enumerator will be released by calling method so no need to // release it here. return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { // WMI Longs will return as strings case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; // WMI Uint32s will return as longs case UINT32: // WinDef.LONG TODO improve in JNA 4.3 values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; default: // Should never get here! If you get this exception you've // added something to the enum without adding it here. Tsk. throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); } clsObj.Release(); } }
#vulnerable code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { enumerator.Release(); return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { // WMI Longs will return as strings case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; // WMI Uint32s will return as longs case UINT32: // WinDef.LONG TODO improve in JNA 4.3 values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; default: // Should never get here! If you get this exception you've // added something to the enum without adding it here. Tsk. throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); } clsObj.Release(); } } #location 30 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static <T extends Enum<T>> Map<T, Long> queryValues(Class<T> propertyEnum, String perfObject, String perfWmiClass) { // Check without locking for performance if (!failedQueryCache.contains(perfObject)) { failedQueryCacheLock.lock(); try { // Double check lock if (!failedQueryCache.contains(perfObject)) { Map<T, Long> valueMap = queryValuesFromPDH(propertyEnum, perfObject); if (!valueMap.isEmpty()) { return valueMap; } // If we are here, query failed LOG.warn("Disabling further attempts to query {}.", perfObject); failedQueryCache.add(perfObject); } } finally { failedQueryCacheLock.unlock(); } } return queryValuesFromWMI(propertyEnum, perfWmiClass); }
#vulnerable code public static <T extends Enum<T>> Map<T, Long> queryValues(Class<T> propertyEnum, String perfObject, String perfWmiClass) { Map<T, Long> valueMap = queryValuesFromPDH(propertyEnum, perfObject); if (valueMap.isEmpty()) { return queryValuesFromWMI(propertyEnum, perfWmiClass); } return valueMap; } #location 3 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<OSFileStore> getWmiVolumes() { Map<String, List<Object>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES); for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) { free = (Long) drives.get(FREESPACE_PROPERTY).get(i); total = (Long) drives.get(SIZE_PROPERTY).get(i); String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i); String name = (String) drives.get(NAME_PROPERTY).get(i); long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name), (String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total)); } return fs; }
#vulnerable code private List<OSFileStore> getWmiVolumes() { Map<String, List<String>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk", "Name,Description,ProviderName,FileSystem,Freespace,Size", null); for (int i = 0; i < drives.get("Name").size(); i++) { free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L); total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L); String description = drives.get("Description").get(i); long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType", "WHERE Name = '" + drives.get("Name").get(i) + "'"); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = drives.get("ProviderName").get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume, drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)), drives.get("FileSystem").get(i), "", free, total)); } return fs; } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public HWDiskStore[] getDisks() { List<HWDiskStore> result; result = new ArrayList<>(); readMap.clear(); writeMap.clear(); populateReadWriteMaps(); Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_DiskDrive", "Name,Manufacturer,Model,SerialNumber,Size,Index", null, DRIVE_TYPES); for (int i = 0; i < vals.get("Name").size(); i++) { HWDiskStore ds = new HWDiskStore(); ds.setName((String) vals.get("Name").get(i)); ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim()); // Most vendors store serial # as a hex string; convert ds.setSerial(ParseUtil.hexStringToString((String) vals.get("SerialNumber").get(i))); String index = vals.get("Index").get(i).toString(); if (readMap.containsKey(index)) { ds.setReads(readMap.get(index)); } if (writeMap.containsKey(index)) { ds.setWrites(writeMap.get(index)); } // If successful this line is the desired value try { ds.setSize(Long.parseLong((String) vals.get("Size").get(i))); } catch (NumberFormatException e) { // If we failed to parse, give up // This is expected for an empty string on some drives ds.setSize(0L); } result.add(ds); } return result.toArray(new HWDiskStore[result.size()]); }
#vulnerable code @Override public HWDiskStore[] getDisks() { List<HWDiskStore> result; result = new ArrayList<>(); Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "Name,Manufacturer,Model,SerialNumber,Size", null); for (int i = 0; i < vals.get("Name").size(); i++) { HWDiskStore ds = new HWDiskStore(); ds.setName(vals.get("Name").get(i)); ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim()); // Most vendors store serial # as a hex string; convert ds.setSerial(ParseUtil.hexStringToString(vals.get("SerialNumber").get(i))); // If successful this line is the desired value try { ds.setSize(Long.parseLong(vals.get("Size").get(i))); } catch (NumberFormatException e) { // If we failed to parse, give up // This is expected for an empty string on some drives ds.setSize(0L); } result.add(ds); } return result.toArray(new HWDiskStore[result.size()]); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static boolean updateDiskStats(HWDiskStore diskStore, DASessionRef session, Map<String, String> mountPointMap, Map<String, String> logicalVolumeMap, Map<CFKey, CFStringRef> cfKeyMap) { // Now look up the device using the BSD Name to get its // statistics String bsdName = diskStore.getName(); CFMutableDictionaryRef matchingDict = IOKitUtil.getBSDNameMatchingDict(bsdName); if (matchingDict != null) { // search for all IOservices that match the bsd name IOIterator driveListIter = IOKitUtil.getMatchingServices(matchingDict); if (driveListIter != null) { // getMatchingServices releases matchingDict IORegistryEntry drive = driveListIter.next(); // Should only match one drive if (drive != null) { // Should be an IOMedia object with a parent // IOBlockStorageDriver object // Get the properties from the parent if (drive.conformsTo("IOMedia")) { IORegistryEntry parent = drive.getParentEntry("IOService"); if (parent != null && parent.conformsTo("IOBlockStorageDriver")) { CFMutableDictionaryRef properties = parent.createCFProperties(); // We now have a properties object with the // statistics we need on it. Fetch them Pointer result = properties.getValue(cfKeyMap.get(CFKey.STATISTICS)); CFDictionaryRef statistics = new CFDictionaryRef(result); diskStore.setTimeStamp(System.currentTimeMillis()); // Now get the stats we want result = statistics.getValue(cfKeyMap.get(CFKey.READ_OPS)); CFNumberRef stat = new CFNumberRef(result); diskStore.setReads(stat.longValue()); result = statistics.getValue(cfKeyMap.get(CFKey.READ_BYTES)); stat.setPointer(result); diskStore.setReadBytes(stat.longValue()); result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_OPS)); stat.setPointer(result); diskStore.setWrites(stat.longValue()); result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_BYTES)); stat.setPointer(result); diskStore.setWriteBytes(stat.longValue()); // Total time is in nanoseconds. Add read+write // and convert total to ms result = statistics.getValue(cfKeyMap.get(CFKey.READ_TIME)); stat.setPointer(result); long xferTime = stat.longValue(); result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_TIME)); stat.setPointer(result); xferTime += stat.longValue(); diskStore.setTransferTime(xferTime / 1_000_000L); properties.release(); } else { // This is normal for FileVault drives, Fusion // drives, and other virtual bsd names LOG.debug("Unable to find block storage driver properties for {}", bsdName); } // Now get partitions for this disk. List<HWPartition> partitions = new ArrayList<>(); CFMutableDictionaryRef properties = drive.createCFProperties(); // Partitions will match BSD Unit property Pointer result = properties.getValue(cfKeyMap.get(CFKey.BSD_UNIT)); CFNumberRef bsdUnit = new CFNumberRef(result); // We need a CFBoolean that's false. // Whole disk has 'true' for Whole and 'false' // for leaf; store the boolean false result = properties.getValue(cfKeyMap.get(CFKey.LEAF)); CFBooleanRef cfFalse = new CFBooleanRef(result); // create a matching dict for BSD Unit CFMutableDictionaryRef propertyDict = CF.CFDictionaryCreateMutable(CF.CFAllocatorGetDefault(), new CFIndex(0), null, null); propertyDict.setValue(cfKeyMap.get(CFKey.BSD_UNIT), bsdUnit); propertyDict.setValue(cfKeyMap.get(CFKey.WHOLE), cfFalse); matchingDict = CF.CFDictionaryCreateMutable(CF.CFAllocatorGetDefault(), new CFIndex(0), null, null); matchingDict.setValue(cfKeyMap.get(CFKey.IO_PROPERTY_MATCH), propertyDict); // search for IOservices that match the BSD Unit // with whole=false; these are partitions IOIterator serviceIterator = IOKitUtil.getMatchingServices(matchingDict); // getMatchingServices releases matchingDict properties.release(); propertyDict.release(); if (serviceIterator != null) { // Iterate disks IORegistryEntry sdService = IOKit.INSTANCE.IOIteratorNext(serviceIterator); while (sdService != null) { // look up the BSD Name String partBsdName = sdService.getStringProperty("BSD Name"); String name = partBsdName; String type = ""; // Get the DiskArbitration dictionary for // this partition DADiskRef disk = DA.DADiskCreateFromBSDName(CF.CFAllocatorGetDefault(), session, partBsdName); if (disk != null) { CFDictionaryRef diskInfo = DA.DADiskCopyDescription(disk); if (diskInfo != null) { // get volume name from its key result = diskInfo.getValue(cfKeyMap.get(CFKey.DA_MEDIA_NAME)); CFStringRef volumePtr = new CFStringRef(result); type = volumePtr.stringValue(); if (type == null) { type = Constants.UNKNOWN; } result = diskInfo.getValue(cfKeyMap.get(CFKey.DA_VOLUME_NAME)); if (result == null) { name = type; } else { volumePtr.setPointer(result); name = volumePtr.stringValue(); } diskInfo.release(); } disk.release(); } String mountPoint; if (logicalVolumeMap.containsKey(partBsdName)) { mountPoint = "Logical Volume: " + logicalVolumeMap.get(partBsdName); } else { mountPoint = mountPointMap.getOrDefault(partBsdName, ""); } Long size = sdService.getLongProperty("Size"); Integer bsdMajor = sdService.getIntegerProperty("BSD Major"); Integer bsdMinor = sdService.getIntegerProperty("BSD Minor"); partitions.add(new HWPartition(partBsdName, name, type, sdService.getStringProperty("UUID"), size == null ? 0L : size, bsdMajor == null ? 0 : bsdMajor, bsdMinor == null ? 0 : bsdMinor, mountPoint)); // iterate sdService.release(); sdService = IOKit.INSTANCE.IOIteratorNext(serviceIterator); } serviceIterator.release(); } Collections.sort(partitions); diskStore.setPartitions(partitions.toArray(new HWPartition[0])); if (parent != null) { parent.release(); } } else { LOG.error("Unable to find IOMedia device or parent for {}", bsdName); } drive.release(); } driveListIter.release(); return true; } } return false; }
#vulnerable code private static boolean updateDiskStats(HWDiskStore diskStore, DASessionRef session, Map<String, String> mountPointMap, Map<String, String> logicalVolumeMap, Map<CFKey, CFStringRef> cfKeyMap) { // Now look up the device using the BSD Name to get its // statistics String bsdName = diskStore.getName(); CFMutableDictionaryRef matchingDict = IOKitUtil.getBSDNameMatchingDict(bsdName); if (matchingDict != null) { // search for all IOservices that match the bsd name IOIterator driveListIter = IOKitUtil.getMatchingServices(matchingDict); if (driveListIter != null) { // getMatchingServices releases matchingDict IORegistryEntry drive = driveListIter.next(); // Should only match one drive if (drive != null) { // Should be an IOMedia object with a parent // IOBlockStorageDriver object // Get the properties from the parent if (drive.conformsTo("IOMedia")) { IORegistryEntry parent = drive.getParentEntry("IOService"); if (parent != null && parent.conformsTo("IOBlockStorageDriver")) { CFMutableDictionaryRef properties = parent.createCFProperties(); // We now have a properties object with the // statistics we need on it. Fetch them Pointer result = properties.getValue(cfKeyMap.get(CFKey.STATISTICS)); CFDictionaryRef statistics = new CFDictionaryRef(result); diskStore.setTimeStamp(System.currentTimeMillis()); // Now get the stats we want result = statistics.getValue(cfKeyMap.get(CFKey.READ_OPS)); CFNumberRef stat = new CFNumberRef(result); diskStore.setReads(stat.longValue()); result = statistics.getValue(cfKeyMap.get(CFKey.READ_BYTES)); stat.setPointer(result); diskStore.setReadBytes(stat.longValue()); result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_OPS)); stat.setPointer(result); diskStore.setWrites(stat.longValue()); result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_BYTES)); stat.setPointer(result); diskStore.setWriteBytes(stat.longValue()); // Total time is in nanoseconds. Add read+write // and convert total to ms result = statistics.getValue(cfKeyMap.get(CFKey.READ_TIME)); stat.setPointer(result); long xferTime = stat.longValue(); result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_TIME)); stat.setPointer(result); xferTime += stat.longValue(); diskStore.setTransferTime(xferTime / 1_000_000L); properties.release(); } else { // This is normal for FileVault drives, Fusion // drives, and other virtual bsd names LOG.debug("Unable to find block storage driver properties for {}", bsdName); } // Now get partitions for this disk. List<HWPartition> partitions = new ArrayList<>(); CFMutableDictionaryRef properties = drive.createCFProperties(); // Partitions will match BSD Unit property Pointer result = properties.getValue(cfKeyMap.get(CFKey.BSD_UNIT)); CFNumberRef bsdUnit = new CFNumberRef(result); // We need a CFBoolean that's false. // Whole disk has 'true' for Whole and 'false' // for leaf; store the boolean false result = properties.getValue(cfKeyMap.get(CFKey.LEAF)); CFBooleanRef cfFalse = new CFBooleanRef(result); // create a matching dict for BSD Unit CFMutableDictionaryRef propertyDict = CF.CFDictionaryCreateMutable(CF.CFAllocatorGetDefault(), new CFIndex(0), null, null); propertyDict.setValue(cfKeyMap.get(CFKey.BSD_UNIT), bsdUnit); propertyDict.setValue(cfKeyMap.get(CFKey.WHOLE), cfFalse); matchingDict = CF.CFDictionaryCreateMutable(CF.CFAllocatorGetDefault(), new CFIndex(0), null, null); matchingDict.setValue(cfKeyMap.get(CFKey.IO_PROPERTY_MATCH), propertyDict); // search for IOservices that match the BSD Unit // with whole=false; these are partitions IOIterator serviceIterator = IOKitUtil.getMatchingServices(matchingDict); // getMatchingServices releases matchingDict properties.release(); propertyDict.release(); // Iterate disks IORegistryEntry sdService = IOKit.INSTANCE.IOIteratorNext(serviceIterator); while (sdService != null) { // look up the BSD Name String partBsdName = sdService.getStringProperty("BSD Name"); String name = partBsdName; String type = ""; // Get the DiskArbitration dictionary for // this partition DADiskRef disk = DA.DADiskCreateFromBSDName(CF.CFAllocatorGetDefault(), session, partBsdName); if (disk != null) { CFDictionaryRef diskInfo = DA.DADiskCopyDescription(disk); if (diskInfo != null) { // get volume name from its key result = diskInfo.getValue(cfKeyMap.get(CFKey.DA_MEDIA_NAME)); CFStringRef volumePtr = new CFStringRef(result); type = volumePtr.stringValue(); if (type == null) { type = Constants.UNKNOWN; } result = diskInfo.getValue(cfKeyMap.get(CFKey.DA_VOLUME_NAME)); if (result == null) { name = type; } else { volumePtr.setPointer(result); name = volumePtr.stringValue(); } diskInfo.release(); } disk.release(); } String mountPoint; if (logicalVolumeMap.containsKey(partBsdName)) { mountPoint = "Logical Volume: " + logicalVolumeMap.get(partBsdName); } else { mountPoint = mountPointMap.getOrDefault(partBsdName, ""); } Long size = sdService.getLongProperty("Size"); Integer bsdMajor = sdService.getIntegerProperty("BSD Major"); Integer bsdMinor = sdService.getIntegerProperty("BSD Minor"); partitions.add(new HWPartition(partBsdName, name, type, sdService.getStringProperty("UUID"), size == null ? 0L : size, bsdMajor == null ? 0 : bsdMajor, bsdMinor == null ? 0 : bsdMinor, mountPoint)); // iterate sdService.release(); sdService = IOKit.INSTANCE.IOIteratorNext(serviceIterator); } serviceIterator.release(); Collections.sort(partitions); diskStore.setPartitions(partitions.toArray(new HWPartition[0])); if (parent != null) { parent.release(); } } else { LOG.error("Unable to find IOMedia device or parent for {}", bsdName); } drive.release(); } driveListIter.release(); return true; } } return false; } #location 135 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static <T extends Enum<T>> Pair<List<String>, Map<T, List<Long>>> queryInstancesAndValues( Class<T> propertyEnum, String perfObject, String perfWmiClass) { // Check without locking for performance if (!failedQueryCache.contains(perfObject)) { failedQueryCacheLock.lock(); try { // Double check lock if (!failedQueryCache.contains(perfObject)) { Pair<List<String>, Map<T, List<Long>>> instancesAndValuesMap = queryInstancesAndValuesFromPDH( propertyEnum, perfObject); if (!instancesAndValuesMap.getA().isEmpty()) { return instancesAndValuesMap; } // If we are here, query failed LOG.warn("Disabling further attempts to query {}.", perfObject); failedQueryCache.add(perfObject); } } finally { failedQueryCacheLock.unlock(); } } return queryInstancesAndValuesFromWMI(propertyEnum, perfWmiClass); }
#vulnerable code public static <T extends Enum<T>> Pair<List<String>, Map<T, List<Long>>> queryInstancesAndValues( Class<T> propertyEnum, String perfObject, String perfWmiClass) { Pair<List<String>, Map<T, List<Long>>> instancesAndValuesMap = queryInstancesAndValuesFromPDH(propertyEnum, perfObject); if (instancesAndValuesMap.getA().isEmpty()) { return queryInstancesAndValuesFromWMI(propertyEnum, perfWmiClass); } return instancesAndValuesMap; } #location 3 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void updateMeminfo() { long now = System.currentTimeMillis(); if (now - this.lastUpdate > 100) { if (!Psapi.INSTANCE.GetPerformanceInfo(perfInfo, perfInfo.size())) { LOG.error("Failed to get Performance Info. Error code: {}", Kernel32.INSTANCE.GetLastError()); return; } this.memAvailable = perfInfo.PageSize.longValue() * perfInfo.PhysicalAvailable.longValue(); this.memTotal = perfInfo.PageSize.longValue() * perfInfo.PhysicalTotal.longValue(); this.swapTotal = perfInfo.PageSize.longValue() * (perfInfo.CommitLimit.longValue() - perfInfo.PhysicalTotal.longValue()); this.lastUpdate = now; } }
#vulnerable code protected void updateMeminfo() { long now = System.currentTimeMillis(); if (now - this.lastUpdate > 100) { if (!Psapi.INSTANCE.GetPerformanceInfo(perfInfo, perfInfo.size())) { LOG.error("Failed to get Performance Info. Error code: {}", Kernel32.INSTANCE.GetLastError()); this.perfInfo = null; } this.memAvailable = perfInfo.PageSize.longValue() * perfInfo.PhysicalAvailable.longValue(); this.memTotal = perfInfo.PageSize.longValue() * perfInfo.PhysicalTotal.longValue(); this.swapTotal = perfInfo.PageSize.longValue() * (perfInfo.CommitLimit.longValue() - perfInfo.PhysicalTotal.longValue()); this.lastUpdate = now; } } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { // Enumerator will be released by calling method so no need to // release it here. return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { // WMI Longs will return as strings case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; // WMI Uint32s will return as longs case UINT32: // WinDef.LONG TODO improve in JNA 4.3 values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property) .add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; default: // Should never get here! If you get this exception you've // added something to the enum without adding it here. Tsk. throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); } clsObj.Release(); } }
#vulnerable code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { // Enumerator will be released by calling method so no need to // release it here. return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { // WMI Longs will return as strings case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; // WMI Uint32s will return as longs case UINT32: // WinDef.LONG TODO improve in JNA 4.3 values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; default: // Should never get here! If you get this exception you've // added something to the enum without adding it here. Tsk. throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); } clsObj.Release(); } } #location 39 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<OSFileStore> getWmiVolumes() { Map<String, List<Object>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES); for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) { free = (Long) drives.get(FREESPACE_PROPERTY).get(i); total = (Long) drives.get(SIZE_PROPERTY).get(i); String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i); String name = (String) drives.get(NAME_PROPERTY).get(i); long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name), (String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total)); } return fs; }
#vulnerable code private List<OSFileStore> getWmiVolumes() { Map<String, List<String>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk", "Name,Description,ProviderName,FileSystem,Freespace,Size", null); for (int i = 0; i < drives.get("Name").size(); i++) { free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L); total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L); String description = drives.get("Description").get(i); long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType", "WHERE Name = '" + drives.get("Name").get(i) + "'"); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = drives.get("ProviderName").get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume, drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)), drives.get("FileSystem").get(i), "", free, total)); } return fs; } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Memory sysctl(String name) { IntByReference size = new IntByReference(); if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, null, size, null, 0)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return null; } Memory m = new Memory(size.getValue()); if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, m, size, null, 0)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return null; } return m; }
#vulnerable code public static Memory sysctl(String name) { IntByReference size = new IntByReference(); if (0 != SystemB.INSTANCE.sysctlbyname(name, null, size, null, 0)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return null; } Memory m = new Memory(size.getValue()); if (0 != SystemB.INSTANCE.sysctlbyname(name, m, size, null, 0)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return null; } return m; } #location 3 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static <T extends Enum<T>> Map<T, Long> queryValues(Class<T> propertyEnum, String perfObject, String perfWmiClass) { // Check without locking for performance if (!failedQueryCache.contains(perfObject)) { failedQueryCacheLock.lock(); try { // Double check lock if (!failedQueryCache.contains(perfObject)) { Map<T, Long> valueMap = queryValuesFromPDH(propertyEnum, perfObject); if (!valueMap.isEmpty()) { return valueMap; } // If we are here, query failed LOG.warn("Disabling further attempts to query {}.", perfObject); failedQueryCache.add(perfObject); } } finally { failedQueryCacheLock.unlock(); } } return queryValuesFromWMI(propertyEnum, perfWmiClass); }
#vulnerable code public static <T extends Enum<T>> Map<T, Long> queryValues(Class<T> propertyEnum, String perfObject, String perfWmiClass) { Map<T, Long> valueMap = queryValuesFromPDH(propertyEnum, perfObject); if (valueMap.isEmpty()) { return queryValuesFromWMI(propertyEnum, perfWmiClass); } return valueMap; } #location 3 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public long[][] queryProcessorCpuLoadTicks() { long[][] ticks = CpuStat.getProcessorCpuLoadTicks(getLogicalProcessorCount()); // In rare cases, /proc/stat reading fails. If so, try again. // In theory we should check all of them, but on failure we can expect all 0's // so we only need to check for processor 0 if (LongStream.of(ticks[0]).sum() == 0) { ticks = CpuStat.getProcessorCpuLoadTicks(getLogicalProcessorCount()); } // convert the Linux Jiffies to Milliseconds. long hz = LinuxOperatingSystem.getHz(); for (int i = 0; i < ticks.length; i++) { for (int j = 0; j < ticks[i].length; j++) { ticks[i][j] = ticks[i][j] * 1000L / hz; } } return ticks; }
#vulnerable code @Override public long[][] queryProcessorCpuLoadTicks() { long[][] ticks = CpuStat.getProcessorCpuLoadTicks(getLogicalProcessorCount()); // convert the Linux Jiffies to Milliseconds. long hz = LinuxOperatingSystem.getHz(); for (int i = 0; i < ticks.length; i++) { for (int j = 0; j < ticks[i].length; j++) { ticks[i][j] = ticks[i][j] * 1000L / hz; } } return ticks; } #location 3 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public OSFileStore[] getFileStores() { // Use getfsstat to map filesystem paths to types Map<String, String> fstype = new HashMap<>(); // Query with null to get total # required int numfs = SystemB.INSTANCE.getfsstat64(null, 0, 0); if (numfs > 0) { // Create array to hold results Statfs[] fs = new Statfs[numfs]; // Fill array with results numfs = SystemB.INSTANCE.getfsstat64(fs, numfs * (new Statfs()).size(), SystemB.MNT_NOWAIT); for (int f = 0; f < numfs; f++) { // Mount to name will match canonical path. // Byte arrays are null-terminated strings fstype.put(new String(fs[f].f_mntonname).trim(), new String(fs[f].f_fstypename).trim()); } } // Now list file systems List<OSFileStore> fsList = new ArrayList<>(); FileSystemView fsv = FileSystemView.getFileSystemView(); // Mac file systems are mounted in /Volumes File volumes = new File("/Volumes"); if (volumes != null && volumes.listFiles() != null) { for (File f : volumes.listFiles()) { // Everyone hates DS Store if (f.getName().endsWith(".DS_Store")) { continue; } String name = fsv.getSystemDisplayName(f); String description = "Volume"; String type = "unknown"; try { String cp = f.getCanonicalPath(); if (cp.equals("/")) name = name + " (/)"; FileStore fs = Files.getFileStore(f.toPath()); if (localDisk.matcher(fs.name()).matches()) { description = "Local Disk"; } if (fs.name().startsWith("localhost:") || fs.name().startsWith("//")) { description = "Network Drive"; } if (fstype.containsKey(cp)) { type = fstype.get(cp); } } catch (IOException e) { LOG.trace("", e); continue; } fsList.add(new OSFileStore(name, description, type, f.getUsableSpace(), f.getTotalSpace())); } } return fsList.toArray(new OSFileStore[fsList.size()]); }
#vulnerable code public OSFileStore[] getFileStores() { // Use getfsstat to map filesystem paths to types Map<String, String> fstype = new HashMap<>(); // Query with null to get total # required int numfs = SystemB.INSTANCE.getfsstat64(null, 0, 0); if (numfs > 0) { // Create array to hold results Statfs[] fs = new Statfs[numfs]; // Fill array with results numfs = SystemB.INSTANCE.getfsstat64(fs, numfs * (new Statfs()).size(), SystemB.MNT_NOWAIT); for (int f = 0; f < numfs; f++) { // Mount to name will match canonical path. // Byte arrays are null-terminated strings fstype.put(new String(fs[f].f_mntonname).trim(), new String(fs[f].f_fstypename).trim()); } } // Now list file systems List<OSFileStore> fsList = new ArrayList<>(); FileSystemView fsv = FileSystemView.getFileSystemView(); // Mac file systems are mounted in /Volumes File volumes = new File("/Volumes"); if (volumes != null) { for (File f : volumes.listFiles()) { // Everyone hates DS Store if (f.getName().endsWith(".DS_Store")) { continue; } String name = fsv.getSystemDisplayName(f); String description = "Volume"; String type = "unknown"; try { String cp = f.getCanonicalPath(); if (cp.equals("/")) name = name + " (/)"; FileStore fs = Files.getFileStore(f.toPath()); if (localDisk.matcher(fs.name()).matches()) { description = "Local Disk"; } if (fs.name().startsWith("localhost:") || fs.name().startsWith("//")) { description = "Network Drive"; } if (fstype.containsKey(cp)) { type = fstype.get(cp); } } catch (IOException e) { LOG.trace("", e); continue; } fsList.add(new OSFileStore(name, description, type, f.getUsableSpace(), f.getTotalSpace())); } } return fsList.toArray(new OSFileStore[fsList.size()]); } #location 23 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public double getCpuTemperature() { // Initialize double tempC = 0d; // If Open Hardware Monitor identifier is set, we couldn't get through // normal WMI, and got ID from OHM at least once so go directly to OHM if (this.tempIdentifierStr != null) { double[] vals = wmiGetValuesForKeys("/namespace:\\\\root\\OpenHardwareMonitor PATH Sensor", this.tempIdentifierStr, "Temperature", "Parent,SensorType,Value"); if (vals.length > 0) { double sum = 0; for (double val : vals) { sum += val; } tempC = sum / vals.length; } return tempC; } // This branch is used the first time and all subsequent times if // successful (tempIdenifierStr == null) // Try to get value using initial or updated successful values int tempK = 0; if (this.wmiTempPath == null) { this.wmiTempPath = "Temperature"; this.wmiTempProperty = "CurrentReading"; tempK = wmiGetValue(this.wmiTempPath, this.wmiTempProperty); if (tempK < 0) { this.wmiTempPath = "/namespace:\\\\root\\cimv2 PATH Win32_TemperatureProbe"; tempK = wmiGetValue(this.wmiTempPath, this.wmiTempProperty); } if (tempK < 0) { this.wmiTempPath = "/namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature"; this.wmiTempProperty = "CurrentTemperature"; tempK = wmiGetValue(this.wmiTempPath, this.wmiTempProperty); } } else { // We've successfully read a previous time, or failed both here and // with OHM tempK = wmiGetValue(this.wmiTempPath, this.wmiTempProperty); } // Convert K to C and return result if (tempK > 0) { tempC = (tempK / 10d) - 273.15; } if (tempC <= 0d) { // Unable to get temperature via WMI. Future attempts will be // attempted via Open Hardware Monitor WMI if successful String[] cpuIdentifiers = wmiGetStrValuesForKey("/namespace:\\\\root\\OpenHardwareMonitor PATH Hardware", "CPU", "HardwareType,Identifier"); if (cpuIdentifiers.length > 0) { this.tempIdentifierStr = cpuIdentifiers[0]; } // If not null, recurse and get value via OHM if (this.tempIdentifierStr != null) { return getCpuTemperature(); } } return tempC; }
#vulnerable code @Override public double getCpuTemperature() { ArrayList<String> hwInfo = ExecutingCommand.runNative("wmic Temperature get CurrentReading"); for (String checkLine : hwInfo) { if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { continue; } else { // If successful this line is in tenths of degrees Kelvin try { int tempK = Integer.parseInt(checkLine.trim()); if (tempK > 0) { return (tempK - 2715) / 10d; } } catch (NumberFormatException e) { // If we failed to parse, give up } break; } } // Above query failed, try something else hwInfo = ExecutingCommand .runNative("wmic /namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature"); for (String checkLine : hwInfo) { if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currenttemperature")) { continue; } else { // If successful this line is in tenths of degrees Kelvin try { int tempK = Integer.parseInt(checkLine.trim()); if (tempK > 0) { return (tempK - 2715) / 10d; } } catch (NumberFormatException e) { // If we failed to parse, give up } break; } } // Above query failed, try something else hwInfo = ExecutingCommand .runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_TemperatureProbe get CurrentReading"); for (String checkLine : hwInfo) { if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { continue; } else { // If successful this line is in tenths of degrees Kelvin try { int tempK = Integer.parseInt(checkLine.trim()); if (tempK > 0) { return (tempK - 2715) / 10d; } } catch (NumberFormatException e) { // If we failed to parse, give up } break; } } return 0d; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public long[] querySystemCpuLoadTicks() { // To get load in processor group scenario, we need perfmon counters, but the // _Total instance is an average rather than total (scaled) number of ticks // which matches GetSystemTimes() results. We can just query the per-processor // ticks and add them up. Calling the get() method gains the benefit of // synchronizing this output with the memoized result of per-processor ticks as // well. long[] ticks = new long[TickType.values().length]; // Sum processor ticks long[][] procTicks = getProcessorCpuLoadTicks(); for (int i = 0; i < ticks.length; i++) { for (long[] procTick : procTicks) { ticks[i] += procTick[i]; } } return ticks; }
#vulnerable code @Override public long[] querySystemCpuLoadTicks() { long[] ticks = new long[TickType.values().length]; WinBase.FILETIME lpIdleTime = new WinBase.FILETIME(); WinBase.FILETIME lpKernelTime = new WinBase.FILETIME(); WinBase.FILETIME lpUserTime = new WinBase.FILETIME(); if (!Kernel32.INSTANCE.GetSystemTimes(lpIdleTime, lpKernelTime, lpUserTime)) { LOG.error("Failed to update system idle/kernel/user times. Error code: {}", Native.getLastError()); return ticks; } // IOwait: // Windows does not measure IOWait. // IRQ and ticks: // Percent time raw value is cumulative 100NS-ticks // Divide by 10_000 to get milliseconds Map<SystemTickCountProperty, Long> valueMap = ProcessorInformation.querySystemCounters(); ticks[TickType.IRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTINTERRUPTTIME, 0L) / 10_000L; ticks[TickType.SOFTIRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTDPCTIME, 0L) / 10_000L; ticks[TickType.IDLE.getIndex()] = lpIdleTime.toDWordLong().longValue() / 10_000L; ticks[TickType.SYSTEM.getIndex()] = lpKernelTime.toDWordLong().longValue() / 10_000L - ticks[TickType.IDLE.getIndex()]; ticks[TickType.USER.getIndex()] = lpUserTime.toDWordLong().longValue() / 10_000L; // Additional decrement to avoid double counting in the total array ticks[TickType.SYSTEM.getIndex()] -= ticks[TickType.IRQ.getIndex()] + ticks[TickType.SOFTIRQ.getIndex()]; return ticks; } #location 18 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void populateReadWriteMaps() { // Although the field names say "PerSec" this is the Raw Data from which // the associated fields are populated in the Formatted Data class, so // in fact this is the data we want Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk", "Name,DiskReadsPerSec,DiskReadBytesPerSec,DiskWritesPerSec,DiskWriteBytesPerSec,PercentDiskTime", null, READ_WRITE_TYPES); for (int i = 0; i < vals.get("Name").size(); i++) { String index = ((String) vals.get("Name").get(i)).split("\\s+")[0]; readMap.put(index, (long) vals.get("DiskReadsPerSec").get(i)); readByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskReadBytesPerSec").get(i), 0L)); writeMap.put(index, (long) vals.get("DiskWritesPerSec").get(i)); writeByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskWriteBytesPerSec").get(i), 0L)); // Units are 100-ns, divide to get ms xferTimeMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("PercentDiskTime").get(i), 0L) / 10000L); } }
#vulnerable code private void populateReadWriteMaps() { // Although the field names say "PerSec" this is the Raw Data from which // the associated fields are populated in the Formatted Data class, so // in fact this is the data we want Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk", "Name,DiskReadBytesPerSec,DiskWriteBytesPerSec", null); for (int i = 0; i < vals.get("Name").size(); i++) { String index = vals.get("Name").get(i).split("\\s+")[0]; readMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskReadBytesPerSec").get(i), 0L)); writeMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskWriteBytesPerSec").get(i), 0L)); } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private DmidecodeStrings readDmiDecode() { String manufacturer = null; String version = null; String releaseDate = ""; // $ sudo dmidecode -t bios // # dmidecode 3.0 // Scanning /dev/mem for entry point. // SMBIOS 2.7 present. // // Handle 0x0000, DMI type 0, 24 bytes // BIOS Information // Vendor: Parallels Software International Inc. // Version: 11.2.1 (32626) // Release Date: 07/15/2016 // ... <snip> ... // BIOS Revision: 11.2 // Firmware Revision: 11.2 final String manufacturerMarker = "Vendor:"; final String versionMarker = "Version:"; final String releaseDateMarker = "Release Date:"; // Only works with root permissions but it's all we've got for (final String checkLine : ExecutingCommand.runNative("dmidecode -t bios")) { if (checkLine.contains(manufacturerMarker)) { manufacturer = checkLine.split(manufacturerMarker)[1].trim(); } else if (checkLine.contains(versionMarker)) { version = checkLine.split(versionMarker)[1].trim(); } else if (checkLine.contains(releaseDateMarker)) { releaseDate = checkLine.split(releaseDateMarker)[1].trim(); } } releaseDate = ParseUtil.parseMmDdYyyyToYyyyMmDD(releaseDate); return new DmidecodeStrings(manufacturer, version, releaseDate); }
#vulnerable code private DmidecodeStrings readDmiDecode() { String manufacturer = null; String version = null; String releaseDate = null; // $ sudo dmidecode -t bios // # dmidecode 3.0 // Scanning /dev/mem for entry point. // SMBIOS 2.7 present. // // Handle 0x0000, DMI type 0, 24 bytes // BIOS Information // Vendor: Parallels Software International Inc. // Version: 11.2.1 (32626) // Release Date: 07/15/2016 // ... <snip> ... // BIOS Revision: 11.2 // Firmware Revision: 11.2 final String manufacturerMarker = "Vendor:"; final String versionMarker = "Version:"; final String releaseDateMarker = "Release Date:"; // Only works with root permissions but it's all we've got for (final String checkLine : ExecutingCommand.runNative("dmidecode -t bios")) { if (checkLine.contains(manufacturerMarker)) { manufacturer = checkLine.split(manufacturerMarker)[1].trim(); } else if (checkLine.contains(versionMarker)) { version = checkLine.split(versionMarker)[1].trim(); } else if (checkLine.contains(releaseDateMarker)) { releaseDate = checkLine.split(releaseDateMarker)[1].trim(); } } releaseDate = ParseUtil.parseMmDdYyyyToYyyyMmDD(releaseDate); return new DmidecodeStrings(manufacturer, version, releaseDate); } #location 34 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { enumerator.Release(); return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; case LONG: // WinDef.LONG TODO improve in JNA 4.3 values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; default: // Should never get here! throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); } clsObj.Release(); } }
#vulnerable code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes) { if (properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must equal properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { enumerator.Release(); return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); switch (propertyTypes[p]) { case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; case LONG: // WinDef.LONG values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; default: // Should never get here! LOG.error("Unimplemented enum type."); } OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); } clsObj.Release(); } } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void updateSwap() { updateMeminfo(); this.swapUsed = PdhUtil.queryCounter(pdhPagingPercentUsageCounter) * this.pageSize; }
#vulnerable code @Override protected void updateSwap() { updateMeminfo(); Map<String, List<Long>> usage = WmiUtil.selectUint32sFrom(null, "Win32_PerfRawData_PerfOS_PagingFile", "PercentUsage,PercentUsage_Base", "WHERE Name=\"_Total\""); if (!usage.get("PercentUsage").isEmpty()) { this.swapUsed = this.swapTotal * usage.get("PercentUsage").get(0) / usage.get("PercentUsage_Base").get(0); } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getTotal() { if (totalMemory == 0) { Sysinfo info = new Sysinfo(); if (0 != Libc.INSTANCE.sysinfo(info)) throw new LastErrorException("Error code: " + Native.getLastError()); totalMemory = info.totalram.longValue() * info.mem_unit; } return totalMemory; }
#vulnerable code public long getTotal() { if (totalMemory == 0) { Scanner in = null; try { in = new Scanner(new FileReader("/proc/meminfo")); } catch (FileNotFoundException e) { totalMemory = 0; return totalMemory; } in.useDelimiter("\n"); while (in.hasNext()) { String checkLine = in.next(); if (checkLine.startsWith("MemTotal:")) { String[] memorySplit = checkLine.split("\\s+"); totalMemory = parseMeminfo(memorySplit); break; } } in.close(); } return totalMemory; } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static UsbDevice[] getUsbDevices() { // Reusable buffer for getting IO name strings Pointer buffer = new Memory(128); // io_name_t is char[128] // Build a list of devices with no parent; these will be the roots List<Long> usbControllers = new ArrayList<>(); // Empty out maps nameMap.clear(); vendorMap.clear(); serialMap.clear(); hubMap.clear(); // Iterate over USB Controllers. All devices are children of one of // these controllers in the "IOService" plane IntByReference iter = new IntByReference(); IOKitUtil.getMatchingServices("IOUSBController", iter); int device = IOKit.INSTANCE.IOIteratorNext(iter.getValue()); while (device != 0) { // Unique global identifier for this device LongByReference id = new LongByReference(); IOKit.INSTANCE.IORegistryEntryGetRegistryEntryID(device, id); usbControllers.add(id.getValue()); // Get device name and store in map IOKit.INSTANCE.IORegistryEntryGetName(device, buffer); nameMap.put(id.getValue(), buffer.getString(0)); // Controllers don't have vendor and serial so ignore at this level // Now iterate the children of this device in the "IOService" plane. // If devices have a parent, link to that parent, otherwise link to // the controller as parent IntByReference childIter = new IntByReference(); IOKit.INSTANCE.IORegistryEntryGetChildIterator(device, "IOService", childIter); int childDevice = IOKit.INSTANCE.IOIteratorNext(childIter.getValue()); while (childDevice != 0) { // Unique global identifier for this device LongByReference childId = new LongByReference(); IOKit.INSTANCE.IORegistryEntryGetRegistryEntryID(childDevice, childId); // Get this device's parent in the "IOUSB" plane IntByReference parent = new IntByReference(); IOKit.INSTANCE.IORegistryEntryGetParentEntry(childDevice, "IOUSB", parent); // If parent is named "Root" ignore that id and use the // controller's id LongByReference parentId = id; IOKit.INSTANCE.IORegistryEntryGetName(parent.getValue(), buffer); if (!buffer.getString(0).equals("Root")) { // Unique global identifier for the parent parentId = new LongByReference(); IOKit.INSTANCE.IORegistryEntryGetRegistryEntryID(parent.getValue(), parentId); } // Store parent in map if (!hubMap.containsKey(parentId.getValue())) { hubMap.put(parentId.getValue(), new ArrayList<Long>()); } hubMap.get(parentId.getValue()).add(childId.getValue()); // Get device name and store in map IOKit.INSTANCE.IORegistryEntryGetName(childDevice, buffer); nameMap.put(childId.getValue(), buffer.getString(0)); // Get vendor and store in map CFTypeRef vendorRef = IOKit.INSTANCE.IORegistryEntryCreateCFProperty(childDevice, cfVendor, CfUtil.ALLOCATOR, 0); if (vendorRef != null && vendorRef.getPointer() != null) { vendorMap.put(childId.getValue(), CfUtil.cfPointerToString(vendorRef.getPointer())); } CfUtil.release(vendorRef); // Get serial and store in map CFTypeRef serialRef = IOKit.INSTANCE.IORegistryEntryCreateCFProperty(childDevice, cfSerial, CfUtil.ALLOCATOR, 0); if (serialRef != null && serialRef.getPointer() != null) { serialMap.put(childId.getValue(), CfUtil.cfPointerToString(serialRef.getPointer())); } CfUtil.release(serialRef); IOKit.INSTANCE.IOObjectRelease(childDevice); childDevice = IOKit.INSTANCE.IOIteratorNext(childIter.getValue()); } IOKit.INSTANCE.IOObjectRelease(childIter.getValue()); IOKit.INSTANCE.IOObjectRelease(device); device = IOKit.INSTANCE.IOIteratorNext(iter.getValue()); } IOKit.INSTANCE.IOObjectRelease(iter.getValue()); // Build tree and return List<UsbDevice> controllerDevices = new ArrayList<UsbDevice>(); for (Long controller : usbControllers) { controllerDevices.add(getDeviceAndChildren(controller)); } return controllerDevices.toArray(new UsbDevice[controllerDevices.size()]); }
#vulnerable code public static UsbDevice[] getUsbDevices() { // Get heirarchical list of USB devices List<String> xml = ExecutingCommand.runNative("system_profiler SPUSBDataType -xml"); // Look for <key>_items</key> which prcedes <array> ... </array> // Each pair of <dict> ... </dict> following is a USB device/hub List<String> items = new ArrayList<>(); boolean copy = false; int indent = 0; for (String s : xml) { s = s.trim(); // Read until <key>_items</key> if (!copy && s.equals("<key>_items</key>")) { copy = true; continue; } // If we've fond items indent with each <array> tag and copy over // everything with indent > 0. if (copy) { if (s.equals("</array>")) { if (--indent == 0) { copy = false; continue; } } if (indent > 0) { items.add(s); } if (s.equals("<array>")) { indent++; } } } // Items now contains 0 or more sets of <dict>...</dict> return getUsbDevices(items); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static ArrayList<String> runNative(String[] cmdToRunWithArgs) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRunWithArgs); } catch (IOException e) { LOG.trace("", e); return null; } ArrayList<String> sa = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { sa.add(line); } p.waitFor(); } catch (InterruptedException e) { LOG.trace("", e); return null; } catch (IOException e) { LOG.trace("", e); return null; } return sa; }
#vulnerable code public static ArrayList<String> runNative(String[] cmdToRunWithArgs) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRunWithArgs); } catch (IOException e) { LOG.trace("", e); return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; ArrayList<String> sa = new ArrayList<>(); try { while ((line = reader.readLine()) != null) { sa.add(line); } p.waitFor(); } catch (InterruptedException e) { LOG.trace("", e); return null; } catch (IOException e) { LOG.trace("", e); return null; } return sa; } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String getFamily() { if (this._family == null) { String etcOsRelease = getReleaseFilename(); try { this.osRelease = FileUtil.readFile(etcOsRelease); for (String line : this.osRelease) { String[] splittedLine = line.split("="); if ((splittedLine[0].equals("NAME") || splittedLine[0].equals("DISTRIB_ID")) && splittedLine.length > 1) { // remove beginning and ending '"' characters, etc from // NAME="Ubuntu" this._family = splittedLine[1].replaceAll("^\"|\"$", ""); break; } } // If we've gotten to the end without matching, use the filename if (this._family == null) { this._family = etcOsRelease.replace("/etc/", "").replace("release", "").replace("version", "") .replace("-", ""); } } catch (IOException e) { LOG.trace("", e); return ""; } } return this._family; }
#vulnerable code @Override public String getFamily() { if (this._family == null) { try (final Scanner in = new Scanner(new FileReader("/etc/os-release"))) { in.useDelimiter("\n"); while (in.hasNext()) { String[] splittedLine = in.next().split("="); if (splittedLine[0].equals("NAME")) { // remove beginning and ending '"' characters, etc from // NAME="Ubuntu" this._family = splittedLine[1].replaceAll("^\"|\"$", ""); break; } } } catch (FileNotFoundException e) { LOG.trace("", e); return ""; } } return this._family; } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<OSFileStore> getWmiVolumes() { Map<String, List<Object>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES); for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) { free = (Long) drives.get(FREESPACE_PROPERTY).get(i); total = (Long) drives.get(SIZE_PROPERTY).get(i); String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i); String name = (String) drives.get(NAME_PROPERTY).get(i); long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name), (String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total)); } return fs; }
#vulnerable code private List<OSFileStore> getWmiVolumes() { Map<String, List<String>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk", "Name,Description,ProviderName,FileSystem,Freespace,Size", null); for (int i = 0; i < drives.get("Name").size(); i++) { free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L); total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L); String description = drives.get("Description").get(i); long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType", "WHERE Name = '" + drives.get("Name").get(i) + "'"); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = drives.get("ProviderName").get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume, drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)), drives.get("FileSystem").get(i), "", free, total)); } return fs; } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean updateAttributes() { try { File ifDir = new File(String.format("/sys/class/net/%s/statistics", getName())); if (!ifDir.isDirectory()) { return false; } } catch (SecurityException e) { return false; } String ifTypePath = String.format("/sys/class/net/%s/type", getName()); String carrierPath = String.format("/sys/class/net/%s/carrier", getName()); String txBytesPath = String.format("/sys/class/net/%s/statistics/tx_bytes", getName()); String rxBytesPath = String.format("/sys/class/net/%s/statistics/rx_bytes", getName()); String txPacketsPath = String.format("/sys/class/net/%s/statistics/tx_packets", getName()); String rxPacketsPath = String.format("/sys/class/net/%s/statistics/rx_packets", getName()); String txErrorsPath = String.format("/sys/class/net/%s/statistics/tx_errors", getName()); String rxErrorsPath = String.format("/sys/class/net/%s/statistics/rx_errors", getName()); String collisionsPath = String.format("/sys/class/net/%s/statistics/collisions", getName()); String rxDropsPath = String.format("/sys/class/net/%s/statistics/rx_dropped", getName()); String ifSpeed = String.format("/sys/class/net/%s/speed", getName()); this.timeStamp = System.currentTimeMillis(); this.ifType = FileUtil.getIntFromFile(ifTypePath); this.connectorPresent = FileUtil.getIntFromFile(carrierPath) > 0; this.bytesSent = FileUtil.getUnsignedLongFromFile(txBytesPath); this.bytesRecv = FileUtil.getUnsignedLongFromFile(rxBytesPath); this.packetsSent = FileUtil.getUnsignedLongFromFile(txPacketsPath); this.packetsRecv = FileUtil.getUnsignedLongFromFile(rxPacketsPath); this.outErrors = FileUtil.getUnsignedLongFromFile(txErrorsPath); this.inErrors = FileUtil.getUnsignedLongFromFile(rxErrorsPath); this.collisions = FileUtil.getUnsignedLongFromFile(collisionsPath); this.inDrops = FileUtil.getUnsignedLongFromFile(rxDropsPath); long speedMiB = FileUtil.getUnsignedLongFromFile(ifSpeed); // speed may be -1 from file. this.speed = speedMiB < 0 ? 0 : speedMiB << 20; return true; }
#vulnerable code @Override public boolean updateAttributes() { try { File ifDir = new File(String.format("/sys/class/net/%s/statistics", getName())); if (!ifDir.isDirectory()) { return false; } } catch (SecurityException e) { return false; } String ifTypePath = String.format("/sys/class/net/%s/type", getName()); String carrierPath = String.format("/sys/class/net/%s/carrier", getName()); String txBytesPath = String.format("/sys/class/net/%s/statistics/tx_bytes", getName()); String rxBytesPath = String.format("/sys/class/net/%s/statistics/rx_bytes", getName()); String txPacketsPath = String.format("/sys/class/net/%s/statistics/tx_packets", getName()); String rxPacketsPath = String.format("/sys/class/net/%s/statistics/rx_packets", getName()); String txErrorsPath = String.format("/sys/class/net/%s/statistics/tx_errors", getName()); String rxErrorsPath = String.format("/sys/class/net/%s/statistics/rx_errors", getName()); String collisionsPath = String.format("/sys/class/net/%s/statistics/collisions", getName()); String rxDropsPath = String.format("/sys/class/net/%s/statistics/rx_dropped", getName()); String ifSpeed = String.format("/sys/class/net/%s/speed", getName()); this.timeStamp = System.currentTimeMillis(); this.ifType = FileUtil.getIntFromFile(ifTypePath); this.connectorPresent = FileUtil.getIntFromFile(carrierPath) > 0; this.bytesSent = FileUtil.getUnsignedLongFromFile(txBytesPath); this.bytesRecv = FileUtil.getUnsignedLongFromFile(rxBytesPath); this.packetsSent = FileUtil.getUnsignedLongFromFile(txPacketsPath); this.packetsRecv = FileUtil.getUnsignedLongFromFile(rxPacketsPath); this.outErrors = FileUtil.getUnsignedLongFromFile(txErrorsPath); this.inErrors = FileUtil.getUnsignedLongFromFile(rxErrorsPath); this.collisions = FileUtil.getUnsignedLongFromFile(collisionsPath); this.inDrops = FileUtil.getUnsignedLongFromFile(rxDropsPath); // speed may be negative from file. Convert to MiB. this.speed = FileUtil.getUnsignedLongFromFile(ifSpeed); this.speed = this.speed < 0 ? 0 : this.speed << 20; return true; } #location 36 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<OSFileStore> getWmiVolumes() { Map<String, List<Object>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES); for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) { free = (Long) drives.get(FREESPACE_PROPERTY).get(i); total = (Long) drives.get(SIZE_PROPERTY).get(i); String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i); String name = (String) drives.get(NAME_PROPERTY).get(i); long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name), (String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total)); } return fs; }
#vulnerable code private List<OSFileStore> getWmiVolumes() { Map<String, List<String>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk", "Name,Description,ProviderName,FileSystem,Freespace,Size", null); for (int i = 0; i < drives.get("Name").size(); i++) { free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L); total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L); String description = drives.get("Description").get(i); long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType", "WHERE Name = '" + drives.get("Name").get(i) + "'"); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = drives.get("ProviderName").get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume, drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)), drives.get("FileSystem").get(i), "", free, total)); } return fs; } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Memory sysctl(String name) { IntByReference size = new IntByReference(); if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, null, size, null, 0)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return null; } Memory m = new Memory(size.getValue()); if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, m, size, null, 0)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return null; } return m; }
#vulnerable code public static Memory sysctl(String name) { IntByReference size = new IntByReference(); if (0 != SystemB.INSTANCE.sysctlbyname(name, null, size, null, 0)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return null; } Memory m = new Memory(size.getValue()); if (0 != SystemB.INSTANCE.sysctlbyname(name, m, size, null, 0)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return null; } return m; } #location 8 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public OSService[] getServices() { // Get running services List<OSService> services = new ArrayList<>(); Set<String> running = new HashSet<>(); for (OSProcess p : getChildProcesses(1, 0, ProcessSort.PID)) { OSService s = new OSService(p.getName(), p.getProcessID(), RUNNING); services.add(s); running.add(p.getName()); } // Get Directories for stopped services File dir = new File("/etc/rc.d"); File[] listFiles; if (dir.exists() && dir.isDirectory() && (listFiles = dir.listFiles()) != null) { for (File f : listFiles) { String name = f.getName(); if (!running.contains(name)) { OSService s = new OSService(name, 0, STOPPED); services.add(s); } } } else { LOG.error("Directory: /etc/init does not exist"); } return services.toArray(new OSService[0]); }
#vulnerable code @Override public OSService[] getServices() { // Get running services List<OSService> services = new ArrayList<>(); Set<String> running = new HashSet<>(); for (OSProcess p : getChildProcesses(1, 0, ProcessSort.PID)) { OSService s = new OSService(p.getName(), p.getProcessID(), RUNNING); services.add(s); running.add(p.getName()); } // Get Directories for stopped services File dir = new File("/etc/rc.d"); if (dir.exists() && dir.isDirectory()) { for (File f : dir.listFiles()) { String name = f.getName(); if (!running.contains(name)) { OSService s = new OSService(name, 0, STOPPED); services.add(s); } } } else { LOG.error("Directory: /etc/init does not exist"); } return services.toArray(new OSService[0]); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void populatePartitionMaps() { driveToPartitionMap.clear(); partitionToLogicalDriveMap.clear(); partitionMap.clear(); // For Regexp matching DeviceIDs Matcher mAnt; Matcher mDep; // Map drives to partitions Map<String, List<Object>> partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskDriveToDiskPartition", DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES); for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) { mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i)); mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i)); if (mAnt.matches() && mDep.matches()) { MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\")) .add(mDep.group(1)); } } // Map partitions to logical disks partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDiskToPartition", DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES); for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) { mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i)); mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i)); if (mAnt.matches() && mDep.matches()) { partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\"); } } // Next, get all partitions and create objects final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition", PARTITION_STRINGS, null, PARTITION_TYPES); for (int i = 0; i < hwPartitionQueryMap.get(WmiProperty.NAME.name()).size(); i++) { String deviceID = (String) hwPartitionQueryMap.get(WmiProperty.DEVICEID.name()).get(i); String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, ""); String uuid = ""; if (!logicalDrive.isEmpty()) { // Get matching volume for UUID char[] volumeChr = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE); uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), ""); } partitionMap .put(deviceID, new HWPartition( (String) hwPartitionQueryMap .get(WmiProperty.NAME.name()).get( i), (String) hwPartitionQueryMap.get(WmiProperty.TYPE.name()).get(i), (String) hwPartitionQueryMap.get(WmiProperty.DESCRIPTION.name()).get(i), uuid, (Long) hwPartitionQueryMap.get(WmiProperty.SIZE.name()).get(i), ((Long) hwPartitionQueryMap.get(WmiProperty.DISKINDEX.name()).get(i)).intValue(), ((Long) hwPartitionQueryMap.get(WmiProperty.INDEX.name()).get(i)).intValue(), logicalDrive)); } }
#vulnerable code private void populatePartitionMaps() { driveToPartitionMap.clear(); partitionToLogicalDriveMap.clear(); partitionMap.clear(); // For Regexp matching DeviceIDs Matcher mAnt; Matcher mDep; // Map drives to partitions Map<String, List<String>> partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDriveToDiskPartition", DRIVE_TO_PARTITION_PROPERTIES, null); for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) { mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i)); mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i)); if (mAnt.matches() && mDep.matches()) { MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\")) .add(mDep.group(1)); } } // Map partitions to logical disks partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_LogicalDiskToPartition", LOGICAL_DISK_TO_PARTITION_PROPERTIES, null); for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) { mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i)); mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i)); if (mAnt.matches() && mDep.matches()) { partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\"); } } // Next, get all partitions and create objects final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition", PARTITION_PROPERTIES, null, PARTITION_TYPES); for (int i = 0; i < hwPartitionQueryMap.get(NAME_PROPERTY).size(); i++) { String deviceID = (String) hwPartitionQueryMap.get(DEVICE_ID_PROPERTY).get(i); String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, ""); String uuid = ""; if (!logicalDrive.isEmpty()) { // Get matching volume for UUID char[] volumeChr = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE); uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), ""); } partitionMap.put(deviceID, new HWPartition((String) hwPartitionQueryMap.get(NAME_PROPERTY).get(i), (String) hwPartitionQueryMap.get(TYPE_PROPERTY).get(i), (String) hwPartitionQueryMap.get(DESCRIPTION_PROPERTY).get(i), uuid, ParseUtil.parseLongOrDefault((String) hwPartitionQueryMap.get(SIZE_PROPERTY).get(i), 0L), ((Long) hwPartitionQueryMap.get(DISK_INDEX_PROPERTY).get(i)).intValue(), ((Long) hwPartitionQueryMap.get(INDEX_PROPERTY).get(i)).intValue(), logicalDrive)); } } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes, WbemServices svc) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); int resultCount = 0; while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { // Enumerator will be released by calling method so no need to // release it here. LOG.debug(String.format("Returned %d results.", resultCount)); return; } resultCount++; VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; // hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; // uint16 == VT_I4, a 32-bit number case UINT16: values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.intValue()); break; // WMI Uint32s will return as longs case UINT32: values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.longValue()); break; // WMI Longs will return as strings so we have the option of // calling a string and parsing later, or calling UINT64 and // letting this method do the parsing case UINT64: values.get(property).add( vtProp.getValue() == null ? 0L : ParseUtil.parseLongOrDefault(vtProp.stringValue(), 0L)); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property) .add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; case BOOLEAN: values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.booleanValue()); break; case PROCESS_GETOWNER: // Win32_Process object GetOwner method String owner = FormatUtil.join("\\", execMethod(svc, vtProp.stringValue(), "GetOwner", "Domain", "User")); values.get(propertyType.name()).add("\\".equals(owner) ? "N/A" : owner); break; case PROCESS_GETOWNERSID: // Win32_Process object GetOwnerSid method String[] ownerSid = execMethod(svc, vtProp.stringValue(), "GetOwnerSid", "Sid"); values.get(propertyType.name()).add(ownerSid.length < 1 ? "" : ownerSid[0]); break; default: // Should never get here! If you get this exception you've // added something to the enum without adding it here. Tsk. throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp); } clsObj.Release(); } }
#vulnerable code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes, WbemServices svc) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { // Enumerator will be released by calling method so no need to // release it here. return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; // uint16 == VT_I4, a 32-bit number case UINT16: values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.intValue()); break; // WMI Uint32s will return as longs case UINT32: values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.longValue()); break; // WMI Longs will return as strings so we have the option of // calling a string and parsing later, or calling UINT64 and // letting this method do the parsing case UINT64: values.get(property).add( vtProp.getValue() == null ? 0L : ParseUtil.parseLongOrDefault(vtProp.stringValue(), 0L)); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property) .add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; case BOOLEAN: values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.booleanValue()); break; case PROCESS_GETOWNER: // Win32_Process object GetOwner method String owner = FormatUtil.join("\\", execMethod(svc, vtProp.stringValue(), "GetOwner", "Domain", "User")); values.get(propertyType.name()).add("\\".equals(owner) ? "N/A" : owner); break; case PROCESS_GETOWNERSID: // Win32_Process object GetOwnerSid method String[] ownerSid = execMethod(svc, vtProp.stringValue(), "GetOwnerSid", "Sid"); values.get(propertyType.name()).add(ownerSid.length < 1 ? "" : ownerSid[0]); break; default: // Should never get here! If you get this exception you've // added something to the enum without adding it here. Tsk. throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp); } clsObj.Release(); } } #location 30 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<OSFileStore> getWmiVolumes() { Map<String, List<Object>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES); for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) { free = (Long) drives.get(FREESPACE_PROPERTY).get(i); total = (Long) drives.get(SIZE_PROPERTY).get(i); String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i); String name = (String) drives.get(NAME_PROPERTY).get(i); long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name), (String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total)); } return fs; }
#vulnerable code private List<OSFileStore> getWmiVolumes() { Map<String, List<String>> drives; List<OSFileStore> fs; String volume; long free; long total; fs = new ArrayList<>(); drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk", "Name,Description,ProviderName,FileSystem,Freespace,Size", null); for (int i = 0; i < drives.get("Name").size(); i++) { free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L); total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L); String description = drives.get("Description").get(i); long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType", "WHERE Name = '" + drives.get("Name").get(i) + "'"); if (type != 4) { char[] chrVolume = new char[BUFSIZE]; Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume, BUFSIZE); volume = new String(chrVolume).trim(); } else { volume = drives.get("ProviderName").get(i); String[] split = volume.split("\\\\"); if (split.length > 1 && split[split.length - 1].length() > 0) { description = split[split.length - 1]; } } fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume, drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)), drives.get("FileSystem").get(i), "", free, total)); } return fs; } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static <T extends Enum<T>> Pair<List<String>, Map<T, List<Long>>> queryInstancesAndValues( Class<T> propertyEnum, String perfObject, String perfWmiClass) { // Check without locking for performance if (!failedQueryCache.contains(perfObject)) { failedQueryCacheLock.lock(); try { // Double check lock if (!failedQueryCache.contains(perfObject)) { Pair<List<String>, Map<T, List<Long>>> instancesAndValuesMap = queryInstancesAndValuesFromPDH( propertyEnum, perfObject); if (!instancesAndValuesMap.getA().isEmpty()) { return instancesAndValuesMap; } // If we are here, query failed LOG.warn("Disabling further attempts to query {}.", perfObject); failedQueryCache.add(perfObject); } } finally { failedQueryCacheLock.unlock(); } } return queryInstancesAndValuesFromWMI(propertyEnum, perfWmiClass); }
#vulnerable code public static <T extends Enum<T>> Pair<List<String>, Map<T, List<Long>>> queryInstancesAndValues( Class<T> propertyEnum, String perfObject, String perfWmiClass) { Pair<List<String>, Map<T, List<Long>>> instancesAndValuesMap = queryInstancesAndValuesFromPDH(propertyEnum, perfObject); if (instancesAndValuesMap.getA().isEmpty()) { return queryInstancesAndValuesFromWMI(propertyEnum, perfWmiClass); } return instancesAndValuesMap; } #location 3 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static UsbDevice[] getUsbDevices() { // Start by collecting information for all PNP devices. While in theory // these could be individually queried with a WHERE clause, grabbing // them all up front incurs minimal memory overhead in exchange for // faster access later // Clear maps nameMap.clear(); vendorMap.clear(); serialMap.clear(); // Query Win32_PnPEntity to populate the maps Map<String, List<String>> usbMap = WmiUtil.selectStringsFrom(null, "Win32_PnPEntity", "Name,Manufacturer,PnPDeviceID", null); for (int i = 0; i < usbMap.get("Name").size(); i++) { String pnpDeviceID = usbMap.get("PnPDeviceID").get(i); nameMap.put(pnpDeviceID, usbMap.get("Name").get(i)); if (usbMap.get("Manufacturer").get(i).length() > 0) { vendorMap.put(pnpDeviceID, usbMap.get("Manufacturer").get(i)); } } // Get serial # for disk drives or other physical media usbMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "PNPDeviceID,SerialNumber", null); for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { serialMap.put(usbMap.get("PNPDeviceID").get(i), ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); } usbMap = WmiUtil.selectStringsFrom(null, "Win32_PhysicalMedia", "PNPDeviceID,SerialNumber", null); for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { serialMap.put(usbMap.get("PNPDeviceID").get(i), ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); } // Build the device tree. Start with the USB Controllers // and recurse downward to devices as needed usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBController", "PNPDeviceID", null); List<UsbDevice> controllerDevices = new ArrayList<UsbDevice>(); for (String controllerDeviceId : usbMap.get("PNPDeviceID")) { putChildrenInDeviceTree(controllerDeviceId, 0); controllerDevices.add(getDeviceAndChildren(controllerDeviceId)); } return controllerDevices.toArray(new UsbDevice[controllerDevices.size()]); }
#vulnerable code public static UsbDevice[] getUsbDevices() { // Start by collecting information for all PNP devices. While in theory // these could be individually queried with a WHERE clause, grabbing // them all up front incurs minimal memory overhead in exchange for // faster access later // Clear maps nameMap.clear(); vendorMap.clear(); serialMap.clear(); // Query Win32_PnPEntity to populate the maps Map<String, List<String>> usbMap = WmiUtil.selectStringsFrom(null, "Win32_PnPEntity", "Name,Manufacturer,PnPDeviceID", null); for (int i = 0; i < usbMap.get("Name").size(); i++) { String pnpDeviceID = usbMap.get("PnPDeviceID").get(i); nameMap.put(pnpDeviceID, usbMap.get("Name").get(i)); if (usbMap.get("Manufacturer").get(i).length() > 0) { vendorMap.put(pnpDeviceID, usbMap.get("Manufacturer").get(i)); } String serialNumber = ""; // PNPDeviceID: USB\VID_203A&PID_FFF9&MI_00\6&18C4CF61&0&0000 // Split by \ to get bus type (USB), VendorID/ProductID, other info // As a temporary hack for a serial number, use last \-split field // using 2nd &-split field if 4 fields String[] idSplit = pnpDeviceID.split("\\\\"); if (idSplit.length > 2) { idSplit = idSplit[2].split("&"); if (idSplit.length > 3) { serialNumber = idSplit[1]; } } if (serialNumber.length() > 0) { serialMap.put(pnpDeviceID, serialNumber); } } // Disk drives or other physical media have a better way of getting // serial number. Grab these and overwrite the temporary serial number // assigned above if necessary usbMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "PNPDeviceID,SerialNumber", null); for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { serialMap.put(usbMap.get("PNPDeviceID").get(i), ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); } usbMap = WmiUtil.selectStringsFrom(null, "Win32_PhysicalMedia", "PNPDeviceID,SerialNumber", null); for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { serialMap.put(usbMap.get("PNPDeviceID").get(i), ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); } // Some USB Devices are hubs to which other devices connect. Knowing // which ones are hubs will help later when walking the device tree usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBHub", "PNPDeviceID", null); List<String> usbHubs = usbMap.get("PNPDeviceID"); // Now build the hub map linking USB devices with their parent hub. // At the top of the device tree are USB Controllers. All USB hubs and // devices descend from these. Because this query returns pointers it's // just not practical to try to query via COM so we use a command line // in order to get USB devices in a text format ArrayList<String> links = ExecutingCommand .runNative("wmic path Win32_USBControllerDevice GET Antecedent,Dependent"); // This iteration actually walks the device tree in order so while the // antecedent of all USB devices is its controller, we know that if a // device is not a hub that the last hub listed is its parent // Devices with PNPDeviceID containing "ROOTHUB" are special and will be // parents of the next item(s) // This won't id chained hubs (other than the root hub) but is a quick // hack rather than walking the entire device tree using the SetupDI API // and good enough since exactly how a USB device is connected is // theoretically transparent to the user hubMap.clear(); String currentHub = null; String rootHub = null; for (String s : links) { String[] split = s.split("\\s+"); if (split.length < 2) { continue; } String antecedent = getId(split[0]); String dependent = getId(split[1]); // Ensure initial defaults are sane if something goes wrong if (currentHub == null || rootHub == null) { currentHub = antecedent; rootHub = antecedent; } String parent; if (dependent.contains("ROOT_HUB")) { // This is a root hub, assign controller as parent; parent = antecedent; rootHub = dependent; currentHub = dependent; } else if (usbHubs.contains(dependent)) { // This is a hub, assign parent as root hub if (rootHub == null) { rootHub = antecedent; } parent = rootHub; currentHub = dependent; } else { // This is not a hub, assign parent as previous hub if (currentHub == null) { currentHub = antecedent; } parent = currentHub; } // Finally add the parent/child linkage to the map if (!hubMap.containsKey(parent)) { hubMap.put(parent, new ArrayList<String>()); } hubMap.get(parent).add(dependent); } // Finally we simply get the device IDs of the USB Controllers. These // will recurse downward to devices as needed usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBController", "PNPDeviceID", null); List<UsbDevice> controllerDevices = new ArrayList<UsbDevice>(); for (String controllerDeviceID : usbMap.get("PNPDeviceID")) { controllerDevices.add(getDeviceAndChildren(controllerDeviceID)); } return controllerDevices.toArray(new UsbDevice[controllerDevices.size()]); } #location 76 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public HWDiskStore[] getDisks() { List<HWDiskStore> result; result = new ArrayList<>(); readMap.clear(); writeMap.clear(); populateReadWriteMaps(); Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_DiskDrive", "Name,Manufacturer,Model,SerialNumber,Size,Index", null, DRIVE_TYPES); for (int i = 0; i < vals.get("Name").size(); i++) { HWDiskStore ds = new HWDiskStore(); ds.setName((String) vals.get("Name").get(i)); ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim()); // Most vendors store serial # as a hex string; convert ds.setSerial(ParseUtil.hexStringToString((String) vals.get("SerialNumber").get(i))); String index = vals.get("Index").get(i).toString(); if (readMap.containsKey(index)) { ds.setReads(readMap.get(index)); } if (writeMap.containsKey(index)) { ds.setWrites(writeMap.get(index)); } // If successful this line is the desired value try { ds.setSize(Long.parseLong((String) vals.get("Size").get(i))); } catch (NumberFormatException e) { // If we failed to parse, give up // This is expected for an empty string on some drives ds.setSize(0L); } result.add(ds); } return result.toArray(new HWDiskStore[result.size()]); }
#vulnerable code @Override public HWDiskStore[] getDisks() { List<HWDiskStore> result; result = new ArrayList<>(); Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "Name,Manufacturer,Model,SerialNumber,Size", null); for (int i = 0; i < vals.get("Name").size(); i++) { HWDiskStore ds = new HWDiskStore(); ds.setName(vals.get("Name").get(i)); ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim()); // Most vendors store serial # as a hex string; convert ds.setSerial(ParseUtil.hexStringToString(vals.get("SerialNumber").get(i))); // If successful this line is the desired value try { ds.setSize(Long.parseLong(vals.get("Size").get(i))); } catch (NumberFormatException e) { // If we failed to parse, give up // This is expected for an empty string on some drives ds.setSize(0L); } result.add(ds); } return result.toArray(new HWDiskStore[result.size()]); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static ArrayList<String> runNative(String cmdToRun) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRun); p.waitFor(); } catch (IOException e) { return null; } catch (InterruptedException e) { e.printStackTrace(); } BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line = ""; ArrayList<String> sa = new ArrayList<String>(); try { while ((line = reader.readLine()) != null) { sa.add(line); } } catch (IOException e) { return null; } return sa; }
#vulnerable code public static ArrayList<String> runNative(String cmdToRun) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRun); //p.waitFor(); } catch (IOException e) { return null; } BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line = ""; ArrayList<String> sa = new ArrayList<String>(); try { while ((line = reader.readLine()) != null) { sa.add(line); } } catch (IOException e) { return null; } p.destroy(); return sa; } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { // Enumerator will be released by calling method so no need to // release it here. return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { // WMI Longs will return as strings case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; // WMI Uint32s will return as longs case UINT32: // WinDef.LONG TODO improve in JNA 4.3 values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property) .add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; default: // Should never get here! If you get this exception you've // added something to the enum without adding it here. Tsk. throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); } clsObj.Release(); } }
#vulnerable code private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator, String[] properties, ValueType[] propertyTypes) { if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- PointerByReference pclsObj = new PointerByReference(); LongByReference uReturn = new LongByReference(0L); while (enumerator.getPointer() != Pointer.NULL) { HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), pclsObj, uReturn); // Requested 1; if 0 objects returned, we're done if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { // Enumerator will be released by calling method so no need to // release it here. return; } VARIANT.ByReference vtProp = new VARIANT.ByReference(); // Get the value of the properties WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); for (int p = 0; p < properties.length; p++) { String property = properties[p]; hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; switch (propertyType) { // WMI Longs will return as strings case STRING: values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); break; // WMI Uint32s will return as longs case UINT32: // WinDef.LONG TODO improve in JNA 4.3 values.get(property) .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); break; case FLOAT: values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); break; case DATETIME: // Read a string in format 20160513072950.782000-420 and // parse to a long representing ms since eopch values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); break; default: // Should never get here! If you get this exception you've // added something to the enum without adding it here. Tsk. throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); } OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); } clsObj.Release(); } } #location 36 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void updateSwap() { updateMeminfo(); this.swapUsed = PdhUtil.queryCounter(pdhPagingPercentUsageCounter) * this.pageSize; }
#vulnerable code @Override protected void updateSwap() { updateMeminfo(); Map<String, List<Long>> usage = WmiUtil.selectUint32sFrom(null, "Win32_PerfRawData_PerfOS_PagingFile", "PercentUsage,PercentUsage_Base", "WHERE Name=\"_Total\""); if (!usage.get("PercentUsage").isEmpty()) { this.swapUsed = this.swapTotal * usage.get("PercentUsage").get(0) / usage.get("PercentUsage_Base").get(0); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @SuppressWarnings("unchecked") public void chainArray() { final List<Map<String, Object>> stooges = new ArrayList<Map<String, Object>>() { { add(new LinkedHashMap<String, Object>() { { put("name", "curly"); put("age", 25); } }); add(new LinkedHashMap<String, Object>() { { put("name", "moe"); put("age", 21); } }); add(new LinkedHashMap<String, Object>() { { put("name", "larry"); put("age", 23); } }); } }; final String youngest = $.chain($.toArray(stooges)) .sortBy( new Function1<Map<String, Object>, Integer>() { public Integer apply(Map<String, Object> item) { return (Integer) item.get("age"); } }) .map( new Function1<Map<String, Object>, String>() { public String apply(Map<String, Object> item) { return item.get("name") + " is " + item.get("age"); } }) .first().item().toString(); assertEquals("moe is 21", youngest); }
#vulnerable code @Test @SuppressWarnings("unchecked") public void chainArray() { final List<Map<String, Object>> stooges = new ArrayList<Map<String, Object>>() { { add(new LinkedHashMap<String, Object>() { { put("name", "curly"); put("age", 25); } }); add(new LinkedHashMap<String, Object>() { { put("name", "moe"); put("age", 21); } }); add(new LinkedHashMap<String, Object>() { { put("name", "larry"); put("age", 23); } }); } }; final String youngest = $.chain(stooges.toArray()) .sortBy( new Function1<Map<String, Object>, Integer>() { public Integer apply(Map<String, Object> item) { return (Integer) item.get("age"); } }) .map( new Function1<Map<String, Object>, String>() { public String apply(Map<String, Object> item) { return item.get("name") + " is " + item.get("age"); } }) .first().item().toString(); assertEquals("moe is 21", youngest); } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void find() { final Optional<Integer> result = _.find(asList(1, 2, 3, 4, 5, 6), new Predicate<Integer>() { public Boolean apply(Integer item) { return item % 2 == 0; } }); assertEquals("Optional.of(2)", result.toString()); }
#vulnerable code @Test public void find() { final Integer result = _.find(asList(1, 2, 3, 4, 5, 6), new Predicate<Integer>() { public Boolean apply(Integer item) { return item % 2 == 0; } }); assertEquals("2", result.toString()); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.