input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Override public void consistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
for (IntVar e : x)
if (e.min() == 1)
numberOnes++;
else if (e.max() != 0)
nonGround = e;
int numberZeros = 0;
for (IntVar e : x)
if (e.max() == 0)
numberZeros++;
else if (e.min() != 1)
nonGround = e;
if (numberOnes + numberZeros == l)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 1, 1);
else
y.domain.in(store.level, y, 0, 0);
else if (numberOnes + numberZeros == l - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
}
#location 29
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override public void consistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
int numberZeros = 0;
for (IntVar e : x) {
if (e.min() == 1)
numberOnes++;
else if (e.max() == 0)
numberZeros++;
else nonGround = e;
}
if (numberOnes + numberZeros == x.length)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 1, 1);
else
y.domain.in(store.level, y, 0, 0);
else if (nonGround != null && numberOnes + numberZeros == x.length - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override public ArrayList<Constraint> decompose(Store store) {
if (constraints != null)
return constraints;
IntDomain setComplement = new IntervalDomain();
for (IntVar var : list)
setComplement.addDom(var.domain);
setComplement = setComplement.subtract(set);
FSM fsm = new FSM();
fsm.initState = new FSMState();
fsm.allStates.add(fsm.initState);
HashMap<FSMState, Integer> mappingQuantity = new HashMap<FSMState, Integer>();
HashMap<String, FSMState> mappingString = new HashMap<String, FSMState>();
mappingQuantity.put(fsm.initState, 0);
mappingString.put("", fsm.initState);
for (int i = 0; i < q; i++) {
HashMap<String, FSMState> mappingStringNext = new HashMap<String, FSMState>();
for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) {
String stateString = entry.getKey();
FSMState state = entry.getValue();
if (mappingQuantity.get(state) < max) {
// transition 1 (within a set) is allowed
FSMState nextState = new FSMState();
state.addTransition(new FSMTransition(set, nextState));
mappingStringNext.put(stateString + "1", nextState);
mappingQuantity.put(nextState, mappingQuantity.get(state) + 1);
}
if (mappingQuantity.get(state) + (q - i) > min) {
// transition 0 (outside set) is allowed
FSMState nextState = new FSMState();
state.addTransition(new FSMTransition(setComplement, nextState));
mappingStringNext.put(stateString + "0", nextState);
mappingQuantity.put(nextState, mappingQuantity.get(state));
}
}
fsm.allStates.addAll(mappingString.values());
mappingString = mappingStringNext;
}
fsm.allStates.addAll(mappingString.values());
fsm.finalStates.addAll(mappingString.values());
for (String description : mappingString.keySet()) {
String one = description.substring(1) + "1";
FSMState predecessor = mappingString.get(description);
FSMState successor = mappingString.get(one);
if (successor != null)
predecessor.addTransition(new FSMTransition(set, successor));
String zero = description.substring(1) + "0";
successor = mappingString.get(zero);
if (successor != null)
predecessor.addTransition(new FSMTransition(setComplement, successor));
}
fsm.resize();
constraints = new ArrayList<Constraint>();
constraints.add(new Regular(fsm, list));
return constraints;
}
#location 61
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override public ArrayList<Constraint> decompose(Store store) {
if (constraints != null)
return constraints;
IntDomain setComplement = new IntervalDomain();
for (IntVar var : list)
setComplement.addDom(var.domain);
setComplement = setComplement.subtract(set);
FSM fsm = new FSM();
fsm.initState = new FSMState();
fsm.allStates.add(fsm.initState);
HashMap<FSMState, Integer> mappingQuantity = new HashMap<FSMState, Integer>();
HashMap<String, FSMState> mappingString = new HashMap<String, FSMState>();
mappingQuantity.put(fsm.initState, 0);
mappingString.put("", fsm.initState);
for (int i = 0; i < q; i++) {
HashMap<String, FSMState> mappingStringNext = new HashMap<String, FSMState>();
for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) {
String stateString = entry.getKey();
FSMState state = entry.getValue();
if (mappingQuantity.get(state) < max) {
// transition 1 (within a set) is allowed
FSMState nextState = new FSMState();
state.addTransition(new FSMTransition(set, nextState));
mappingStringNext.put(stateString + "1", nextState);
mappingQuantity.put(nextState, mappingQuantity.get(state) + 1);
}
if (mappingQuantity.get(state) + (q - i) > min) {
// transition 0 (outside set) is allowed
FSMState nextState = new FSMState();
state.addTransition(new FSMTransition(setComplement, nextState));
mappingStringNext.put(stateString + "0", nextState);
mappingQuantity.put(nextState, mappingQuantity.get(state));
}
}
fsm.allStates.addAll(mappingString.values());
mappingString = mappingStringNext;
}
fsm.allStates.addAll(mappingString.values());
fsm.finalStates.addAll(mappingString.values());
for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) {
String description = entry.getKey();
FSMState state = entry.getValue();
String one = description.substring(1) + "1";
FSMState predecessor = state;
FSMState successor = mappingString.get(one);
if (successor != null)
predecessor.addTransition(new FSMTransition(set, successor));
String zero = description.substring(1) + "0";
successor = mappingString.get(zero);
if (successor != null)
predecessor.addTransition(new FSMTransition(setComplement, successor));
}
fsm.resize();
constraints = new ArrayList<Constraint>();
constraints.add(new Regular(fsm, list));
return constraints;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Parameterized.Parameters
public static Collection<String> parametricTest() throws IOException {
FileReader file = new FileReader(relativePath + timeCategory + listFileName);
BufferedReader br = new BufferedReader(file);
String line = "";
List<String> list = new ArrayList<String>();
int i = 0;
while ((line = br.readLine())!=null) {
list.add(i, line);
i++;
}
return list;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Parameterized.Parameters
public static Collection<String> parametricTest() throws IOException {
return fileReader(timeCategory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void prepareVizHeader() {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(new FileOutputStream(visFilename));
} catch (FileNotFoundException e) {
e.printStackTrace();
printWriter = new PrintWriter(new StringWriter());
}
StreamResult streamResult = new StreamResult(printWriter);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
try {
hdVis = tf.newTransformerHandler();
Transformer serializer = hdVis.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // "ISO-8859-1");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
hdVis.setResult(streamResult);
hdVis.startDocument();
AttributesImpl atts = new AttributesImpl();
atts.addAttribute("", "", "version", "CDATA", "1.0");
atts.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
atts.addAttribute("", "", "xsi:noNamespaceSchemaLocation", "CDATA", "visualization.xsd");
String ourText = " Generated by JaCoP solver; " + getDateTime() + " ";
char[] comm = ourText.toCharArray();
hdVis.comment(comm, 0, comm.length);
hdVis.startElement("", "", "visualization", atts);
// visualizer
if (tracedVar.size() != 0) {
AttributesImpl visAtt = new AttributesImpl();
visAtt.addAttribute("", "", "id", "CDATA", "1");
visAtt.addAttribute("", "", "type", "CDATA", "vector");
visAtt.addAttribute("", "", "display", "CDATA", "expanded");
visAtt.addAttribute("", "", "group", "CDATA", "default");
visAtt.addAttribute("", "", "x", "CDATA", "0");
visAtt.addAttribute("", "", "y", "CDATA", "0");
int minV = minValue(tracedVar), maxV = maxValue(tracedVar);
visAtt.addAttribute("", "", "width", "CDATA", "" + tracedVar.size());
visAtt.addAttribute("", "", "height", "CDATA", "" + (int) (maxV - minV + 1));
visAtt.addAttribute("", "", "min", "CDATA", "" + minV);
visAtt.addAttribute("", "", "max", "CDATA", "" + maxV);
hdVis.startElement("", "", "visualizer", visAtt);
hdVis.endElement("", "", "visualizer");
}
generateVisualizationNode(0, true);
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
void prepareTreeHeader() {
OutputStreamWriter printWriter;
try {
printWriter = new OutputStreamWriter(
new FileOutputStream(treeFilename),
Charset.forName("UTF-8").newEncoder()
);
} catch (FileNotFoundException e) {
e.printStackTrace();
printWriter = new OutputStreamWriter(
System.out,
Charset.forName("UTF-8").newEncoder()
);
}
StreamResult streamResult = new StreamResult(printWriter);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
try {
hdTree = tf.newTransformerHandler();
Transformer serializer = hdTree.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // "ISO-8859-1");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
hdTree.setResult(streamResult);
hdTree.startDocument();
AttributesImpl atts = new AttributesImpl();
atts.addAttribute("", "", "version", "CDATA", "1.0");
atts.addAttribute("", "", "xmln:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
atts.addAttribute("", "", "xsi:noNamespaceSchemaLocation", "CDATA", "tree.xsd");
String ourText = " Generated by JaCoP solver; " + getDateTime() + " ";
char[] comm = ourText.toCharArray();
hdTree.comment(comm, 0, comm.length);
hdTree.startElement("", "", "tree", atts);
atts = new AttributesImpl();
atts.addAttribute("", "", "id", "CDATA", "0");
hdTree.startElement("", "", "root", atts);
hdTree.endElement("", "", "root");
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void run_sequence_search(int solveKind, SimpleNode kind, SearchItem si) {
singleSearch = false;
//kind.dump("");
this.si = si;
if (options.getVerbose()) {
String solve = "notKnown";
switch (solveKind) {
case 0:
solve = "%% satisfy";
break; // satisfy
case 1:
Var costMin = (getCost((ASTSolveExpr) kind.jjtGetChild(0)) != null) ?
getCost((ASTSolveExpr) kind.jjtGetChild(0)) :
getCostFloat((ASTSolveExpr) kind.jjtGetChild(0));
solve = "%% minimize(" + costMin + ") ";
minimize = true;
break; // minimize
case 2:
Var costMax = (getCost((ASTSolveExpr) kind.jjtGetChild(0)) != null) ?
getCost((ASTSolveExpr) kind.jjtGetChild(0)) :
getCostFloat((ASTSolveExpr) kind.jjtGetChild(0));
solve = "%% maximize(" + costMax + ") ";
break; // maximize
default:
throw new RuntimeException("Internal error in " + getClass().getName());
}
System.out.println(solve + " : " + si);
}
DepthFirstSearch<Var> masterLabel = null;
DepthFirstSearch<Var> last_search = null;
SelectChoicePoint<Var> masterSelect = null;
list_seq_searches = new ArrayList<Search<Var>>();
for (int i = 0; i < si.getSearchItems().size(); i++) {
if (i == 0) { // master search
masterLabel = sub_search(si.getSearchItems().get(i), masterLabel, true);
last_search = getLastSearch(masterLabel);
masterSelect = variable_selection;
if (!print_search_info)
masterLabel.setPrintInfo(false);
} else {
DepthFirstSearch<Var> label = sub_search(si.getSearchItems().get(i), last_search, false);
last_search.addChildSearch(label);
last_search = getLastSearch(label);
if (!print_search_info)
last_search.setPrintInfo(false);
}
}
DepthFirstSearch<Var>[] complementary_search = setSubSearchForAll(last_search, options);
for (DepthFirstSearch<Var> aComplementary_search : complementary_search) {
if (aComplementary_search != null) {
list_seq_searches.add(aComplementary_search);
if (!print_search_info)
aComplementary_search.setPrintInfo(false);
}
}
Result = false;
Var cost = null;
Var max_cost = null;
optimization = false;
final_search_seq = list_seq_searches.get(list_seq_searches.size() - 1);
long currentTime = timer.getCPUTime();
initTime = currentTime - startCPU;
startCPU = currentTime;
int to = options.getTimeOut();
if (to > 0)
for (Search s : list_seq_searches)
s.setTimeOutMilliseconds(to);
int ns = options.getNumberSolutions();
if (si.exploration() == null || si.exploration().equals("complete"))
switch (solveKind) {
case 0: // satisfy
FloatDomain.intervalPrint(options.getInterval()); // print intervals for float variables
if (options.getAll()) { // all solutions
if (restartCalculator != null)
throw new IllegalArgumentException("Flatzinc option for search for all solutions (-a) cannot be used in restart search.");
for (int i = 0; i < si.getSearchItems().size(); i++) { //list_seq_searches.size(); i++) {
list_seq_searches.get(i).getSolutionListener().searchAll(true);
list_seq_searches.get(i).getSolutionListener().recordSolutions(false);
if (ns > 0)
list_seq_searches.get(i).getSolutionListener().setSolutionLimit(ns);
}
}
if (options.runSearch())
if (restartCalculator != null) {
label = masterLabel;
rs = new RestartSearch<>(store, masterLabel, masterSelect, restartCalculator);
Result = rs.labeling();
}
else {
label = masterLabel;
Result = masterLabel.labeling(store, masterSelect);
}
else {
// storing flatiznc defined search
flatzincDFS = masterLabel;
flatzincVariableSelection = masterSelect;
flatzincCost = null;
return;
}
break;
case 1: // minimize
optimization = true;
FloatDomain.intervalPrint(options.getInterval()); // print intervals for float variables
cost = getCost((ASTSolveExpr) kind.jjtGetChild(0));
if (cost != null)
costVariable = cost;
else {
cost = getCostFloat((ASTSolveExpr) kind.jjtGetChild(0));
costVariable = cost;
}
// Result = restart_search(masterLabel, masterSelect, cost, true);
for (Search<Var> list_seq_searche : list_seq_searches)
list_seq_searche.setOptimize(true);
if (ns > 0) {
for (int i = 0; i < list_seq_searches.size() - 1; i++) {
((DepthFirstSearch) list_seq_searches.get(i)).respectSolutionListenerAdvice = true;
((DepthFirstSearch) list_seq_searches.get(i)).getSolutionListener().setSolutionLimit(ns);
}
final_search_seq.getSolutionListener().setSolutionLimit(ns);
((DepthFirstSearch) final_search_seq).respectSolutionListenerAdvice = true;
}
if (options.runSearch())
if (restartCalculator != null) {
label = masterLabel;
rs = new RestartSearch<>(store, masterLabel, masterSelect, restartCalculator, cost);
Result = rs.labeling();
}
else {
label = masterLabel;
Result = masterLabel.labeling(store, masterSelect, cost);
}
else {
// storing flatiznc defined search
flatzincDFS = masterLabel;
flatzincVariableSelection = masterSelect;
flatzincCost = cost;
return;
}
break;
case 2: //maximize
optimization = true;
// cost = getCost((ASTSolveExpr)kind.jjtGetChild(0));
FloatDomain.intervalPrint(options.getInterval()); // print intervals for float variables
cost = getCost((ASTSolveExpr) kind.jjtGetChild(0));
if (cost != null) { // maximize
max_cost = new IntVar(store, "-" + cost.id(), IntDomain.MinInt, IntDomain.MaxInt);
pose(new XplusYeqC((IntVar) max_cost, (IntVar) cost, 0));
costVariable = max_cost;
} else {
cost = getCostFloat((ASTSolveExpr) kind.jjtGetChild(0));
max_cost = new FloatVar(store, "-" + cost.id(), VariablesParameters.MIN_FLOAT, VariablesParameters.MAX_FLOAT);
pose(new PplusQeqR((FloatVar) max_cost, (FloatVar) cost, new FloatVar(store, 0.0, 0.0)));
costVariable = max_cost;
}
// Result = restart_search(masterLabel, masterSelect, cost, false);
for (Search<Var> list_seq_searche : list_seq_searches)
list_seq_searche.setOptimize(true);
if (ns > 0) {
for (int i = 0; i < list_seq_searches.size() - 1; i++)
((DepthFirstSearch) list_seq_searches.get(i)).respectSolutionListenerAdvice = true;
final_search_seq.getSolutionListener().setSolutionLimit(ns);
((DepthFirstSearch) final_search_seq).respectSolutionListenerAdvice = true;
}
if (options.runSearch())
if (restartCalculator != null) {
label = masterLabel;
rs = new RestartSearch<>(store, masterLabel, masterSelect, restartCalculator, max_cost);
Result = rs.labeling();
}
else {
label = masterLabel;
Result = masterLabel.labeling(store, masterSelect, max_cost);
}
else {
// storing flatiznc defined search
flatzincDFS = masterLabel;
flatzincVariableSelection = masterSelect;
flatzincCost = max_cost;
return;
}
break;
}
else {
throw new IllegalArgumentException(
"Not recognized or supported " + si.exploration() + " search explorarion strategy ; compilation aborted");
}
if (!options.getAll() && lastSolution != null)
helperSolutionPrinter(lastSolution.toString());
printStatisticsForSeqSearch(false, Result);
}
#location 149
#vulnerability type NULL_DEREFERENCE | #fixed code
ArrayList<SearchItem> parseSearchAnnotations(ArrayList<SearchItem> search_seq) {
ArrayList<SearchItem> ns = new ArrayList<SearchItem>();
for (SearchItem s : search_seq)
if (s.search_type.equals("restart_none"))
continue;
else if (s.search_type.equals("restart_constant") || s.search_type.equals("restart_linear") || s.search_type.equals("restart_geometric") ||
s.search_type.equals("restart_luby"))
restartCalculator = s.restartCalculator;
else if (s.search_type.endsWith("_search"))// && !s.search_type.equals("priority_search"))
ns.add(s);
else
System.out.println("%% Warning: Not supported search annotation: "+s.search_type+"; ignored.");
return ns;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override public void notConsistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
for (IntVar e : x)
if (e.min() == 1)
numberOnes++;
else if (e.max() != 0)
nonGround = e;
int numberZeros = 0;
for (IntVar e : x)
if (e.max() == 0)
numberZeros++;
else if (e.min() != 1)
nonGround = e;
if (numberOnes + numberZeros == l)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 0, 0);
else
y.domain.in(store.level, y, 1, 1);
else if (numberOnes + numberZeros == l - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override public void notConsistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
int numberZeros = 0;
for (IntVar e : x) {
if (e.min() == 1)
numberOnes++;
else if (e.max() == 0)
numberZeros++;
else nonGround = e;
}
if (numberOnes + numberZeros == x.length)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 0, 0);
else
y.domain.in(store.level, y, 1, 1);
else if (nonGround != null && numberOnes + numberZeros == x.length - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String[] readFile(String file) {
ArrayList<String> result = new ArrayList<String>();
System.out.println("readFile(" + file + ")");
try {
BufferedReader inr = new BufferedReader(new FileReader(file));
String str;
while ((str = inr.readLine()) != null && str.length() > 0) {
str = str.trim();
// ignore comments
if (str.startsWith("#") || str.startsWith("%")) {
continue;
}
result.add(str);
} // end while
inr.close();
} catch (IOException e) {
System.out.println(e);
}
return result.toArray(new String[result.size()]);
}
#location 27
#vulnerability type RESOURCE_LEAK | #fixed code
public static String[] readFile(String file) {
ArrayList<String> result = new ArrayList<String>();
System.out.println("readFile(" + file + ")");
try {
BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String str;
while ((str = inr.readLine()) != null && str.length() > 0) {
str = str.trim();
// ignore comments
if (str.startsWith("#") || str.startsWith("%")) {
continue;
}
result.add(str);
} // end while
inr.close();
} catch (IOException e) {
System.out.println(e);
}
return result.toArray(new String[result.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override public void notConsistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
for (IntVar e : x)
if (e.min() == 1)
numberOnes++;
else if (e.max() != 0)
nonGround = e;
int numberZeros = 0;
for (IntVar e : x)
if (e.max() == 0)
numberZeros++;
else if (e.min() != 1)
nonGround = e;
if (numberOnes + numberZeros == l)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 0, 0);
else
y.domain.in(store.level, y, 1, 1);
else if (numberOnes + numberZeros == l - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
}
#location 29
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override public void notConsistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
int numberZeros = 0;
for (IntVar e : x) {
if (e.min() == 1)
numberOnes++;
else if (e.max() == 0)
numberZeros++;
else nonGround = e;
}
if (numberOnes + numberZeros == x.length)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 0, 0);
else
y.domain.in(store.level, y, 1, 1);
else if (nonGround != null && numberOnes + numberZeros == x.length - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public int countWatches() {
if (watchedConstraints == null)
return 0;
int count = 0;
for (Var v : watchedConstraints.keySet())
count += watchedConstraints.get(v).size();
return count;
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public int countWatches() {
if (watchedConstraints == null)
return 0;
int count = 0;
for (HashSet<Constraint> c : watchedConstraints.values())
count += c.size();
return count;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public FloatVar[] getVariableFloatArray(String ident) {
FloatVar[] a = variableFloatArrayTable.get(ident);
if (a == null) {
double[] floatA = floatArrayTable.get(ident);
a = new FloatVar[floatA.length];
for (int i = 0; i < floatA.length; i++) {
a[i] = new FloatVar(store, floatA[i], floatA[i]);
}
}
return a;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public FloatVar[] getVariableFloatArray(String ident) {
FloatVar[] a = variableFloatArrayTable.get(ident);
if (a == null) {
double[] floatA = floatArrayTable.get(ident);
if (floatA != null) {
a = new FloatVar[floatA.length];
for (int i = 0; i < floatA.length; i++) {
a[i] = new FloatVar(store, floatA[i], floatA[i]);
}
}
else
throw new IllegalArgumentException("Array identifier does not exist: " + ident);
}
return a;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override public void consistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
for (IntVar e : x)
if (e.min() == 1)
numberOnes++;
else if (e.max() != 0)
nonGround = e;
int numberZeros = 0;
for (IntVar e : x)
if (e.max() == 0)
numberZeros++;
else if (e.min() != 1)
nonGround = e;
if (numberOnes + numberZeros == l)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 1, 1);
else
y.domain.in(store.level, y, 0, 0);
else if (numberOnes + numberZeros == l - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override public void consistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
int numberZeros = 0;
for (IntVar e : x) {
if (e.min() == 1)
numberOnes++;
else if (e.max() == 0)
numberZeros++;
else nonGround = e;
}
if (numberOnes + numberZeros == x.length)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 1, 1);
else
y.domain.in(store.level, y, 0, 0);
else if (nonGround != null && numberOnes + numberZeros == x.length - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override public void notConsistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
for (IntVar e : x)
if (e.min() == 1)
numberOnes++;
else if (e.max() != 0)
nonGround = e;
int numberZeros = 0;
for (IntVar e : x)
if (e.max() == 0)
numberZeros++;
else if (e.min() != 1)
nonGround = e;
if (numberOnes + numberZeros == l)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 0, 0);
else
y.domain.in(store.level, y, 1, 1);
else if (numberOnes + numberZeros == l - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override public void notConsistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
int numberZeros = 0;
for (IntVar e : x) {
if (e.min() == 1)
numberOnes++;
else if (e.max() == 0)
numberZeros++;
else nonGround = e;
}
if (numberOnes + numberZeros == x.length)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 0, 0);
else
y.domain.in(store.level, y, 1, 1);
else if (nonGround != null && numberOnes + numberZeros == x.length - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void readDictionaryFromFile(String file, List<Integer> wordSizes) {
for (int wordSize : wordSizes) {
int wordCount = 0;
IntVar[] list = new IntVar[wordSize];
for (int i = 0; i < wordSize; i++)
list[i] = blank;
int[] tupleForGivenWord = new int[wordSize];
MDD resultForWordSize = new MDD(list);
try {
BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String str;
while ((str = inr.readLine()) != null && str.length() > 0) {
str = str.trim();
// ignore comments
// starting with either # or %
if (str.startsWith("#") || str.startsWith("%")) {
continue;
}
if (str.length() != wordSize)
continue;
for (int i = 0; i < wordSize; i++) {
tupleForGivenWord[i] = mapping.get(str.substring(i, i + 1));
}
wordCount++;
resultForWordSize.addTuple(tupleForGivenWord);
// lineCount++;
} // end while
inr.close();
} catch (IOException e) {
System.out.println(e);
}
System.out.println("There are " + wordCount + " words of size " + wordSize);
resultForWordSize.reduce();
mdds.put(wordSize, resultForWordSize);
}
}
#location 45
#vulnerability type RESOURCE_LEAK | #fixed code
public void readDictionaryFromFile(String file, List<Integer> wordSizes) {
for (int wordSize : wordSizes) {
int wordCount = 0;
IntVar[] list = new IntVar[wordSize];
for (int i = 0; i < wordSize; i++)
list[i] = blank;
int[] tupleForGivenWord = new int[wordSize];
MDD resultForWordSize = new MDD(list);
try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
String str;
while ((str = inr.readLine()) != null && str.length() > 0) {
str = str.trim();
// ignore comments
// starting with either # or %
if (str.startsWith("#") || str.startsWith("%")) {
continue;
}
if (str.length() != wordSize)
continue;
for (int i = 0; i < wordSize; i++) {
tupleForGivenWord[i] = mapping.get(str.substring(i, i + 1));
}
wordCount++;
resultForWordSize.addTuple(tupleForGivenWord);
// lineCount++;
} // end while
inr.close();
} catch (IOException e) {
System.out.println(e);
}
System.out.println("There are " + wordCount + " words of size " + wordSize);
resultForWordSize.reduce();
mdds.put(wordSize, resultForWordSize);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override public ArrayList<Constraint> decompose(Store store) {
if (constraints != null)
return constraints;
IntDomain setComplement = new IntervalDomain();
for (IntVar var : list)
setComplement.addDom(var.domain);
setComplement = setComplement.subtract(set);
FSM fsm = new FSM();
fsm.initState = new FSMState();
fsm.allStates.add(fsm.initState);
HashMap<FSMState, Integer> mappingQuantity = new HashMap<FSMState, Integer>();
HashMap<String, FSMState> mappingString = new HashMap<String, FSMState>();
mappingQuantity.put(fsm.initState, 0);
mappingString.put("", fsm.initState);
for (int i = 0; i < q; i++) {
HashMap<String, FSMState> mappingStringNext = new HashMap<String, FSMState>();
for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) {
String stateString = entry.getKey();
FSMState state = entry.getValue();
if (mappingQuantity.get(state) < max) {
// transition 1 (within a set) is allowed
FSMState nextState = new FSMState();
state.addTransition(new FSMTransition(set, nextState));
mappingStringNext.put(stateString + "1", nextState);
mappingQuantity.put(nextState, mappingQuantity.get(state) + 1);
}
if (mappingQuantity.get(state) + (q - i) > min) {
// transition 0 (outside set) is allowed
FSMState nextState = new FSMState();
state.addTransition(new FSMTransition(setComplement, nextState));
mappingStringNext.put(stateString + "0", nextState);
mappingQuantity.put(nextState, mappingQuantity.get(state));
}
}
fsm.allStates.addAll(mappingString.values());
mappingString = mappingStringNext;
}
fsm.allStates.addAll(mappingString.values());
fsm.finalStates.addAll(mappingString.values());
for (String description : mappingString.keySet()) {
String one = description.substring(1) + "1";
FSMState predecessor = mappingString.get(description);
FSMState successor = mappingString.get(one);
if (successor != null)
predecessor.addTransition(new FSMTransition(set, successor));
String zero = description.substring(1) + "0";
successor = mappingString.get(zero);
if (successor != null)
predecessor.addTransition(new FSMTransition(setComplement, successor));
}
fsm.resize();
constraints = new ArrayList<Constraint>();
constraints.add(new Regular(fsm, list));
return constraints;
}
#location 66
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override public ArrayList<Constraint> decompose(Store store) {
if (constraints != null)
return constraints;
IntDomain setComplement = new IntervalDomain();
for (IntVar var : list)
setComplement.addDom(var.domain);
setComplement = setComplement.subtract(set);
FSM fsm = new FSM();
fsm.initState = new FSMState();
fsm.allStates.add(fsm.initState);
HashMap<FSMState, Integer> mappingQuantity = new HashMap<FSMState, Integer>();
HashMap<String, FSMState> mappingString = new HashMap<String, FSMState>();
mappingQuantity.put(fsm.initState, 0);
mappingString.put("", fsm.initState);
for (int i = 0; i < q; i++) {
HashMap<String, FSMState> mappingStringNext = new HashMap<String, FSMState>();
for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) {
String stateString = entry.getKey();
FSMState state = entry.getValue();
if (mappingQuantity.get(state) < max) {
// transition 1 (within a set) is allowed
FSMState nextState = new FSMState();
state.addTransition(new FSMTransition(set, nextState));
mappingStringNext.put(stateString + "1", nextState);
mappingQuantity.put(nextState, mappingQuantity.get(state) + 1);
}
if (mappingQuantity.get(state) + (q - i) > min) {
// transition 0 (outside set) is allowed
FSMState nextState = new FSMState();
state.addTransition(new FSMTransition(setComplement, nextState));
mappingStringNext.put(stateString + "0", nextState);
mappingQuantity.put(nextState, mappingQuantity.get(state));
}
}
fsm.allStates.addAll(mappingString.values());
mappingString = mappingStringNext;
}
fsm.allStates.addAll(mappingString.values());
fsm.finalStates.addAll(mappingString.values());
for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) {
String description = entry.getKey();
FSMState state = entry.getValue();
String one = description.substring(1) + "1";
FSMState predecessor = state;
FSMState successor = mappingString.get(one);
if (successor != null)
predecessor.addTransition(new FSMTransition(set, successor));
String zero = description.substring(1) + "0";
successor = mappingString.get(zero);
if (successor != null)
predecessor.addTransition(new FSMTransition(setComplement, successor));
}
fsm.resize();
constraints = new ArrayList<Constraint>();
constraints.add(new Regular(fsm, list));
return constraints;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Parameterized.Parameters
public static Collection<String> parametricTest() throws IOException {
FileReader file = new FileReader(relativePath + timeCategory + listFileName);
BufferedReader br = new BufferedReader(file);
String line = "";
List<String> list = new ArrayList<String>();
int i = 0;
while ((line = br.readLine())!=null) {
list.add(i, line);
i++;
}
return list;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Parameterized.Parameters
public static Collection<String> parametricTest() throws IOException {
return fileReader(timeCategory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void filterDomains() {
for (int i = 0; i < x.length; i++) {
int xIndex = varMap.get(x[i]);
Map<Integer,long[]> xSupport = supports[xIndex];
ValueEnumeration e = x[i].dom().valueEnumeration();
while (e.hasMoreElements()) {
int el = e.nextElement();
Integer indexInteger = residues[i].get(el);
if (indexInteger == null) {
x[i].domain.inComplement(store.level, x[i], el);
continue;
}
int index = indexInteger.intValue();
long[] bs = xSupport.get(el);
if (bs != null) {
if ((rbs.words[index].value() & xSupport.get(el)[index]) == 0L) {
index = rbs.intersectIndex(bs);
if (index == -1)
x[i].domain.inComplement(store.level, x[i], el);
else
residues[i].put(el, index);
}
} else
x[i].domain.inComplement(store.level, x[i], el);
}
}
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
void init() {
int n = tuple.length;
rbs = new ReversibleSparseBitSet(store, x, tuple);
makeSupport();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override public void consistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
for (IntVar e : x)
if (e.min() == 1)
numberOnes++;
else if (e.max() != 0)
nonGround = e;
int numberZeros = 0;
for (IntVar e : x)
if (e.max() == 0)
numberZeros++;
else if (e.min() != 1)
nonGround = e;
if (numberOnes + numberZeros == l)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 1, 1);
else
y.domain.in(store.level, y, 0, 0);
else if (numberOnes + numberZeros == l - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override public void consistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
int numberZeros = 0;
for (IntVar e : x) {
if (e.min() == 1)
numberOnes++;
else if (e.max() == 0)
numberZeros++;
else nonGround = e;
}
if (numberOnes + numberZeros == x.length)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 1, 1);
else
y.domain.in(store.level, y, 0, 0);
else if (nonGround != null && numberOnes + numberZeros == x.length - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void prepareTreeHeader() {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(new FileOutputStream(treeFilename));
} catch (FileNotFoundException e) {
e.printStackTrace();
printWriter = new PrintWriter(new StringWriter());
}
StreamResult streamResult = new StreamResult(printWriter);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
try {
hdTree = tf.newTransformerHandler();
Transformer serializer = hdTree.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // "ISO-8859-1");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
hdTree.setResult(streamResult);
hdTree.startDocument();
AttributesImpl atts = new AttributesImpl();
atts.addAttribute("", "", "version", "CDATA", "1.0");
atts.addAttribute("", "", "xmln:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
atts.addAttribute("", "", "xsi:noNamespaceSchemaLocation", "CDATA", "tree.xsd");
String ourText = " Generated by JaCoP solver; " + getDateTime() + " ";
char[] comm = ourText.toCharArray();
hdTree.comment(comm, 0, comm.length);
hdTree.startElement("", "", "tree", atts);
atts = new AttributesImpl();
atts.addAttribute("", "", "id", "CDATA", "0");
hdTree.startElement("", "", "root", atts);
hdTree.endElement("", "", "root");
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
void prepareTreeHeader() {
OutputStreamWriter printWriter;
try {
printWriter = new OutputStreamWriter(
new FileOutputStream(treeFilename),
Charset.forName("UTF-8").newEncoder()
);
} catch (FileNotFoundException e) {
e.printStackTrace();
printWriter = new OutputStreamWriter(
System.out,
Charset.forName("UTF-8").newEncoder()
);
}
StreamResult streamResult = new StreamResult(printWriter);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
try {
hdTree = tf.newTransformerHandler();
Transformer serializer = hdTree.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // "ISO-8859-1");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
hdTree.setResult(streamResult);
hdTree.startDocument();
AttributesImpl atts = new AttributesImpl();
atts.addAttribute("", "", "version", "CDATA", "1.0");
atts.addAttribute("", "", "xmln:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
atts.addAttribute("", "", "xsi:noNamespaceSchemaLocation", "CDATA", "tree.xsd");
String ourText = " Generated by JaCoP solver; " + getDateTime() + " ";
char[] comm = ourText.toCharArray();
hdTree.comment(comm, 0, comm.length);
hdTree.startElement("", "", "tree", atts);
atts = new AttributesImpl();
atts.addAttribute("", "", "id", "CDATA", "0");
hdTree.startElement("", "", "root", atts);
hdTree.endElement("", "", "root");
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void updateTable(HashSet<IntVar> fdvs) {
for (IntVar v : fdvs) {
// recent pruning
IntDomain cd = v.dom();
IntDomain pd = cd.previousDomain();
IntDomain rp;
int delta;
if (pd == null) {
rp = cd;
delta = IntDomain.MaxInt;
} else {
rp = pd.subtract(cd);
delta = rp.getSize();
if (delta == 0)
continue;
}
rbs.clearMask();
int xIndex = varMap.get(v);
Map<Integer, long[]> xSupport = supports[xIndex];
if (delta < cd.getSize()) { // incremental update
ValueEnumeration e = rp.valueEnumeration();
while (e.hasMoreElements()) {
long[] bs = xSupport.get(e.nextElement());
if (bs != null)
rbs.addToMask(bs);
}
rbs.reverseMask();
} else { // reset-based update
ValueEnumeration e = cd.valueEnumeration();
while (e.hasMoreElements()) {
long[] bs = xSupport.get(e.nextElement());
if (bs != null)
rbs.addToMask(bs);
}
}
rbs.intersectWithMask();
if (rbs.isEmpty())
throw store.failException;
}
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
void init() {
int n = tuple.length;
int lastWordSize = n % 64;
int numberBitSets = n / 64 + ((lastWordSize != 0) ? 1 : 0);
rbs = new ReversibleSparseBitSet();
long[] words = makeSupportAndWords(numberBitSets);
rbs.init(store, words);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Parameterized.Parameters
public static Collection<String> parametricTest() throws IOException {
FileReader file = new FileReader(relativePath + timeCategory + listFileName);
BufferedReader br = new BufferedReader(file);
String line = "";
List<String> list = new ArrayList<String>();
int i = 0;
while ((line = br.readLine())!=null) {
list.add(i, line);
i++;
}
return list;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Parameterized.Parameters
public static Collection<String> parametricTest() throws IOException {
return fileReader(timeCategory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void readFile(String file) {
System.out.println("readFile(" + file + ")");
try {
BufferedReader inr = new BufferedReader(new FileReader(file));
String str;
int lineCount = 0;
ArrayList<ArrayList<Integer>> MatrixI = new ArrayList<ArrayList<Integer>>();
while ((str = inr.readLine()) != null && str.length() > 0) {
str = str.trim();
// ignore comments
// starting with either # or %
if (str.startsWith("#") || str.startsWith("%")) {
continue;
}
str = str.replace("_", "");
String row[] = str.split("\\s+");
System.out.println(str);
// first line: column names: Ignore but count them
if (lineCount == 0) {
c = row.length;
colsums = new int[c];
} else {
// This is the last line: the column sums
if (row.length == c) {
colsums = new int[row.length];
for (int j = 0; j < row.length; j++) {
colsums[j] = Integer.parseInt(row[j]);
}
System.out.println();
} else {
// Otherwise:
// The problem matrix: index 1 .. row.length-1
// The row sums: index row.length
ArrayList<Integer> this_row = new ArrayList<Integer>();
for (int j = 0; j < row.length; j++) {
String s = row[j];
if (s.equals("*")) {
this_row.add(0);
} else {
this_row.add(Integer.parseInt(s));
}
}
MatrixI.add(this_row);
}
}
lineCount++;
} // end while
inr.close();
//
// Now we know everything to be known:
// Construct the problem matrix and column sums.
//
r = MatrixI.size();
rowsums = new int[r];
matrix = new int[r][c];
for (int i = 0; i < r; i++) {
ArrayList<Integer> this_row = MatrixI.get(i);
for (int j = 1; j < c + 1; j++) {
matrix[i][j - 1] = this_row.get(j);
}
rowsums[i] = this_row.get(c + 1);
}
} catch (IOException e) {
System.out.println(e);
}
}
#location 78
#vulnerability type RESOURCE_LEAK | #fixed code
public void readFile(String file) {
System.out.println("readFile(" + file + ")");
try {
BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String str;
int lineCount = 0;
ArrayList<ArrayList<Integer>> MatrixI = new ArrayList<ArrayList<Integer>>();
while ((str = inr.readLine()) != null && str.length() > 0) {
str = str.trim();
// ignore comments
// starting with either # or %
if (str.startsWith("#") || str.startsWith("%")) {
continue;
}
str = str.replace("_", "");
String row[] = str.split("\\s+");
System.out.println(str);
// first line: column names: Ignore but count them
if (lineCount == 0) {
c = row.length;
colsums = new int[c];
} else {
// This is the last line: the column sums
if (row.length == c) {
colsums = new int[row.length];
for (int j = 0; j < row.length; j++) {
colsums[j] = Integer.parseInt(row[j]);
}
System.out.println();
} else {
// Otherwise:
// The problem matrix: index 1 .. row.length-1
// The row sums: index row.length
ArrayList<Integer> this_row = new ArrayList<Integer>();
for (int j = 0; j < row.length; j++) {
String s = row[j];
if (s.equals("*")) {
this_row.add(0);
} else {
this_row.add(Integer.parseInt(s));
}
}
MatrixI.add(this_row);
}
}
lineCount++;
} // end while
inr.close();
//
// Now we know everything to be known:
// Construct the problem matrix and column sums.
//
r = MatrixI.size();
rowsums = new int[r];
matrix = new int[r][c];
for (int i = 0; i < r; i++) {
ArrayList<Integer> this_row = MatrixI.get(i);
for (int j = 1; j < c + 1; j++) {
matrix[i][j - 1] = this_row.get(j);
}
rowsums[i] = this_row.get(c + 1);
}
} catch (IOException e) {
System.out.println(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public HashSet<Constraint> getConstraints() {
HashSet<Constraint> constraints = new HashSet<Constraint>();
Set<String> ids = variablesHashMap.keySet();
for (String s : ids) {
Domain d = variablesHashMap.get(s).dom();
ArrayList<Constraint> c = d.constraints();
constraints.addAll(c);
}
return constraints;
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
public HashSet<Constraint> getConstraints() {
HashSet<Constraint> constraints = new HashSet<Constraint>();
for (Var v : variablesHashMap.values()) {
Domain d = v.dom();
ArrayList<Constraint> c = d.constraints();
constraints.addAll(c);
}
return constraints;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Parameterized.Parameters
public static Collection<String> parametricTest() throws IOException {
FileReader file = new FileReader(relativePath + timeCategory + listFileName);
BufferedReader br = new BufferedReader(file);
String line = "";
List<String> list = new ArrayList<String>();
int i = 0;
while ((line = br.readLine())!=null) {
list.add(i, line);
i++;
}
return list;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Parameterized.Parameters
public static Collection<String> parametricTest() throws IOException {
return fileReader(timeCategory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void saveLatexToFile(String desc) {
String fileName = this.latexFile + (calls++) + ".tex";
File f = new File(fileName);
FileOutputStream fs;
try {
System.out.println("save latex file " + fileName);
fs = new FileOutputStream(f);
fs.write(this.toLatex(desc).getBytes("UTF-8"));
fs.flush();
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
public void saveLatexToFile(String desc) {
String fileName = this.latexFile + (calls++) + ".tex";
File f = new File(fileName);
try(FileOutputStream fs = new FileOutputStream(f)) {
System.out.println("save latex file " + fileName);
fs.write(this.toLatex(desc).getBytes("UTF-8"));
fs.flush();
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static int[][] readFile(String file) {
int[][] problem = null; // The problem matrix
int r = 0;
int c = 0;
System.out.println("readFile(" + file + ")");
int lineCount = 0;
try {
BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String str;
while ((str = inr.readLine()) != null && str.length() > 0) {
str = str.trim();
// ignore comments
if (str.startsWith("#") || str.startsWith("%")) {
continue;
}
System.out.println(str);
if (lineCount == 0) {
r = Integer.parseInt(str); // number of rows
} else if (lineCount == 1) {
c = Integer.parseInt(str); // number of columns
problem = new int[r][c];
} else {
// the problem matrix
String row[] = str.split("");
for (int j = 1; j <= c; j++) {
String s = row[j];
if (s.equals(".")) {
problem[lineCount - 2][j - 1] = -1;
} else {
problem[lineCount - 2][j - 1] = Integer.parseInt(s);
}
}
}
lineCount++;
} // end while
inr.close();
} catch (IOException e) {
System.out.println(e);
}
return problem;
}
#location 49
#vulnerability type RESOURCE_LEAK | #fixed code
public static int[][] readFile(String file) {
int[][] problem = null; // The problem matrix
int r = 0;
int c = 0;
System.out.println("readFile(" + file + ")");
int lineCount = 0;
try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
String str;
while ((str = inr.readLine()) != null && str.length() > 0) {
str = str.trim();
// ignore comments
if (str.startsWith("#") || str.startsWith("%")) {
continue;
}
System.out.println(str);
if (lineCount == 0) {
r = Integer.parseInt(str); // number of rows
} else if (lineCount == 1) {
c = Integer.parseInt(str); // number of columns
problem = new int[r][c];
} else {
// the problem matrix
String row[] = str.split("");
for (int j = 1; j <= c; j++) {
String s = row[j];
if (s.equals(".")) {
problem[lineCount - 2][j - 1] = -1;
} else {
problem[lineCount - 2][j - 1] = Integer.parseInt(s);
}
}
}
lineCount++;
} // end while
inr.close();
} catch (IOException e) {
System.out.println(e);
}
return problem;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void uppendToLatexFile(String desc, String fileName) {
try {
System.out.println("save latex file " + fileName);
OutputStreamWriter char_output = new OutputStreamWriter(
new FileOutputStream(fileName),
Charset.forName("UTF-8").newEncoder()
);
BufferedWriter fs;
fs = new BufferedWriter(char_output);
fs.append(this.toLatex(desc));
fs.flush();
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
public void uppendToLatexFile(String desc, String fileName) {
try(OutputStreamWriter char_output = new OutputStreamWriter(new FileOutputStream(fileName),
Charset.forName("UTF-8").newEncoder());
BufferedWriter fs = new BufferedWriter(char_output)) {
System.out.println("save latex file " + fileName);
fs.append(this.toLatex(desc));
fs.flush();
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void saveLatexToFile(String desc) {
String fileName = this.latexFile + (calls++) + ".tex";
File f = new File(fileName);
FileOutputStream fs;
try {
System.out.println("save latex file " + fileName);
fs = new FileOutputStream(f);
fs.write(this.toLatex(desc).getBytes("UTF-8"));
fs.flush();
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
public void saveLatexToFile(String desc) {
String fileName = this.latexFile + (calls++) + ".tex";
File f = new File(fileName);
try(FileOutputStream fs = new FileOutputStream(f)) {
System.out.println("save latex file " + fileName);
fs.write(this.toLatex(desc).getBytes("UTF-8"));
fs.flush();
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static int[][] readFile(String file) {
int[][] problem = null; // The problem matrix
int r = 0;
int c = 0;
System.out.println("readFile(" + file + ")");
int lineCount = 0;
try {
BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String str;
while ((str = inr.readLine()) != null && str.length() > 0) {
str = str.trim();
// ignore comments
if (str.startsWith("#") || str.startsWith("%")) {
continue;
}
System.out.println(str);
if (lineCount == 0) {
r = Integer.parseInt(str); // number of rows
} else if (lineCount == 1) {
c = Integer.parseInt(str); // number of columns
problem = new int[r][c];
} else {
// the problem matrix
String row[] = str.split("");
for (int j = 1; j <= c; j++) {
String s = row[j];
if (s.equals(".")) {
problem[lineCount - 2][j - 1] = -1;
} else {
problem[lineCount - 2][j - 1] = Integer.parseInt(s);
}
}
}
lineCount++;
} // end while
inr.close();
} catch (IOException e) {
System.out.println(e);
}
return problem;
}
#location 49
#vulnerability type RESOURCE_LEAK | #fixed code
public static int[][] readFile(String file) {
int[][] problem = null; // The problem matrix
int r = 0;
int c = 0;
System.out.println("readFile(" + file + ")");
int lineCount = 0;
try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
String str;
while ((str = inr.readLine()) != null && str.length() > 0) {
str = str.trim();
// ignore comments
if (str.startsWith("#") || str.startsWith("%")) {
continue;
}
System.out.println(str);
if (lineCount == 0) {
r = Integer.parseInt(str); // number of rows
} else if (lineCount == 1) {
c = Integer.parseInt(str); // number of columns
problem = new int[r][c];
} else {
// the problem matrix
String row[] = str.split("");
for (int j = 1; j <= c; j++) {
String s = row[j];
if (s.equals(".")) {
problem[lineCount - 2][j - 1] = -1;
} else {
problem[lineCount - 2][j - 1] = Integer.parseInt(s);
}
}
}
lineCount++;
} // end while
inr.close();
} catch (IOException e) {
System.out.println(e);
}
return problem;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
int estimatePruningRecursive(IntVar xVar, Integer v, List<IntVar> exploredX, List<Integer> exploredV) {
if (exploredX.contains(xVar))
return 0;
exploredX.add(xVar);
exploredV.add(v);
int pruning = 0;
IntDomain xDom = xVar.dom();
pruning = xDom.getSize() - 1;
TimeStamp<Integer> stamp = null;
SimpleArrayList<IntVar> currentSimpleArrayList = null;
ValueEnumeration enumer = xDom.valueEnumeration();
// Permutation only
if (stampValues.value() - stampNotGroundedVariables.value() == 1)
for (int i = enumer.nextElement(); enumer.hasMoreElements(); i = enumer.nextElement()) {
if (!exploredV.contains(i)) {
Integer iInteger = i;
stamp = stamps.get(iInteger);
int lastPosition = stamp.value();
// lastPosition == 0 means one variable, so check if there
// is atmost one variable for value
if (lastPosition < exploredX.size() + 1) {
currentSimpleArrayList = valueMapVariable.get(iInteger);
IntVar singleVar = null;
boolean single = true;
for (int m = 0; m <= lastPosition; m++)
if (!exploredX.contains(currentSimpleArrayList.get(m)))
if (singleVar == null)
singleVar = currentSimpleArrayList.get(m);
else
single = false;
if (single && singleVar == null) {
System.out.println(this);
System.out.println("StampValues - 1 " + (stampValues.value() - 1));
System.out.println("Not grounded Var " + stampNotGroundedVariables.value());
int lastNotGroundedVariable = stampNotGroundedVariables.value();
Var variable = null;
for (int l = 0; l <= lastNotGroundedVariable; l++) {
variable = list[l];
System.out.println("Stamp for " + variable + " " + sccStamp.get(variable).value());
System.out.println("Matching " + matching.get(variable).value());
}
}
if (single && singleVar != null)
pruning += estimatePruningRecursive(singleVar, iInteger, exploredX, exploredV);
singleVar = null;
}
iInteger = null;
}
}
enumer = null;
stamp = stamps.get(v);
currentSimpleArrayList = valueMapVariable.get(v);
int lastPosition = stamp.value();
for (int i = 0; i <= lastPosition; i++) {
IntVar variable = currentSimpleArrayList.get(i);
// checks if there is at most one value for variable
if (!exploredX.contains(variable) && variable.dom().getSize() < exploredV.size() + 2) {
boolean single = true;
Integer singleVal = null;
for (ValueEnumeration enumerX = variable.dom().valueEnumeration(); enumerX.hasMoreElements(); ) {
Integer next = enumerX.nextElement();
if (!exploredV.contains(next))
if (singleVal == null)
singleVal = next;
else
single = false;
}
if (single)
pruning += estimatePruningRecursive(variable, singleVal, exploredX, exploredV);
}
}
stamp = null;
return pruning;
}
#location 77
#vulnerability type NULL_DEREFERENCE | #fixed code
int estimatePruning(IntVar x, Integer v) {
List<IntVar> exploredX = new ArrayList<IntVar>();
List<Integer> exploredV = new ArrayList<Integer>();
int pruning = estimatePruningRecursive(x, v, exploredX, exploredV);
SimpleArrayList<IntVar> currentSimpleArrayList = null;
Integer value = null;
for (int i = 0; i < exploredV.size(); i++) {
value = exploredV.get(i);
currentSimpleArrayList = valueMapVariable.get(value);
TimeStamp<Integer> stamp = stamps.get(value);
int lastPosition = stamp.value();
for (int j = 0; j <= lastPosition; j++)
// Edge between j and value was not counted yet
if (!exploredX.contains(currentSimpleArrayList.get(j)))
pruning++;
stamp = null;
}
currentSimpleArrayList = null;
value = null;
exploredX = null;
exploredV = null;
return pruning;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override public void notConsistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
for (IntVar e : x)
if (e.min() == 1)
numberOnes++;
else if (e.max() != 0)
nonGround = e;
int numberZeros = 0;
for (IntVar e : x)
if (e.max() == 0)
numberZeros++;
else if (e.min() != 1)
nonGround = e;
if (numberOnes + numberZeros == l)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 0, 0);
else
y.domain.in(store.level, y, 1, 1);
else if (numberOnes + numberZeros == l - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
}
#location 29
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override public void notConsistency(final Store store) {
IntVar nonGround = null;
int numberOnes = 0;
int numberZeros = 0;
for (IntVar e : x) {
if (e.min() == 1)
numberOnes++;
else if (e.max() == 0)
numberZeros++;
else nonGround = e;
}
if (numberOnes + numberZeros == x.length)
if ((numberOnes & 1) == 1)
y.domain.in(store.level, y, 0, 0);
else
y.domain.in(store.level, y, 1, 1);
else if (nonGround != null && numberOnes + numberZeros == x.length - 1)
if (y.min() == 1)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 1, 1);
else
nonGround.domain.in(store.level, nonGround, 0, 0);
else if (y.max() == 0)
if ((numberOnes & 1) == 1)
nonGround.domain.in(store.level, nonGround, 0, 0);
else
nonGround.domain.in(store.level, nonGround, 1, 1);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override public void model() {
if (filename != null) {
/* read from file args[0] */
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
while ((str = in.readLine()) != null)
if (!str.trim().equals("")) {
int commentPosition = str.indexOf("//");
if (commentPosition == 0)
continue;
else
str = str.substring(0, commentPosition);
lines[noLines] = str;
noLines++;
}
in.close();
} catch (FileNotFoundException e) {
System.err.println("File " + filename + " could not be found");
} catch (IOException e) {
System.err.println("Something is wrong with the file" + filename);
}
} else {
if (lines != null) {
// Standard use case if no file is supplied
// lines[0] = "SEND+MORE=MONEY";
// lines[0] = "BASIC+LOGIC=PASCAL";
// lines[0] = "CRACK+HACK=ERROR";
// lines[0] = "PEAR+APPLE=GRAPE";
// lines[0] = "CRACKS+TRACKS=RACKET";
// lines[0] = "TRIED+RIDE=STEER";
// lines[0] = "DEEMED+SENSE=SYSTEM";
// lines[0] = "DOWN+WWW=ERROR";
// lines[0] = "BARREL+BROOMS=SHOVELS";
// lines[0] = "LYNNE+LOOKS=SLEEPY";
// lines[0] = "STARS+RATE=TREAT";
// lines[0] = "DAYS+TOO=SHORT";
// lines[0] = "BASE+BALL=GAMES";
// lines[0] = "MEMO+FROM=HOMER";
// lines[0] = "IS+THIS=HERE";
lines[0] = "HERE+SHE=COMES";
noLines = 1;
}
System.out.println("No input file was supplied, using lines : ");
for (int i = 0; i < noLines; i++)
System.out.println(lines[0]);
}
/* Creating constraint store */
store = new Store();
ArrayList<ArrayList<String>> words = new ArrayList<ArrayList<String>>();
// Adding array list for each inputed line
for (int i = 0; i < noLines; i++)
words.add(new ArrayList<String>());
// letters used in the file.
HashMap<String, IntVar> letters = new HashMap<String, IntVar>();
// parsing the words within each line.
for (int i = 0; i < noLines; i++) {
Pattern pat = Pattern.compile("[=+]");
String[] result = pat.split(lines[i]);
for (int j = 0; j < result.length; j++)
words.get(i).add(result[j]);
}
vars = new ArrayList<IntVar>();
for (int i = 0; i < noLines; i++)
for (int j = words.get(i).size() - 1; j >= 0; j--)
for (int z = words.get(i).get(j).length() - 1; z >= 0; z--) {
char[] currentChar = {words.get(i).get(j).charAt(z)};
if (letters.get(new String(currentChar)) == null) {
IntVar currentLetter = new IntVar(store, new String(currentChar), 0, base - 1);
vars.add(currentLetter);
letters.put(new String(currentChar), currentLetter);
}
}
if (letters.size() > base) {
System.out.println("Expressions contain more than letters than base of the number system used ");
System.out.println("Base " + base);
System.out.println("Letters " + letters);
System.out.println("There can not be any solution");
}
store.impose(new Alldistinct(vars.toArray(new IntVar[0])));
for (int currentLine = 0; currentLine < noLines; currentLine++) {
int noWords = words.get(currentLine).size();
IntVar[] fdv4words = new IntVar[noWords];
IntVar[] terms = new IntVar[noWords - 1];
for (int j = 0; j < noWords; j++) {
String currentWord = words.get(currentLine).get(j);
fdv4words[j] = new IntVar(store, currentWord, 0, IntDomain.MaxInt);
// stores fdvs corresponding to all but the last one in the
// separate
// array for later use.
if (j < noWords - 1)
terms[j] = fdv4words[j];
IntVar[] lettersWithinCurrentWord = new IntVar[currentWord.length()];
for (int i = 0; i < currentWord.length(); i++) {
char[] currentChar = {currentWord.charAt(i)};
lettersWithinCurrentWord[i] = letters.get(new String(currentChar));
}
store.impose(new LinearInt(store, lettersWithinCurrentWord, createWeights(currentWord.length(), base), "==", fdv4words[j]));
// store.impose(new SumWeight(lettersWithinCurrentWord,
// createWeights(currentWord.length(), base),
// fdv4words[j]));
store.impose(new XneqC(lettersWithinCurrentWord[0], 0));
}
store.impose(new SumInt(store, terms, "==", fdv4words[noWords - 1]));
}
}
#location 27
#vulnerability type RESOURCE_LEAK | #fixed code
@Override public void model() {
if (filename != null) {
/* read from file args[0] */
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));
String str;
while ((str = in.readLine()) != null)
if (!str.trim().equals("")) {
int commentPosition = str.indexOf("//");
if (commentPosition == 0)
continue;
else
str = str.substring(0, commentPosition);
lines[noLines] = str;
noLines++;
}
in.close();
} catch (FileNotFoundException e) {
System.err.println("File " + filename + " could not be found");
} catch (IOException e) {
System.err.println("Something is wrong with the file" + filename);
}
} else {
if (lines != null) {
// Standard use case if no file is supplied
// lines[0] = "SEND+MORE=MONEY";
// lines[0] = "BASIC+LOGIC=PASCAL";
// lines[0] = "CRACK+HACK=ERROR";
// lines[0] = "PEAR+APPLE=GRAPE";
// lines[0] = "CRACKS+TRACKS=RACKET";
// lines[0] = "TRIED+RIDE=STEER";
// lines[0] = "DEEMED+SENSE=SYSTEM";
// lines[0] = "DOWN+WWW=ERROR";
// lines[0] = "BARREL+BROOMS=SHOVELS";
// lines[0] = "LYNNE+LOOKS=SLEEPY";
// lines[0] = "STARS+RATE=TREAT";
// lines[0] = "DAYS+TOO=SHORT";
// lines[0] = "BASE+BALL=GAMES";
// lines[0] = "MEMO+FROM=HOMER";
// lines[0] = "IS+THIS=HERE";
lines[0] = "HERE+SHE=COMES";
noLines = 1;
}
System.out.println("No input file was supplied, using lines : ");
for (int i = 0; i < noLines; i++)
System.out.println(lines[0]);
}
/* Creating constraint store */
store = new Store();
ArrayList<ArrayList<String>> words = new ArrayList<ArrayList<String>>();
// Adding array list for each inputed line
for (int i = 0; i < noLines; i++)
words.add(new ArrayList<String>());
// letters used in the file.
HashMap<String, IntVar> letters = new HashMap<String, IntVar>();
// parsing the words within each line.
for (int i = 0; i < noLines; i++) {
Pattern pat = Pattern.compile("[=+]");
String[] result = pat.split(lines[i]);
for (int j = 0; j < result.length; j++)
words.get(i).add(result[j]);
}
vars = new ArrayList<IntVar>();
for (int i = 0; i < noLines; i++)
for (int j = words.get(i).size() - 1; j >= 0; j--)
for (int z = words.get(i).get(j).length() - 1; z >= 0; z--) {
char[] currentChar = {words.get(i).get(j).charAt(z)};
if (letters.get(new String(currentChar)) == null) {
IntVar currentLetter = new IntVar(store, new String(currentChar), 0, base - 1);
vars.add(currentLetter);
letters.put(new String(currentChar), currentLetter);
}
}
if (letters.size() > base) {
System.out.println("Expressions contain more than letters than base of the number system used ");
System.out.println("Base " + base);
System.out.println("Letters " + letters);
System.out.println("There can not be any solution");
}
store.impose(new Alldistinct(vars.toArray(new IntVar[0])));
for (int currentLine = 0; currentLine < noLines; currentLine++) {
int noWords = words.get(currentLine).size();
IntVar[] fdv4words = new IntVar[noWords];
IntVar[] terms = new IntVar[noWords - 1];
for (int j = 0; j < noWords; j++) {
String currentWord = words.get(currentLine).get(j);
fdv4words[j] = new IntVar(store, currentWord, 0, IntDomain.MaxInt);
// stores fdvs corresponding to all but the last one in the
// separate
// array for later use.
if (j < noWords - 1)
terms[j] = fdv4words[j];
IntVar[] lettersWithinCurrentWord = new IntVar[currentWord.length()];
for (int i = 0; i < currentWord.length(); i++) {
char[] currentChar = {currentWord.charAt(i)};
lettersWithinCurrentWord[i] = letters.get(new String(currentChar));
}
store.impose(new LinearInt(store, lettersWithinCurrentWord, createWeights(currentWord.length(), base), "==", fdv4words[j]));
// store.impose(new SumWeight(lettersWithinCurrentWord,
// createWeights(currentWord.length(), base),
// fdv4words[j]));
store.impose(new XneqC(lettersWithinCurrentWord[0], 0));
}
store.impose(new SumInt(store, terms, "==", fdv4words[noWords - 1]));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void readFromFile(String filename) {
String lines[] = new String[100];
int[] dimensions = new int[2];
/* read from file args[0] or qcp.txt */
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
str = in.readLine();
Pattern pat = Pattern.compile(" ");
String[] result = pat.split(str);
int current = 0;
for (int j = 0; j < result.length; j++)
try {
int currentNo = Integer.parseInt(result[j]);
dimensions[current++] = currentNo;
} catch (Exception ex) {
}
lines = new String[dimensions[0] + dimensions[1]];
int n = 0;
while ((str = in.readLine()) != null && n < lines.length) {
lines[n] = str;
n++;
}
in.close();
} catch (FileNotFoundException e) {
System.err.println("I can not find file " + filename);
} catch (IOException e) {
System.err.println("Something is wrong with file" + filename);
}
row_rules = new int[dimensions[1]][];
col_rules = new int[dimensions[0]][];
// Transforms strings into ints
for (int i = 0; i < lines.length; i++) {
Pattern pat = Pattern.compile(" ");
String[] result = pat.split(lines[i]);
int[] sequence = new int[result.length];
int current = 0;
for (int j = 0; j < result.length; j++)
try {
sequence[current++] = Integer.parseInt(result[j]);
} catch (Exception ex) {
}
if (i < row_rules.length)
row_rules[i] = sequence;
else
col_rules[i - row_rules.length] = sequence;
}
}
#location 36
#vulnerability type RESOURCE_LEAK | #fixed code
public void readFromFile(String filename) {
String lines[] = new String[100];
int[] dimensions = new int[2];
/* read from file args[0] or qcp.txt */
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));
String str;
str = in.readLine();
Pattern pat = Pattern.compile(" ");
String[] result = pat.split(str);
int current = 0;
for (int j = 0; j < result.length; j++)
try {
int currentNo = Integer.parseInt(result[j]);
dimensions[current++] = currentNo;
} catch (Exception ex) {
}
lines = new String[dimensions[0] + dimensions[1]];
int n = 0;
while ((str = in.readLine()) != null && n < lines.length) {
lines[n] = str;
n++;
}
in.close();
} catch (FileNotFoundException e) {
System.err.println("I can not find file " + filename);
} catch (IOException e) {
System.err.println("Something is wrong with file" + filename);
}
row_rules = new int[dimensions[1]][];
col_rules = new int[dimensions[0]][];
// Transforms strings into ints
for (int i = 0; i < lines.length; i++) {
Pattern pat = Pattern.compile(" ");
String[] result = pat.split(lines[i]);
int[] sequence = new int[result.length];
int current = 0;
for (int j = 0; j < result.length; j++)
try {
sequence[current++] = Integer.parseInt(result[j]);
} catch (Exception ex) {
}
if (i < row_rules.length)
row_rules[i] = sequence;
else
col_rules[i - row_rules.length] = sequence;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void float_comparison(int operation, SimpleNode node, int reifStart) {
// node.dump("");
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
boolean reified = false;
if (p.startsWith("_reif", reifStart)) {
reified = true;
}
if (reified) { // reified constraint
PrimitiveConstraint c = null;
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
IntVar v3 = getVariable(p3);
if (p2.getType() == 5) { // var rel float
FloatVar v1 = getFloatVariable(p1);
double i2 = getFloat(p2);
switch (operation) {
case eq :
if (v1.min() > i2 || v1.max() < i2) {
v3.domain.in(store.level, v3, 0, 0);
return;
}
else if (v1.min() == i2 && v1.singleton() ) {
v3.domain.in(store.level, v3, 1, 1);
return;
} else if (v3.max() == 0) {
v1.domain.inComplement(store.level, v1, i2);
return;
}
else if (v3.min() == 1) {
v1.domain.in(store.level, v1, i2, i2);
return;
}
else
c = new PeqC(v1, i2);
break;
case ne :
if (v1.min() > i2 || v1.max() < i2) {
v3.domain.in(store.level, v3, 1, 1);
return;
}
else if (v1.min() == i2 && v1.singleton() ) {
v3.domain.in(store.level, v3, 0, 0);
return;
} else if (v3.max() == 0) {
v1.domain.in(store.level, v1, i2, i2);
return;
}
else if (v3.min() == 1) {
v1.domain.inComplement(store.level, v1, i2);
return;
}
else
c = new PneqC(v1, i2);
break;
case lt :
if (v1.max() < i2) {
v3.domain.in(store.level, v3, 1, 1);
return;
}
else if (v1.min() >= i2 ) {
v3.domain.in(store.level, v3, 0, 0);
return;
}
else
c = new PltC(v1, i2);
break;
case le :
if (v1.max() <= i2) {
v3.domain.in(store.level, v3, 1, 1);
return;
}
else if (v1.min() > i2 ) {
v3.domain.in(store.level, v3, 0, 0);
return;
}
else
c = new PlteqC(v1, i2);
break;
// case gt :
// if (v1.min() > i2) {
// v3.domain.in(store.level, v3, 1, 1);
// return;
// }
// else if (v1.max() <= i2 ) {
// v3.domain.in(store.level, v3, 0, 0);
// return;
// }
// else
// c = new PgtC(v1, i2);
// break;
// case ge :
// if (v1.min() >= i2) {
// v3.domain.in(store.level, v3, 1, 1);
// return;
// }
// else if (v1.max() < i2 ) {
// v3.domain.in(store.level, v3, 0, 0);
// return;
// }
// else
// c = new PgteqC(v1, i2);
// break;
}
} else if (p1.getType() == 5) { // float rel var
FloatVar v2 = getFloatVariable(p2);
double i1 = getFloat(p1);
switch (operation) {
case eq :
if (v2.min() > i1 || v2.max() < i1) {
v3.domain.in(store.level, v3, 0, 0);
return;
}
else if (v2.min() == i1 && v2.singleton() ) {
v3.domain.in(store.level, v3, 1, 1);
return;
}
else if (v3.max() == 0) {
v2.domain.inComplement(store.level, v2, i1);
return;
}
else if (v3.min() == 1) {
v2.domain.in(store.level, v2, i1, i1);
return;
}
else
c = new PeqC(v2, i1);
break;
case ne :
if (v2.min() > i1 || v2.max() < i1) {
v3.domain.in(store.level, v3, 1, 1);
return;
}
else if (v2.min() == i1 && v2.singleton() ) {
v3.domain.in(store.level, v3, 0, 0);
return;
}
else
c = new PneqC(v2, i1);
break;
case lt :
if (i1 < v2.min()) {
v3.domain.in(store.level, v3, 1, 1);
return;
}
else if (i1 >= v2.max() ) {
v3.domain.in(store.level, v3, 0, 0);
return;
}
else
c = new PgtC(v2, i1);
break;
case le :
if (i1 <= v2.min()) {
v3.domain.in(store.level, v3, 1, 1);
return;
}
else if (i1 > v2.max() ) {
v3.domain.in(store.level, v3, 0, 0);
return;
}
else
c = new PgteqC(v2, i1);
break;
// case gt :
// if (i1 > v2.max()) {
// v3.domain.in(store.level, v3, 1, 1);
// return;
// }
// else if (i1 <= v2.min() ) {
// v3.domain.in(store.level, v3, 0, 0);
// return;
// }
// else
// c = new PltC(v2, i1);
// break;
// case ge :
// if (i1 > v2.max()) {
// v3.domain.in(store.level, v3, 1, 1);
// return;
// }
// else if (i1 < v2.min() ) {
// v3.domain.in(store.level, v3, 0, 0);
// return;
// }
// else
// c = new PlteqC(v2, i1);
// break;
}
} else { // var rel var
FloatVar v1 = getFloatVariable(p1);
FloatVar v2 = getFloatVariable(p2);
switch (operation) {
case eq :
c = new PeqQ(v1, v2);
break;
case ne :
c = new PneqQ(v1, v2);
break;
case lt :
c = new PltQ(v1, v2);
break;
case le :
c = new PlteqQ(v1, v2);
break;
// case gt :
// c = new PgtQ(v1, v2);
// break;
// case ge :
// c = new PgteqQ(v1, v2);
// break;
}
}
Constraint cr = new Reified(c, v3);
pose(cr);
}
else { // not reified constraints
if (p1.getType() == 5) { // first parameter float
if (p2.getType() == 0 || p2.getType() == 1) { // first parameter float & second parameter float
double i1 = getFloat(p1);
double i2 = getFloat(p2);
switch (operation) {
case eq :
if (i1 != i2) throw Store.failException;
break;
case ne :
if (i1 == i2) throw Store.failException;
break;
case lt :
if (i1 >= i2) throw Store.failException;
break;
case le :
if (i1 > i2) throw Store.failException;
break;
// case gt :
// if (i1 <= i2) throw Store.failException;
// break;
// case ge :
// if (i1 < i2) throw Store.failException;
// break;
}
}
else { // first parameter float & second parameter var
double i1 = getFloat(p1);
FloatVar v2 = getFloatVariable(p2);
switch (operation) {
case eq :
v2.domain.in(store.level, v2, i1, i1);
break;
case ne :
v2.domain.inComplement(store.level, v2, i1);
break;
case lt :
v2.domain.in(store.level, v2, FloatDomain.next(i1), VariablesParameters.MAX_FLOAT);
break;
case le :
v2.domain.in(store.level, v2, i1, VariablesParameters.MAX_FLOAT);
break;
// case gt :
// v2.domain.in(store.level, v2, IntDomain.MinInt, i1-1);
// break;
// case ge :
// v2.domain.in(store.level, v2, IntDomain.MinInt, i1);
// break;
}
}
}
else { // first parameter var
if (p2.getType() == 5) { // first parameter var & second parameter float
FloatVar v1 = getFloatVariable(p1);
double i2 = getFloat(p2);
switch (operation) {
case eq :
v1.domain.in(store.level, v1, i2, i2);
break;
case ne :
v1.domain.inComplement(store.level, v1, i2);
break;
case lt :
v1.domain.in(store.level, v1, VariablesParameters.MIN_FLOAT, FloatDomain.previous(i2));
break;
case le :
v1.domain.in(store.level, v1, VariablesParameters.MIN_FLOAT, i2);
break;
// case gt :
// v1.domain.in(store.level, v1, i2+1, VariablesParameters.MAX_FLOAT);
// break;
// case ge :
// v1.domain.in(store.level, v1, i2, VariablesParameters.MAX_FLOAT);
// break;
}
}
else { // first parameter var & second parameter var
PrimitiveConstraint c = null;
FloatVar v1 = getFloatVariable(p1);
FloatVar v2 = getFloatVariable(p2);
switch (operation) {
case eq :
c = new PeqQ(v1, v2);
break;
case ne :
c = new PneqQ(v1, v2);
break;
case lt :
c = new PltQ(v1, v2);
break;
case le :
c = new PlteqQ(v1, v2);
break;
// case gt :
// c = new PgtQ(v1, v2);
// break;
// case ge :
// c = new PgteqQ(v1, v2);
// break;
}
pose(c);
}
}
}
}
#location 338
#vulnerability type NULL_DEREFERENCE | #fixed code
void generateConstraints(SimpleNode constraintWithAnnotations, Tables table, Options opt) throws FailException {
this.opt = opt;
// if (!storeLevelIncreased) {
// System.out.println("1. Level="+store.level);
// store.setLevel(store.level + 1);
// storeLevelIncreased = true;
// System.out.println("2. Level="+store.level);
// }
if (debug)
constraintWithAnnotations.dump("");
// default consistency - bounds
boundsConsistency = true;
domainConsistency = false;
definedVar = null;
dictionary = table;
// this.zero = table.zero;
// this.one = table.one;
int numberChildren = constraintWithAnnotations.jjtGetNumChildren();
// System.out.println ("numberChildren = "+numberChildren);
if (numberChildren > 1 )
parseAnnotations(constraintWithAnnotations);
SimpleNode node = (SimpleNode)constraintWithAnnotations.jjtGetChild(0);
// node.dump("=> ");
// Predicates
if (node.getId() == JJTCONSTELEM) {
p = ((ASTConstElem)node).getName();
if (p.startsWith("int2float")) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new XeqP(getVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("float_") ) {
int operation = comparisonPredicate(p, 6);
// node.dump("");
// System.out.println(p + " op = " + operation);
// float_eq*, float_ne*, float_lt*, float_gt*, float_le*, and float_ge*
if ( operation != -1) {
float_comparison(operation, node, 8);
}
// float_lin_* (eq, ne, lt, gt, le, ge)
else if (p.startsWith("lin_", 6)) {
operation = comparisonPredicate(p, 10);
float_lin_relation(operation, node);
}
else if (p.startsWith("plus", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
if (p1.getType() == 5) {// p1 int
pose(new PplusCeqR(getFloatVariable(p2), getFloat(p1), getFloatVariable(p3)));
}
else if (p2.getType() == 5) {// p2 int
pose(new PplusCeqR(getFloatVariable(p1), getFloat(p2), getFloatVariable(p3)));
}
else
pose(new PplusQeqR(getFloatVariable(p1), getFloatVariable(p2), getFloatVariable(p3)));
} else if (p.startsWith("times", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
if (p1.getType() == 5) {// p1 float
pose(new PmulCeqR(getFloatVariable(p2), getFloat(p1), getFloatVariable(p3)));
}
else if (p2.getType() == 5) {// p2 float
pose(new PmulCeqR(getFloatVariable(p1), getFloat(p2), getFloatVariable(p3)));
}
else
pose(new PmulQeqR(getFloatVariable(p1), getFloatVariable(p2), getFloatVariable(p3)));
} else if (p.startsWith("div", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
pose(new PdivQeqR(getFloatVariable(p1), getFloatVariable(p2), getFloatVariable(p3)));
}
else if (p.startsWith("abs", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new AbsPeqR(getFloatVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("sqrt", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new SqrtPeqR(getFloatVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("sin", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new SinPeqR(getFloatVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("cos", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new CosPeqR(getFloatVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("asin", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new AsinPeqR(getFloatVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("acos", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new AcosPeqR(getFloatVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("tan", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new TanPeqR(getFloatVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("atan", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new AtanPeqR(getFloatVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("exp", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new ExpPeqR(getFloatVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("ln", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
pose(new LnPeqR(getFloatVariable(p1), getFloatVariable(p2)));
}
else if (p.startsWith("min", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
FloatVar v1 = getFloatVariable(p1);
FloatVar v2 = getFloatVariable(p2);
FloatVar v3 = getFloatVariable(p3);
pose(new org.jacop.floats.constraints.Min(new FloatVar[] {v1, v2}, v3));
// 1.
// pose(new IfThenElse(new PlteqQ(v1,v2), new PeqQ(v1,v3), new PeqQ(v2,v3)));
// 2.
// pose(new IfThen(new PltQ(v1,v2), new PeqQ(v1,v3)));
// pose(new IfThen(new PltQ(v2,v1), new PeqQ(v2,v3)));
}
else if (p.startsWith("max", 6)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
FloatVar v1 = getFloatVariable(p1);
FloatVar v2 = getFloatVariable(p2);
FloatVar v3 = getFloatVariable(p3);
pose(new org.jacop.floats.constraints.Max(new FloatVar[] {v1, v2}, v3));
// 1.
// pose(new IfThenElse(new PltQ(v2,v1), new PeqQ(v1,v3), new PeqQ(v2,v3)));
// 2.
// pose(new IfThen(new PltQ(v2,v1), new PeqQ(v1,v3)));
// pose(new IfThen(new PltQ(v1,v2), new PeqQ(v2,v3)));
}
else {
System.err.println("%% ERROR: JaCoP does not implement this constraints on floats");
System.exit(0);
}
}
// int_* predicates
else if (p.startsWith("int_") ) {
int operation = comparisonPredicate(p, 4);
// System.out.println(p + " op = " + operation);
if (p.startsWith("negate", 4)) {
int_negate(node);
}
// int_eq*, int_ne*, int_lt*, int_gt*, int_le*, and int_ge*
else if ( operation != -1) {
int_comparison(operation, node, 6);
}
// int_lin_* (eq, ne, lt, gt, le, ge)
else if (p.startsWith("lin_", 4)) {
operation = comparisonPredicate(p, 8);
int_lin_relation(operation, node);
}
else if (p.startsWith("plus", 4)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
if (p1.getType() == 0) {// p1 int
pose(new XplusCeqZ(getVariable(p2), getInt(p1), getVariable(p3)));
}
else if (p2.getType() == 0) {// p2 int
pose(new XplusCeqZ(getVariable(p1), getInt(p2), getVariable(p3)));
}
else if (p3.getType() == 0) {// p3 int
pose(new XplusYeqC(getVariable(p1), getVariable(p2), getInt(p3)));
}
else
pose(new XplusYeqZ(getVariable(p1), getVariable(p2), getVariable(p3)));
}
else if (p.startsWith("minus", 4)) {
// p1 - p2 = p3 <=> p2 + p3 = p1
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
if (p2.getType() == 0) {// p2 int
pose(new XplusCeqZ(getVariable(p3), getInt(p2), getVariable(p1)));
}
else if (p3.getType() == 0) {// p3 int
pose(new XplusCeqZ(getVariable(p2), getInt(p3), getVariable(p1)));
}
else if (p3.getType() == 0) {// p1 int
pose(new XplusYeqC(getVariable(p2), getVariable(p3), getInt(p1)));
}
else
pose(new XplusYeqZ(getVariable(p2), getVariable(p3), getVariable(p1)));
}
else if (p.startsWith("times", 4)) {
// node.dump("");
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
if (p1.getType() == 0) {// p1 int
pose(new XmulCeqZ(getVariable(p2), getInt(p1), getVariable(p3)));
}
else if (p2.getType() == 0) {// p2 int
pose(new XmulCeqZ(getVariable(p1), getInt(p2), getVariable(p3)));
}
else if (p3.getType() == 0) {// p3 int
pose(new XmulYeqC(getVariable(p1), getVariable(p2), getInt(p3)));
}
else {
IntVar v1 = getVariable(p1), v2 = getVariable(p2), v3 = getVariable(p3);
if (v1.min() >= 0 && v1.max() <= 1 && v2.min() >= 0 && v2.max() <= 1 && v3.min() >= 0 && v3.max() <= 1)
pose(new AndBoolSimple(v1, v2, v3));
else
pose(new XmulYeqZ(v1, v2, v3));
}
}
else if (p.startsWith("div", 4)) {
// p1/p2 = p3
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
IntVar v1 = getVariable(p1);
IntVar v2 = getVariable(p2);
IntVar v3 = getVariable(p3);
pose(new XdivYeqZ(v1, v2, v3));
}
else if (p.startsWith("mod", 4)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
IntVar v1 = getVariable(p1);
IntVar v2 = getVariable(p2);
IntVar v3 = getVariable(p3);
pose(new XmodYeqZ(v1, v2, v3));
}
else if (p.startsWith("min", 4)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
IntVar v1 = getVariable(p1);
IntVar v2 = getVariable(p2);
IntVar v3 = getVariable(p3);
// pose(new IfThen(new XlteqY(v1,v2), new XeqY(v1,v3)));
// pose(new IfThen(new XlteqY(v2,v1), new XeqY(v2,v3)));
if (v1 == v2)
pose(new XeqY(v1, v3));
else
pose(new org.jacop.constraints.Min(new IntVar[] {v1, v2}, v3));
}
else if (p.startsWith("max", 4)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
IntVar v1 = getVariable(p1);
IntVar v2 = getVariable(p2);
IntVar v3 = getVariable(p3);
// pose(new IfThen(new XgteqY(v1,v2), new XeqY(v1,v3)));
// pose(new IfThen(new XgteqY(v2,v1), new XeqY(v2,v3)));
if ( v1.singleton() && v2.singleton() ) {
int max = java.lang.Math.max(v1.value(), v2.value());
v3.domain.in(store.level, v3, max, max);
}
else if (v1.singleton() && v1.value() >= v2.max() ) {
int max = v1.value();
v3.domain.in(store.level, v3, max, max);
}
else if (v2.singleton() && v2.value() >= v1.max() ) {
int max = v2.value();
v3.domain.in(store.level, v3, max, max);
}
else if (v1.min() >= v2.max() )
pose(new XeqY(v1, v3));
else if (v2.min() >= v1.max() )
pose(new XeqY(v2, v3));
else if (v1 == v2)
pose(new XeqY(v1, v3));
else
pose(new org.jacop.constraints.Max(new IntVar[] {v1, v2}, v3));
}
else if (p.startsWith("abs", 4)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
IntVar v1 = getVariable(p1);
IntVar v2 = getVariable(p2);
if (boundsConsistency)
pose(new AbsXeqY(v1, v2));
else
pose(new AbsXeqY(v1, v2, true));
}
else if (p.startsWith("pow", 4)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
IntVar v1 = getVariable(p1);
IntVar v2 = getVariable(p2);
IntVar v3 = getVariable(p3);
pose(new XexpYeqZ(v1, v2, v3));
}
else
System.out.println("TODO: "+p);
}
// array_* predicates
else if (p.startsWith("array_") ) {
if (p.startsWith("bool_", 6)) {
if (p.startsWith("and", 11)) {
// node.dump("");
IntVar[] a1 = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar v = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
if (opt.useSat())
sat.generate_and(a1, v);
else
pose(new AndBool(a1, v));
}
else if (p.startsWith("or", 11)) {
// node.dump("");
IntVar[] a1 = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar v = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
if (opt.useSat())
sat.generate_or(a1, v);
else
pose(new OrBool(a1, v));
}
else if (p.startsWith("xor", 11)) {
SimpleNode p1 = (SimpleNode)node.jjtGetChild(0);
IntVar[] a1 = getVarArray(p1);
if (opt.useSat())
sat.generate_xor(a1, dictionary.getConstant(1)); // one);
else
pose(new XorBool(a1, dictionary.getConstant(1))); // one));
}
else if (p.startsWith("element", 11)) {
// array_bool_element
generateIntElementConstraint(node);
}
else
System.err.println("%% ERROR: Not expected constraint : "+p);
}
else if (p.startsWith("var_bool_element", 6) ) {
// array_var_bool_element
generateVarElementConstraint(node);
// generateElementConstraint(p, 0);
}
else if (p.startsWith("var_int_element", 6) ) {
// array_var_int_element
generateVarElementConstraint(node);
// generateElementConstraint(p, 1);
}
else if (p.startsWith("int_element", 6)) {
// array_int_element
generateIntElementConstraint(node);
}
else if (p.startsWith("var_set_element", 6) ) {
// array_var_set_element
generateVarSetElementConstraint(node);
}
else if (p.startsWith("set_element", 6)) {
// array_set_element
generateSetElementConstraint(node);
}
else if (p.startsWith("float_element", 6)) {
generateFloatElementConstraint(node);
}
else
System.out.println("TODO: "+p);
}
// bool_* predicates
else if (p.startsWith("bool_") ) {
int operation = comparisonPredicate(p, 5);
// bool_left_imp
// a <- b <-> r
//-------------
// 0 <- 0 <-> 1
// 0 <- 1 <-> 0
// 1 <- 0 <-> 1
// 1 <- 1 <-> 1
if (p.startsWith("left_imp", 5)) {
IntVar v1 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar v2 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
IntVar v3 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
if (opt.useSat())
sat.generate_implication_reif(v2, v1, v3);
else
pose(new IfThenBool(v2, v1, v3));
}
else if ( operation != -1) {
// bool_eq*, bool_ne*, bool_lt*, bool_gt*, bool_le*, and bool_ge*
if (opt.useSat()) {
if (p.startsWith("eq_reif", 5) ) {
IntVar v1 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar v2 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
IntVar v3 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
sat.generate_eq_reif(v1, v2, v3);
}
else if (p.startsWith("ne_reif", 5) ) {
IntVar v1 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar v2 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
IntVar v3 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
sat.generate_neq_reif(v1, v2, v3);
}
else if (p.startsWith("le_reif", 5) ) {
IntVar a = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar b = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
IntVar c = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
sat.generate_le_reif(a, b, c);
}
else if (p.startsWith("lt_reif", 5) ) {
IntVar a = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar b = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
IntVar c = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
sat.generate_lt_reif(a, b, c);
}
else if (p.startsWith("eq", 5) ) {
IntVar a = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar b = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
sat.generate_eq(a, b);
}
else if (p.startsWith("ne", 5) ) {
IntVar a = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar b = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
sat.generate_not(a, b);
}
else if (p.startsWith("le", 5) ) {
IntVar a = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar b = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
sat.generate_le(a, b);
}
else if (p.startsWith("lt", 5) ) {
IntVar a = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar b = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
sat.generate_lt(a, b);
}
}
else {
int_comparison(operation, node, 7);
}
}
// bool_or
else if (p.startsWith("or", 5)) {
IntVar v1 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar v2 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
IntVar v3 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
if (opt.useSat())
sat.generate_or(new IntVar[] {v1, v2}, v3);
else
pose(new OrBoolSimple(v1, v2, v3));
}
// bool_and
else if (p.startsWith("and", 5)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
IntVar v1 = getVariable(p1);
IntVar v2 = getVariable(p2);
IntVar v3 = getVariable(p3);
if (opt.useSat())
sat.generate_and(new IntVar[] {v1, v2}, v3);
else
pose(new AndBoolSimple(v1, v2, v3));
}
// bool_xor
else if (p.startsWith("xor", 5)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
IntVar v1 = getVariable(p1);
IntVar v2 = getVariable(p2);
IntVar v3 = getVariable(p3);
if (opt.useSat())
sat.generate_neq_reif(v1, v2, v3);
else
pose(new XorBool(new IntVar[] {v1, v2}, v3));
}
// bool_not
else if (p.startsWith("not", 5)) {
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
IntVar v1 = getVariable(p1);
IntVar v2 = getVariable(p2);
if (opt.useSat())
sat.generate_not(v1, v2);
else
pose(new XneqY(v1, v2));
}
// bool_right_imp
// a -> b <-> r
//-------------
// 0 -> 0 <-> 1
// 0 -> 1 <-> 1
// 1 -> 0 <-> 0
// 1 -> 1 <-> 1
else if (p.startsWith("right_imp", 5)) {
// node.dump("");
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
ASTScalarFlatExpr p3 = (ASTScalarFlatExpr)node.jjtGetChild(2);
IntVar v1 = getVariable(p1);
IntVar v2 = getVariable(p2);
IntVar v3 = getVariable(p3);
if (opt.useSat())
sat.generate_implication_reif(v1, v2, v3);
else
pose(new IfThenBool(v1, v2, v3));
}
// bool_clause([x1,..., xm], [y1,..., yn]) ===>
// x1 \/ ... \/ xm \/ not y1 \/ ... \/ not yn
else if (p.startsWith("clause", 5)) {
IntVar[] a1 = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[] a2 = getVarArray((SimpleNode)node.jjtGetChild(1));
if (a1.length == 0 && a2.length == 0 )
return;
if (opt.useSat()) {
if (p.startsWith("_reif", 11)) { // reified
IntVar r = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
sat.generate_clause_reif(a1, a2, r);
}
else
sat.generate_clause(a1, a2);
}
else { // not SAT generation, use CP constraints
ArrayList<IntVar> a1reduced = new ArrayList<IntVar>();
for (int i = 0; i < a1.length; i++)
if (a1[i].max() != 0)
a1reduced.add(a1[i]);
ArrayList<IntVar> a2reduced = new ArrayList<IntVar>();
for (int i = 0; i < a2.length; i++)
if (a2[i].min() != 1)
a2reduced.add(a2[i]);
if (a1reduced.size() == 0 && a2reduced.size() == 0 )
throw store.failException;
PrimitiveConstraint c;
if (a1reduced.size() == 0)
c = new AndBool(a2reduced, dictionary.getConstant(0)); // zero);
else if (a2reduced.size() == 0)
c = new OrBool(a1reduced, dictionary.getConstant(1)); // one);
else if (a1reduced.size() == 1 && a2reduced.size() == 1)
if (a1reduced.get(0).min() == 1)
return;
else
c = new XlteqY(a2reduced.get(0), a1reduced.get(0));
else
c = new BoolClause(a1reduced, a2reduced);
// bool_clause_reif/3 defined in redefinitions-2.0.
if (p.startsWith("_reif", 11)) {
IntVar r = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
pose(new Reified(c, r)); }
else
pose(c);
}
}
// bool_lin_* (eq, ne, lt, gt, le, ge)
else if (p.startsWith("lin_", 5)) {
operation = comparisonPredicate(p, 9);
int_lin_relation(operation, node);
}
else
System.out.println("TODO: "+p);
// <-------------
}
// set_* predicates
else if (p.startsWith("set_") ) {
if (p.startsWith("eq", 4)) {
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
PrimitiveConstraint c = new org.jacop.set.constraints.AeqB(v1, v2);
if (p.startsWith("_reif", 6)) {
IntVar v3 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
pose(new Reified(c, v3));
}
else
pose(c);
}
else if (p.startsWith("ne", 4)) {
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
PrimitiveConstraint c = new Not(new org.jacop.set.constraints.AeqB(v1, v2));
if (p.startsWith("_reif", 6)) {
IntVar v3 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
pose(new Reified(c, v3));
}
else
pose(c);
}
else if (p.startsWith("lt", 4)) {
if (p.startsWith("_reif", 6)) {
System.err.println("%% set_lt_reif with list of set variables is not avaible in org.jacop.set");
System.exit(0);
}
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
pose(new Lex(v1, v2));
}
else if (p.startsWith("gt", 4)) {
if (p.startsWith("_reif", 6)) {
System.err.println("%% set_gt_reif with list of set variables is not avaible in org.jacop.set");
System.exit(0);
}
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
pose(new Lex(v2, v1));
}
else if (p.startsWith("le", 4)) {
if (p.startsWith("_reif", 6)) {
System.err.println("%% set_le_reif with list of set variables is not avaible in org.jacop.set");
System.exit(0);
}
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
pose(new Lex(v1, v2, false));
}
else if (p.startsWith("ge", 4)) {
if (p.startsWith("_reif", 6)) {
System.err.println("%% set_ge_reif with list of set variables is not avaible in org.jacop.set");
System.exit(0);
}
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
pose(new Lex(v2, v1, false));
}
else if (p.startsWith("intersect", 4)) {
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
SetVar v3 = getSetVariable(node, 2);
pose(new AintersectBeqC(v1, v2, v3));
}
else if (p.startsWith("card", 4)) {
SetVar v1 = getSetVariable(node, 0);
IntVar v2 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
if (v2.singleton()) {
v1.domain.inCardinality(store.level, v1, v2.min(), v2.max());
if (debug)
System.out.println ("Cardinality of set " + v1 + " = " + v2);
}
else
pose(new CardAeqX(v1, v2));
}
else if (p.startsWith("in", 4)) {
PrimitiveConstraint c;
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
SimpleNode v1Type = (SimpleNode)node.jjtGetChild(1);
if (v1Type.getId() == JJTSETLITERAL) {
IntDomain d = getSetLiteral(node, 1);
IntVar v1 = getVariable(p1);
if (p.startsWith("_reif", 6))
// if (opt.useSat()) { // it can be moved to SAT solver but it is slow in the current implementation
// IntVar v3 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
// sat.generate_inSet_reif(v1, d, v3);
// return;
// }
// else
c = new org.jacop.constraints.In(v1, d);
else {
v1.domain.in(store.level, v1, d);
return;
}
}
else {
SetVar v2 = getSetVariable(node, 1);
if (p1.getType() == 0) { // p1 int
int i1 = getInt(p1);
c = new EinA(i1, v2);
}
else { // p1 var
IntVar v1 = getVariable(p1);
c = new XinA(v1, v2);
}
}
// FIXME, include AinB here?
if (p.startsWith("_reif", 6)) {
IntVar v3 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
pose(new Reified(c, v3));
}
else
pose(c);
}
else if (p.startsWith("subset", 4)) {
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
PrimitiveConstraint c = new AinB(v1, v2);
if (p.startsWith("_reif", 10)) {
IntVar v3 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
pose(new Reified(c, v3));
}
else
pose(c);
}
else if (p.startsWith("superset", 4)) {
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
PrimitiveConstraint c = new AinB(v2, v1);
if (p.startsWith("_reif", 12)) {
IntVar v3 = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
pose(new Reified(c, v3));
}
else
pose(c);
}
else if (p.startsWith("union", 4)) {
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
SetVar v3 = getSetVariable(node, 2);
pose(new AunionBeqC(v1, v2, v3));
}
else if (p.startsWith("diff", 4)) {
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
SetVar v3 = getSetVariable(node, 2);
pose(new AdiffBeqC(v1, v2, v3));
}
else if (p.startsWith("symdiff", 4)) {
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
SetVar v3 = getSetVariable(node, 2);
SetVar t1 = new SetVar(store, new BoundSetDomain(IntDomain.MinInt, IntDomain.MaxInt));
SetVar t2 = new SetVar(store, new BoundSetDomain(IntDomain.MinInt, IntDomain.MaxInt));
pose(new AdiffBeqC(v1, v2, t1));
pose(new AdiffBeqC(v2, v1, t2));
pose(new AunionBeqC(t1, t2, v3));
}
else
System.out.println("TODO: "+p);
}
// bool2int and int2bool coercion operations
else if (p.equals("bool2int") || p.equals("int2bool") ) {
// node.dump("");
ASTScalarFlatExpr p1 = (ASTScalarFlatExpr)node.jjtGetChild(0);
ASTScalarFlatExpr p2 = (ASTScalarFlatExpr)node.jjtGetChild(1);
// if (opt.useSat()) // it can be moved to SAT solver but it is slow in the current implementation
// sat.generate_eq(getVariable(p1), getVariable(p2));
// else
pose(new XeqY(getVariable(p1), getVariable(p2)));
}
// ========== JaCoP constraints ==================>>
else if (p.startsWith("jacop_"))
if (p.startsWith("cumulative", 6)) {
IntVar[] s = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[] d = getVarArray((SimpleNode)node.jjtGetChild(1));
IntVar[] r = getVarArray((SimpleNode)node.jjtGetChild(2));
IntVar b = getVariable((ASTScalarFlatExpr)node.jjtGetChild(3));
if (s.length > 200)
// for large number of taks (>200)
// edge-finding is not used
pose(new Cumulative(s, d, r, b, false, true, false));
else
pose(new Cumulative(s, d, r, b, true, true, false));
}
else if (p.startsWith("circuit", 6)) {
IntVar[] v = getVarArray((SimpleNode)node.jjtGetChild(0));
pose(new Circuit(v));
if ( domainConsistency && ! opt.getBoundConsistency()) // we add additional implied constraint if domain consistency is required
parameterListForAlldistincts.add(v);
}
else if (p.startsWith("subcircuit", 6)) {
IntVar[] v = getVarArray((SimpleNode)node.jjtGetChild(0));
pose(new Subcircuit(v));
}
else if (p.startsWith("alldiff", 6)) {
IntVar[] v = getVarArray((SimpleNode)node.jjtGetChild(0));
IntervalDomain dom = new IntervalDomain();
for (IntVar var : v)
dom = (IntervalDomain)dom.union( var.dom() );
if (v.length <= 100) { // && v.length == dom.getSize()) {
// we do not not pose Alldistinct directly because of possible inconsistency with its
// intiallization; we collect all vectors and pose it at the end when all constraints are posed
// pose(new Alldistinct(v));
if (boundsConsistency || opt.getBoundConsistency()) {
pose(new Alldiff(v));
// System.out.println("Alldiff imposed");
}
else { // domain consistency
parameterListForAlldistincts.add(v);
// System.out.println("Alldistinct imposed on " + java.util.Arrays.asList(v));
}
}
else {
pose(new Alldiff(v));
// System.out.println("Alldiff imposed");
}
}
else if (p.startsWith("alldistinct", 6)) {
IntVar[] v = getVarArray((SimpleNode)node.jjtGetChild(0));
// we do not not pose Alldistinct directly because of possible inconsistency with its
// intiallization; we collect all vectors and pose it at the end when all constraints are posed
// pose(new Alldistinct(v));
parameterListForAlldistincts.add(v);
// System.out.println("Alldistinct imposed "+ java.util.Arrays.asList(v));
}
else if (p.startsWith("among_var", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[] s = getVarArray((SimpleNode)node.jjtGetChild(1));
IntVar v = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
// we do not not pose AmongVar directly because of possible inconsistency with its
// intiallization; we collect all constraints and pose them at the end when all other constraints are posed
// ---- KK, 2015-10-17
// among must not have duplicated variables there
// could be constants that have the same value and
// are duplicated.
IntVar[] xx = new IntVar[x.length];
HashSet<IntVar> varSet = new HashSet<IntVar>();
for (int i = 0; i < x.length; i++) {
if (varSet.contains(x[i]) && x[i].singleton())
xx[i] = new IntVar(store, x[i].min(), x[i].max());
else {
xx[i] = x[i];
varSet.add(x[i]);
}
}
IntVar[] ss = new IntVar[s.length];
varSet = new HashSet<IntVar>();
for (int i = 0; i < s.length; i++) {
if (varSet.contains(s[i]) && s[i].singleton())
ss[i] = new IntVar(store, s[i].min(), s[i].max());
else {
ss[i] = s[i];
varSet.add(s[i]);
}
}
IntVar vv;
if (varSet.contains(v) && v.singleton())
vv = new IntVar(store, v.min(), v.max());
else
vv = v;
//----
delayedConstraints.add(new AmongVar(xx, ss, vv));
// pose(new AmongVar(x, s, v));
}
else if (p.startsWith("among", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
IntDomain s = getSetLiteral(node, 1);
IntVar v = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
// ---- KK, 2015-10-17
// among must not have duplicated variables. In x vecor
// could be constants that have the same value and
// are duplicated.
IntVar[] xx = new IntVar[x.length];
HashSet<IntVar> varSet = new HashSet<IntVar>();
for (int i = 0; i < x.length; i++) {
if (varSet.contains(x[i]) && x[i].singleton())
xx[i] = new IntVar(store, x[i].min(), x[i].max());
else {
xx[i] = x[i];
varSet.add(x[i]);
}
}
IntVar vv;
if (varSet.contains(v) && v.singleton())
vv = new IntVar(store, v.min(), v.max());
else
vv = v;
//----
IntervalDomain setImpl = new IntervalDomain();
for (ValueEnumeration e = s.valueEnumeration(); e.hasMoreElements();) {
int val = e.nextElement();
setImpl.unionAdapt(new IntervalDomain(val, val));
}
pose(new Among(xx, setImpl, vv));
// }
}
else if (p.startsWith("gcc", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[] c = getVarArray((SimpleNode)node.jjtGetChild(1));
int index_min = getInt((ASTScalarFlatExpr)node.jjtGetChild(2));
int index_max = index_min + c.length - 1;
for (int i=0; i<x.length; i++) {
if (index_min>x[i].max() || index_max<x[i].min()) {
System.err.println("%% ERROR: gcc domain error in variable " + x[i]);
System.exit(0);
}
if (index_min>x[i].min() && index_min<x[i].max())
x[i].domain.inMin(store.level, x[i], index_min);
if (index_max<x[i].max() && index_max>x[i].min())
x[i].domain.inMax(store.level, x[i], index_max);
}
// System.out.println("c = " + Arrays.asList(x));
// =========> remove all non-existing-values counters
IntDomain gcc_dom = new IntervalDomain();
for (IntVar v : x)
gcc_dom = gcc_dom.union( v.dom() );
ArrayList<Var> c_list = new ArrayList<Var>();
for (int i=0; i<c.length; i++)
if ( gcc_dom.contains(i+index_min ) )
c_list.add(c[i]);
else
pose(new XeqC(c[i], 0));
IntVar[] c_array = new IntVar[c_list.size()];
c_array = c_list.toArray(c_array);
// =========>
pose(new GCC(x, c_array));
}
else if (p.startsWith("global_cardinality_closed", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
int[] cover = getIntArray((SimpleNode)node.jjtGetChild(1));
IntVar[] counter = getVarArray((SimpleNode)node.jjtGetChild(2));
IntDomain gcc_dom = new IntervalDomain();
for (int e : cover)
gcc_dom = gcc_dom.union( e );
for (IntVar v : x)
v.domain.in(store.level, v, gcc_dom);
pose( new GCC(x, counter));
}
else if (p.startsWith("global_cardinality_low_up_closed", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
int[] cover = getIntArray((SimpleNode)node.jjtGetChild(1));
int[] low = getIntArray((SimpleNode)node.jjtGetChild(2));
int[] up = getIntArray((SimpleNode)node.jjtGetChild(3));
IntDomain gcc_dom = new IntervalDomain();
for (int e : cover)
gcc_dom = gcc_dom.union( e );
for (IntVar v : x)
v.domain.in(store.level, v, gcc_dom);
IntVar[] counter = new IntVar[low.length];
for (int i = 0; i < counter.length; i++)
counter[i] = new IntVar(store, "counter"+i, low[i], up[i]);
pose( new GCC(x, counter));
}
else if (p.startsWith("diff2_strict", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[] y = getVarArray((SimpleNode)node.jjtGetChild(1));
IntVar[] lx = getVarArray((SimpleNode)node.jjtGetChild(2));
IntVar[] ly = getVarArray((SimpleNode)node.jjtGetChild(3));
pose(new Disjoint(x, y, lx, ly));
}
else if (p.startsWith("diff2", 6)) {
IntVar[] v = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[][] r = new IntVar[v.length/4][4];
for (int i=0; i<r.length; i++)
for (int j=0; j<4; j++)
r[i][j] = v[4*i+j];
pose(new Diff2(r));
}
else if (p.startsWith("list_diff2", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[] y = getVarArray((SimpleNode)node.jjtGetChild(1));
IntVar[] lx = getVarArray((SimpleNode)node.jjtGetChild(2));
IntVar[] ly = getVarArray((SimpleNode)node.jjtGetChild(3));
pose(new Diff2(x, y, lx, ly));
}
else if (p.startsWith("count", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
int y = getInt((ASTScalarFlatExpr)node.jjtGetChild(1));
IntVar c = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
pose(new Count(x, c, y));
// pose(new Among(x, new IntervalDomain(y,y), c));
}
else if (p.startsWith("nvalue", 6)) {
IntVar n = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(1));
pose(new Values(x, n));
}
else if (p.startsWith("minimum_arg_int", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar index = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
pose(new org.jacop.constraints.ArgMin(x, index));
}
else if (p.startsWith("minimum", 6)) {
IntVar n = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(1));
pose(new org.jacop.constraints.Min(x, n));
}
else if (p.startsWith("maximum_arg_int", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar index = getVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
pose(new org.jacop.constraints.ArgMax(x, index));
}
else if (p.startsWith("maximum", 6)) {
IntVar n = getVariable((ASTScalarFlatExpr)node.jjtGetChild(0));
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(1));
pose(new org.jacop.constraints.Max(x, n));
}
else if (p.startsWith("table_int", 6) ||
p.startsWith("table_bool", 6)) {
IntVar[] v = getVarArray((SimpleNode)node.jjtGetChild(0));
int size = v.length;
int[] tbl = getIntArray((SimpleNode)node.jjtGetChild(1));
int[][] t = new int[tbl.length/size][size];
for (int i=0; i<t.length; i++)
for (int j=0; j<size; j++)
t[i][j] = tbl[size*i+j];
// we do not not pose ExtensionalSupportMDD directly because of possible inconsistency with its
// intiallization; we collect all constraints and pose them at the end when all other constraints are posed
delayedConstraints.add(new ExtensionalSupportMDD(v, t));
//pose(new ExtensionalSupportMDD(v, t));
}
else if (p.startsWith("assignment", 6)) {
IntVar[] f = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[] invf = getVarArray((SimpleNode)node.jjtGetChild(1));
int index_f = getInt((ASTScalarFlatExpr)node.jjtGetChild(2));
int index_invf = getInt((ASTScalarFlatExpr)node.jjtGetChild(3));
// we do not not pose Assignment directly because of possible inconsistency with its
// intiallization; we collect all constraints and pose them at the end when all other constraints are posed
if ( domainConsistency && !opt.getBoundConsistency()) // we add additional implied constraint if domain consistency is required
parameterListForAlldistincts.add(f);
delayedConstraints.add(new Assignment(f, invf, index_f, index_invf));
// pose(new Assignment(f, invf, index_f, index_invf));
}
else if (p.startsWith("regular", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
int Q = getInt((ASTScalarFlatExpr)node.jjtGetChild(1));
int S = getInt((ASTScalarFlatExpr)node.jjtGetChild(2));
int[] d = getIntArray((SimpleNode)node.jjtGetChild(3));
int q0 = getInt((ASTScalarFlatExpr)node.jjtGetChild(4));
IntDomain F = getSetLiteral(node, 5);
int minIndex = getInt((ASTScalarFlatExpr)node.jjtGetChild(6));
/* it seems that it is does not needed since mapping in Regular
is only used to queue variables and identify them; constant variables
will never be queued
// regular must not have duplicated variables. In x vecor
// could be constants that have the same value and
// are duplicated.
IntVar[] xx = new IntVar[x.length];
HashSet<IntVar> varSet = new HashSet<IntVar>();
for (int i = 0; i < x.length; i++) {
if (varSet.contains(x[i]) && x[i].singleton())
xx[i] = new IntVar(store, x[i].min(), x[i].max());
else {
xx[i] = x[i];
varSet.add(xx[i]);
}
}
//----
*/
// Build DFA
FSM dfa = new FSM();
FSMState[] s = new FSMState[Q];
for (int i=0; i<s.length; i++) {
s[i] = new FSMState();
dfa.allStates.add(s[i]);
}
dfa.initState = s[q0 - 1];
ValueEnumeration final_states = F.valueEnumeration(); //new SetValueEnumeration(F);
while (final_states.hasMoreElements())
dfa.finalStates.add(s[final_states.nextElement()-1]);
// System.out.println("init state: "+ dfa.initState+", "+ F + " final states: "+dfa.finalStates +", first state: "+ s[0]);
for (int i=0; i<Q; i++) {
// System.out.print(i+": ");
for (int j=0; j<S; j++)
if (d[i*S+j] != 0) {
s[i].transitions.add(new FSMTransition(new IntervalDomain(j+minIndex,j+minIndex), s[d[i*S+j]-minIndex]));
// System.out.print("("+(int)(j+minIndex)+") -> "+ (int)(d[i*S+j]-minIndex)+", ");
}
// System.out.println();
}
pose(new Regular(dfa, x));
// System.out.println(dfa+"\n");
// System.out.println("Regular("+Arrays.asList(x)+", "+Q+", "+
// S+", "+Arrays.asList(d)+", "+q0+", "+
// dfa.finalStates+", "+minIndex+")");
}
else if (p.startsWith("knapsack", 6)) {
int[] weights = getIntArray((SimpleNode)node.jjtGetChild(0));
int[] profits = getIntArray((SimpleNode)node.jjtGetChild(1));
IntVar W = getVariable((ASTScalarFlatExpr)node.jjtGetChild(2));
IntVar P = getVariable((ASTScalarFlatExpr)node.jjtGetChild(3));
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(4));
// System.out.println("Knapsack("+
// java.util.Arrays.toString(weights) +
// ", "+ java.util.Arrays.toString(profits) +
// ", "+ W +
// ", "+ P +
// ", " + java.util.Arrays.asList(x) +")");
pose(new Knapsack(profits, weights, x, W, P));
}
else if (p.startsWith("sequence", 6)) { // implements jacop_sequence
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
IntDomain u = getSetLiteral(node, 1);
int q = getInt((ASTScalarFlatExpr)node.jjtGetChild(2));
int min = getInt((ASTScalarFlatExpr)node.jjtGetChild(3));
int max = getInt((ASTScalarFlatExpr)node.jjtGetChild(4));
IntervalDomain setImpl = new IntervalDomain();
for(int i = 0; true ;i++) {
Interval val = u.getInterval(i);
if (val != null)
setImpl.unionAdapt(val);
else
break;
}
DecomposedConstraint c = new Sequence(x, setImpl, q, min, max);
// System.out.println("sequence("+java.util.Arrays.asList(x)+", "+
// u+", "+q+", "+", "+min+", "+max);
store.imposeDecomposition(c);
}
else if (p.startsWith("stretch", 6)) {
int[] values = getIntArray((SimpleNode)node.jjtGetChild(0));
int[] min = getIntArray((SimpleNode)node.jjtGetChild(1));
int[] max = getIntArray((SimpleNode)node.jjtGetChild(2));
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(3));
// System.out.println("Stretch("+java.util.Arrays.asList(values) +
// ", " + java.util.Arrays.asList(min) +
// ", " + java.util.Arrays.asList(max) +
// ", "+ java.util.Arrays.asList(x)+")");
DecomposedConstraint c = new Stretch(values, min, max, x);
store.imposeDecomposition(c);
}
else if (p.startsWith("disjoint", 6)) {
SetVar v1 = getSetVariable(node, 0);
SetVar v2 = getSetVariable(node, 1);
pose(new AdisjointB(v1, v2));
}
// else if (p.startsWith("sequence", 6)) {
// Variable[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
// Set u = getSetLiteral((SimpleNode)node, 1);
// int q = getInt((ASTScalarFlatExpr)node.jjtGetChild(2));
// int min = getInt((ASTScalarFlatExpr)node.jjtGetChild(3));
// int max = getInt((ASTScalarFlatExpr)node.jjtGetChild(4));
// DecomposedConstraint c = new Sequence(x, u, q, min, max);
// System.out.println("sequence("+Arrays.asList(x)+", "+
// u+", "+q+", "+", "+min+", "+max);
// store.imposeDecomposition(c);
// }
else if (p.startsWith("network", 6)) {
int[] arc = getIntArray((SimpleNode)node.jjtGetChild(0));
IntVar[] flow = getVarArray((SimpleNode)node.jjtGetChild(1));
IntVar[] weight = getVarArray((SimpleNode)node.jjtGetChild(2));
int[] balance = getIntArray((SimpleNode)node.jjtGetChild(3));
IntVar cost = getVariable((ASTScalarFlatExpr)node.jjtGetChild(4));
// System.out.println("NetworkFlow("+ arc +
// ", " + java.util.Arrays.asList(flow) +
// ", " + java.util.Arrays.asList(weight) +
// ", "+ balance +
// ", "+ cost +")");
NetworkBuilder net = new NetworkBuilder();
Node[] netNode = new Node[balance.length];
for (int i = 0; i < balance.length; i++)
netNode[i] = net.addNode("n_"+i, balance[i]);
for (int i = 0; i < flow.length; i++) {
net.addArc(netNode[arc[2*i]-1], netNode[arc[2*i+1]-1], weight[i], flow[i]);
}
net.setCostVariable(cost);
pose(new NetworkFlow(net));
}
else if (p.startsWith("lex_less_int", 6) || p.startsWith("lex_less_bool", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[] y = getVarArray((SimpleNode)node.jjtGetChild(1));
// System.out.println ("lex_less_int: x.length = " + x.length + " y.length = " + y.length);
pose(new LexOrder(x, y, true));
// DecomposedConstraint c = new org.jacop.constraints.Lex(new IntVar[][] {x, y}, true);
// store.imposeDecomposition(c);
}
else if (p.startsWith("lex_lesseq_int", 6) || p.startsWith("lex_lesseq_bool", 6)) {
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[] y = getVarArray((SimpleNode)node.jjtGetChild(1));
// System.out.println ("lex_lesseq_int: x.length = " + x.length + " y.length = " + y.length);
pose(new LexOrder(x, y, false));
// DecomposedConstraint c = new org.jacop.constraints.Lex(new IntVar[][] {x, y});
// store.imposeDecomposition(c);
}
else if (p.startsWith("bin_packing", 6)) {
IntVar[] bin = getVarArray((SimpleNode)node.jjtGetChild(0));
IntVar[] capacity = getVarArray((SimpleNode)node.jjtGetChild(1));
int[] w = getIntArray((SimpleNode)node.jjtGetChild(2));
// ---- KK, 2015-10-18
// bin_packing must not have duplicated variables. on x vecor
// could be constants that have the same value and
// are duplicated.
IntVar[] binx = new IntVar[bin.length];
HashSet<IntVar> varSet = new HashSet<IntVar>();
for (int i = 0; i < bin.length; i++) {
if (varSet.contains(bin[i]) && bin[i].singleton())
binx[i] = new IntVar(store, bin[i].min(), bin[i].max());
else {
binx[i] = bin[i];
varSet.add(bin[i]);
}
}
pose( new org.jacop.constraints.binpacking.Binpacking(binx, capacity, w) );
// Constraint binPack = new org.jacop.constraints.binpacking.Binpacking(bin, capacity, w);
// delayedConstraints.add(binPack);
}
else if (p.startsWith("float_maximum", 6)) {
FloatVar p2 = getFloatVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
FloatVar[] p1 = getFloatVarArray((SimpleNode)node.jjtGetChild(0));
pose(new org.jacop.floats.constraints.Max(p1, p2));
}
else if (p.startsWith("float_minimum", 6)) {
FloatVar p2 = getFloatVariable((ASTScalarFlatExpr)node.jjtGetChild(1));
FloatVar[] p1 = getFloatVarArray((SimpleNode)node.jjtGetChild(0));
pose(new org.jacop.floats.constraints.Min(p1, p2));
}
else if (p.startsWith("geost", 6)) {
int dim = getInt((ASTScalarFlatExpr)node.jjtGetChild(0));
int[] rect_size = getIntArray((SimpleNode)node.jjtGetChild(1));
int[] rect_offset = getIntArray((SimpleNode)node.jjtGetChild(2));
IntDomain[] shape = getSetArray((SimpleNode)node.jjtGetChild(3));
IntVar[] x = getVarArray((SimpleNode)node.jjtGetChild(4));
IntVar[] kind = getVarArray((SimpleNode)node.jjtGetChild(5));
// System.out.println("dim = " + dim);
// System.out.print("rect_size = [");
// for (int i = 0; i < rect_size.length; i++)
// System.out.print(" " + rect_size[i]);
// System.out.print("]\nrect_offset = [");
// for (int i = 0; i < rect_offset.length; i++)
// System.out.print(" " + rect_offset[i]);
// System.out.println("]\nshape = " + java.util.Arrays.asList(shape));
// System.out.println("x = " + java.util.Arrays.asList(x));
// System.out.println("kind = " + java.util.Arrays.asList(kind));
// System.out.println("===================");
ArrayList<Shape> shapes = new ArrayList<Shape>();
// dummy shape to have right indexes for kind (starting from 1)
ArrayList<DBox> dummy = new ArrayList<DBox>();
int[] offsetDummy = new int[dim];
int[] sizeDummy = new int[dim];
for (int k = 0; k < dim; k++) {
offsetDummy[k] = 0;
sizeDummy[k] = 1;
}
dummy.add(new DBox(offsetDummy, sizeDummy));
shapes.add( new Shape(0, dummy));
// create all shapes (starting with id=1)
for (int i = 0; i < shape.length; i++) {
ArrayList<DBox> shape_i = new ArrayList<DBox>();
for (ValueEnumeration e = shape[i].valueEnumeration(); e.hasMoreElements();) {
int j = e.nextElement();
int[] offset = new int[dim];
int[] size = new int[dim];
for (int k = 0; k < dim; k++) {
offset[k] = rect_offset[(j-1)*dim+k];
size[k] = rect_size[(j-1)*dim+k];
}
shape_i.add(new DBox(offset, size));
}
shapes.add( new Shape((i+1), shape_i) );
}
// for (int i = 0; i < shapes.size(); i++)
// System.out.println("*** " + shapes.get(i));
ArrayList<GeostObject> objects = new ArrayList<GeostObject>();
for (int i = 0; i < kind.length; i++) {
IntVar[] coords = new IntVar[dim];
for (int k = 0; k < dim; k++)
coords[k] = x[i*dim+k];
// System.out.println("coords = " + java.util.Arrays.asList(coords));
IntVar start = new IntVar(store, "start["+i+"]", 0,0);
IntVar duration = new IntVar(store, "duration["+i+"]", 1,1);
IntVar end = new IntVar(store, "end["+i+"]", 1, 1);
GeostObject obj = new GeostObject(i, coords, kind[i], start, duration, end);
objects.add(obj);
}
// System.out.println("===========");
// for (int i = 0; i < objects.size(); i++)
// System.out.println(objects.get(i));
// System.out.println("===========");
ArrayList<ExternalConstraint> constraints = new ArrayList<ExternalConstraint>();
int[] dimensions = new int[dim+1];
for (int i = 0; i < dim+1; i++)
dimensions[i] = i;
NonOverlapping constraint1 = new NonOverlapping(objects, dimensions);
constraints.add(constraint1);
if (p.startsWith("geost_bb", 6)) {
int[] lb = getIntArray((SimpleNode)node.jjtGetChild(6));
int[] ub = getIntArray((SimpleNode)node.jjtGetChild(7));
// System.out.print("[");
// for (int i = 0; i < lb.length; i++)
// System.out.print(" " + lb[i]);
// System.out.print("]\n[");
// for (int i = 0; i < ub.length; i++)
// System.out.print(" " + ub[i]);
// System.out.println("]");
InArea constraint2 = new InArea(new DBox(lb, ub), null);
constraints.add(constraint2);
}
pose( new Geost(objects, constraints, shapes) );
}
else
System.err.println("%% ERROR: Constraint "+p+" not supported.");
// >>========== JaCoP constraints ==================
else
System.err.println("%% ERROR: Constraint "+p+" not supported.");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void readAuction(String filename) {
noGoods = 0;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));
// the first line represents the input goods
String line = br.readLine();
StringTokenizer tk = new StringTokenizer(line, "(),: ");
initialQuantity = new ArrayList<Integer>();
while (tk.hasMoreTokens()) {
noGoods++;
tk.nextToken();
initialQuantity.add(Integer.parseInt(tk.nextToken()));
}
// the second line represents the output goods
line = br.readLine();
tk = new StringTokenizer(line, "(),: ");
finalQuantity = new ArrayList<Integer>();
while (tk.hasMoreTokens()) {
tk.nextToken();
finalQuantity.add(Integer.parseInt(tk.nextToken()));
}
// until the word price is read, one is reading transformations.
// Assume that the transformations are properly grouped
line = br.readLine();
int bidCounter = 1;
int bid_xorCounter = 1;
int transformationCounter = 0;
int goodsCounter = 0;
int Id, in, out;
int[] input;
int[] output;
bids = new ArrayList<ArrayList<ArrayList<Transformation>>>();
bids.add(new ArrayList<ArrayList<Transformation>>());
(bids.get(0)).add(new ArrayList<Transformation>());
while (!line.equals("price")) {
tk = new StringTokenizer(line, "():, ");
transformationCounter++;
if (Integer.parseInt(tk.nextToken()) > bidCounter) {
bidCounter++;
bid_xorCounter = 1;
transformationCounter = 1;
bids.add(new ArrayList<ArrayList<Transformation>>());
bids.get(bidCounter - 1).add(new ArrayList<Transformation>());
}
//System.out.println(bidCounter + " " + bid_xorCounter);
if (Integer.parseInt(tk.nextToken()) > bid_xorCounter) {
bid_xorCounter++;
transformationCounter = 1;
bids.get(bidCounter - 1).add(new ArrayList<Transformation>());
}
// this token contains the number of the transformation
tk.nextToken();
bids.get(bidCounter - 1).get(bid_xorCounter - 1).add(new Transformation());
bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds = new ArrayList<Integer>();
bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta = new ArrayList<Delta>();
input = new int[noGoods];
output = new int[noGoods];
goodsCounter = 0;
while (tk.hasMoreTokens()) {
goodsCounter++;
//System.out.println(goodsCounter);
if (goodsCounter <= noGoods) {
Id = Integer.parseInt(tk.nextToken()) - 1;
in = Integer.parseInt(tk.nextToken());
input[Id] = in;
} else {
Id = Integer.parseInt(tk.nextToken()) - 1;
out = Integer.parseInt(tk.nextToken());
output[Id] = out;
}
}
for (int i = 0; i < noGoods; i++) {
//delta = output[i] - input[i];
if (output[i] > maxDelta) {
maxDelta = output[i];
} else if (-input[i] < minDelta) {
minDelta = -input[i];
}
if (output[i] != 0 || input[i] != 0) {
//System.out.print(i + " " + input[i] + ":" + output[i] + " ");
//System.out.println(bidCounter + " " + bid_xorCounter + " " + transformationCounter + " " + i + " " + delta);
bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds.add(i);
bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta
.add(new Delta(input[i], output[i]));
}
}
System.out.print("\n");
line = br.readLine();
}
// now read in the price for each xor bid
costs = new ArrayList<ArrayList<Integer>>();
costs.add(new ArrayList<Integer>());
bidCounter = 1;
line = br.readLine();
while (!(line == null)) {
tk = new StringTokenizer(line, "(): ");
if (Integer.parseInt(tk.nextToken()) > bidCounter) {
bidCounter++;
costs.add(new ArrayList<Integer>());
}
// this token contains the xor_bid id.
tk.nextToken();
costs.get(bidCounter - 1).add(Integer.parseInt(tk.nextToken()));
line = br.readLine();
}
} catch (FileNotFoundException ex) {
System.err.println("You need to run this program in a directory that contains the required file.");
System.err.println(ex);
System.exit(-1);
} catch (IOException ex) {
System.err.println(ex);
}
System.out.println(this.maxCost);
System.out.println(this.maxDelta);
System.out.println(this.minDelta);
}
#location 144
#vulnerability type RESOURCE_LEAK | #fixed code
public void readAuction(String filename) {
noGoods = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));
// the first line represents the input goods
String line = br.readLine();
StringTokenizer tk = new StringTokenizer(line, "(),: ");
initialQuantity = new ArrayList<Integer>();
while (tk.hasMoreTokens()) {
noGoods++;
tk.nextToken();
initialQuantity.add(Integer.parseInt(tk.nextToken()));
}
// the second line represents the output goods
line = br.readLine();
tk = new StringTokenizer(line, "(),: ");
finalQuantity = new ArrayList<Integer>();
while (tk.hasMoreTokens()) {
tk.nextToken();
finalQuantity.add(Integer.parseInt(tk.nextToken()));
}
// until the word price is read, one is reading transformations.
// Assume that the transformations are properly grouped
line = br.readLine();
int bidCounter = 1;
int bid_xorCounter = 1;
int transformationCounter = 0;
int goodsCounter = 0;
int Id, in, out;
int[] input;
int[] output;
bids = new ArrayList<ArrayList<ArrayList<Transformation>>>();
bids.add(new ArrayList<ArrayList<Transformation>>());
(bids.get(0)).add(new ArrayList<Transformation>());
while (!line.equals("price")) {
tk = new StringTokenizer(line, "():, ");
transformationCounter++;
if (Integer.parseInt(tk.nextToken()) > bidCounter) {
bidCounter++;
bid_xorCounter = 1;
transformationCounter = 1;
bids.add(new ArrayList<ArrayList<Transformation>>());
bids.get(bidCounter - 1).add(new ArrayList<Transformation>());
}
//System.out.println(bidCounter + " " + bid_xorCounter);
if (Integer.parseInt(tk.nextToken()) > bid_xorCounter) {
bid_xorCounter++;
transformationCounter = 1;
bids.get(bidCounter - 1).add(new ArrayList<Transformation>());
}
// this token contains the number of the transformation
tk.nextToken();
bids.get(bidCounter - 1).get(bid_xorCounter - 1).add(new Transformation());
bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds = new ArrayList<Integer>();
bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta = new ArrayList<Delta>();
input = new int[noGoods];
output = new int[noGoods];
goodsCounter = 0;
while (tk.hasMoreTokens()) {
goodsCounter++;
//System.out.println(goodsCounter);
if (goodsCounter <= noGoods) {
Id = Integer.parseInt(tk.nextToken()) - 1;
in = Integer.parseInt(tk.nextToken());
input[Id] = in;
} else {
Id = Integer.parseInt(tk.nextToken()) - 1;
out = Integer.parseInt(tk.nextToken());
output[Id] = out;
}
}
for (int i = 0; i < noGoods; i++) {
//delta = output[i] - input[i];
if (output[i] > maxDelta) {
maxDelta = output[i];
} else if (-input[i] < minDelta) {
minDelta = -input[i];
}
if (output[i] != 0 || input[i] != 0) {
//System.out.print(i + " " + input[i] + ":" + output[i] + " ");
//System.out.println(bidCounter + " " + bid_xorCounter + " " + transformationCounter + " " + i + " " + delta);
bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds.add(i);
bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta
.add(new Delta(input[i], output[i]));
}
}
System.out.print("\n");
line = br.readLine();
}
// now read in the price for each xor bid
costs = new ArrayList<ArrayList<Integer>>();
costs.add(new ArrayList<Integer>());
bidCounter = 1;
line = br.readLine();
while (!(line == null)) {
tk = new StringTokenizer(line, "(): ");
if (Integer.parseInt(tk.nextToken()) > bidCounter) {
bidCounter++;
costs.add(new ArrayList<Integer>());
}
// this token contains the xor_bid id.
tk.nextToken();
costs.get(bidCounter - 1).add(Integer.parseInt(tk.nextToken()));
line = br.readLine();
}
} catch (FileNotFoundException ex) {
System.err.println("You need to run this program in a directory that contains the required file.");
System.err.println(ex);
throw new RuntimeException("You need to run this program in a directory that contains the required file : " + filename);
} catch (IOException ex) {
System.err.println(ex);
}
finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(this.maxCost);
System.out.println(this.maxDelta);
System.out.println(this.minDelta);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void updateTable(HashSet<IntVar> fdvs) {
for (IntVar v : fdvs) {
// recent pruning
IntDomain cd = v.dom();
IntDomain pd = cd.previousDomain();
IntDomain rp;
int delta;
if (pd == null) {
rp = cd;
delta = IntDomain.MaxInt;
} else {
rp = pd.subtract(cd);
delta = rp.getSize();
if (delta == 0)
continue;
}
mask = 0; // clear mask
int xIndex = varMap.get(v);
Map<Integer, Long> xSupport = supports[xIndex];
if (delta < cd.getSize()) { // incremental update
ValueEnumeration e = rp.valueEnumeration();
while (e.hasMoreElements()) {
Long bs = xSupport.get(e.nextElement());
if (bs != null)
mask |= (bs.longValue());
}
mask = ~mask;
} else { // reset-based update
ValueEnumeration e = cd.valueEnumeration();
while (e.hasMoreElements()) {
Long bs = xSupport.get(e.nextElement());
if (bs != null)
mask |= (bs.longValue());
}
}
boolean empty = intersectWithMask();
if (empty)
throw store.failException;
}
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
boolean validTuple(int index) {
int[] t = tuple[index];
int n = t.length;
int i = 0;
while (i < n) {
if (!x[i].dom().contains(t[i]))
return false;
i++;
}
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
StringInterner stringInterner() {
if (stringInterner == null)
stringInterner = new StringInterner(8 * 1024);
return stringInterner;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
AbstractBytes() {
this(new VanillaBytesMarshallerFactory(), new AtomicInteger(1));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSimpleLock() {
DirectBytes bytes = new DirectStore(64).createSlice();
bytes.writeLong(0, -1L);
assertFalse(bytes.tryLockLong(0));
bytes.writeLong(0, 0L);
assertTrue(bytes.tryLockLong(0));
long val1 = bytes.readLong(0);
assertTrue(bytes.tryLockLong(0));
bytes.unlockLong(0);
assertEquals(val1, bytes.readLong(0));
bytes.unlockLong(0);
assertEquals(0L, bytes.readLong(0));
try {
bytes.unlockLong(0);
fail();
} catch (IllegalMonitorStateException e) {
// expected.
}
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSimpleLock() {
DirectBytes bytes = new DirectStore(64).bytes();
bytes.writeLong(0, -1L);
assertFalse(bytes.tryLockLong(0));
bytes.writeLong(0, 0L);
assertTrue(bytes.tryLockLong(0));
long val1 = bytes.readLong(0);
assertTrue(bytes.tryLockLong(0));
bytes.unlockLong(0);
assertEquals(val1, bytes.readLong(0));
bytes.unlockLong(0);
assertEquals(0L, bytes.readLong(0));
try {
bytes.unlockLong(0);
fail();
} catch (IllegalMonitorStateException e) {
// expected.
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLocking() throws Exception {
// a page
long start = System.nanoTime();
final DirectStore store1 = DirectStore.allocate(1 << 12);
final int lockCount = 20 * 1000000;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
long id = Thread.currentThread().getId();
System.out.println("Thread " + id);
assertEquals(0, id >>> 24);
try {
DirectBytes slice1 = store1.createSlice();
for (int i = 0; i < lockCount; i++) {
slice1.busyLockInt(0);
int toggle1 = slice1.readInt(4);
if (toggle1 == 1) {
slice1.writeInt(4, 0);
} else {
i--;
}
slice1.unlockInt(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
long id = Thread.currentThread().getId();
assertEquals(0, id >>> 24);
System.out.println("Thread " + id);
DirectBytes slice1 = store1.createSlice();
for (int i = 0; i < lockCount; i++) {
slice1.busyLockInt(0);
int toggle1 = slice1.readInt(4);
if (toggle1 == 0) {
slice1.writeInt(4, 1);
} else {
i--;
}
slice1.unlockInt(0);
}
store1.free();
long time = System.nanoTime() - start;
System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time));
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testLocking() {
// a page
long start = System.nanoTime();
final DirectStore store1 = DirectStore.allocate(1 << 12);
final int lockCount = 20 * 1000 * 1000;
new Thread(new Runnable() {
@Override
public void run() {
manyToggles(store1, lockCount, 1, 0);
}
}).start();
manyToggles(store1, lockCount, 0, 1);
store1.free();
long time = System.nanoTime() - start;
System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String... args) throws IOException, InterruptedException {
boolean toggleTo = Boolean.parseBoolean(args[0]);
File tmpFile = new File(System.getProperty("java.io.tmpdir"), "lock-test.dat");
FileChannel fc = new RandomAccessFile(tmpFile, "rw").getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, RECORDS * RECORD_SIZE);
ByteBufferBytes bytes = new ByteBufferBytes(mbb);
long start = 0;
for (int i = -WARMUP / RECORDS; i < (RUNS + RECORDS - 1) / RECORDS; i++) {
if (i == 0) {
start = System.nanoTime();
System.out.println("Started");
}
for (int j = 0; j < RECORDS; j++) {
int recordOffset = j * RECORD_SIZE;
for (int t = 9999; t >= 0; t--) {
if (t == 0)
if (i >= 0) {
throw new AssertionError("Didn't toggle in time !??");
} else {
System.out.println("waiting");
t = 9999;
Thread.sleep(200);
}
bytes.busyLockLong(recordOffset + LOCK);
try {
boolean flag = bytes.readBoolean(recordOffset + FLAG);
if (flag == toggleTo) {
if (t % 100 == 0)
System.out.println("j: " + j + " is " + flag);
continue;
}
bytes.writeBoolean(recordOffset + FLAG, toggleTo);
break;
} finally {
bytes.unlockLong(recordOffset + LOCK);
}
}
}
}
long time = System.nanoTime() - start;
final int toggles = (RUNS + RECORDS - 1) / RECORDS * RECORDS * 2; // one for each of two processes.
System.out.printf("Toogled %,d times with an average delay of %,d ns%n",
toggles, time / toggles);
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String... args) throws IOException, InterruptedException {
boolean toggleTo = Boolean.parseBoolean(args[0]);
File tmpFile = new File(System.getProperty("java.io.tmpdir"), "lock-test.dat");
FileChannel fc = new RandomAccessFile(tmpFile, "rw").getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, RECORDS * RECORD_SIZE);
ByteBufferBytes bytes = new ByteBufferBytes(mbb);
long start = 0;
for (int i = -WARMUP / RECORDS; i < (RUNS + RECORDS - 1) / RECORDS; i++) {
if (i == 0) {
start = System.nanoTime();
System.out.println("Started");
}
for (int j = 0; j < RECORDS; j++) {
int recordOffset = j * RECORD_SIZE;
for (int t = 9999; t >= 0; t--) {
if (t == 0)
if (i >= 0) {
throw new AssertionError("Didn't toggle in time !??");
} else {
System.out.println("waiting");
t = 9999;
Thread.sleep(200);
}
bytes.busyLockLong(recordOffset + LOCK);
try {
boolean flag = bytes.readBoolean(recordOffset + FLAG);
if (flag == toggleTo) {
if (t % 100 == 0)
System.out.println("j: " + j + " is " + flag);
continue;
}
bytes.writeBoolean(recordOffset + FLAG, toggleTo);
break;
} finally {
bytes.unlockLong(recordOffset + LOCK);
}
}
}
}
long time = System.nanoTime() - start;
final int toggles = (RUNS + RECORDS - 1) / RECORDS * RECORDS * 2; // one for each of two processes.
System.out.printf("Toogled %,d times with an average delay of %,d ns%n",
toggles, time / toggles);
fc.close();
tmpFile.deleteOnExit();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLocking() throws Exception {
// a page
final DirectStore store1 = DirectStore.allocate(1 << 12);
final DirectStore store2 = DirectStore.allocate(1 << 12);
final int lockCount = 10 * 1000000;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
long id = Thread.currentThread().getId();
System.out.println("Thread " + id);
assertEquals(0, id >>> 24);
int expected = (1 << 24) | (int) id;
try {
DirectBytes slice1 = store1.createSlice();
DirectBytes slice2 = store2.createSlice();
for (int i = 0; i < lockCount; i += 2) {
slice1.busyLockInt(0);
slice2.busyLockInt(0);
int lockValue1 = slice1.readInt(0);
if (lockValue1 != expected)
assertEquals(expected, lockValue1);
int lockValue2 = slice2.readInt(0);
if (lockValue2 != expected)
assertEquals(expected, lockValue2);
int toggle1 = slice1.readInt(4);
if (toggle1 == 1) {
slice1.writeInt(4, 0);
// if (i % 10000== 0)
// System.out.println("t: " + i);
} else {
i--;
}
int toggle2 = slice2.readInt(4);
if (toggle2 == 1) {
slice2.writeInt(4, 0);
// if (i % 10000== 0)
// System.out.println("t: " + i);
} else {
i--;
}
int lockValue1A = slice1.readInt(0);
int lockValue2A = slice1.readInt(0);
try {
slice2.unlockInt(0);
slice1.unlockInt(0);
} catch (IllegalStateException e) {
int lockValue1B = slice1.readInt(0);
int lockValue2B = slice2.readInt(0);
System.err.println("i= " + i +
" lock: " + Integer.toHexString(lockValue1A) + " / " + Integer.toHexString(lockValue2A) +
" lock: " + Integer.toHexString(lockValue1B) + " / " + Integer.toHexString(lockValue2B));
throw e;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
long id = Thread.currentThread().getId();
assertEquals(0, id >>> 24);
int expected = (1 << 24) | (int) id;
System.out.println("Thread " + id);
DirectBytes slice1 = store1.createSlice();
DirectBytes slice2 = store2.createSlice();
for (int i = 0; i < lockCount; i += 2) {
slice1.busyLockInt(0);
slice2.busyLockInt(0);
int lockValue1 = slice1.readInt(0);
if (lockValue1 != expected)
assertEquals(expected, lockValue1);
int lockValue2 = slice2.readInt(0);
if (lockValue2 != expected)
assertEquals(expected, lockValue2);
int toggle1 = slice1.readInt(4);
if (toggle1 == 0) {
slice1.writeInt(4, 1);
// if (i % 10000== 0)
// System.out.println("t: " + i);
} else {
i--;
}
int toggle2 = slice2.readInt(4);
if (toggle2 == 0) {
slice2.writeInt(4, 1);
// if (i % 10000== 0)
// System.out.println("t: " + i);
} else {
i--;
}
int lockValue1A = slice1.readInt(0);
int lockValue2A = slice1.readInt(0);
try {
slice2.unlockInt(0);
slice1.unlockInt(0);
} catch (IllegalStateException e) {
int lockValue1B = slice1.readInt(0);
int lockValue2B = slice2.readInt(0);
System.err.println("i= " + i +
" lock: " + Integer.toHexString(lockValue1A) + " / " + Integer.toHexString(lockValue2A) +
" lock: " + Integer.toHexString(lockValue1B) + " / " + Integer.toHexString(lockValue2B));
throw e;
}
}
store1.free();
store2.free();
}
#location 51
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testLocking() throws Exception {
// a page
long start = System.nanoTime();
final DirectStore store1 = DirectStore.allocate(1 << 12);
final int lockCount = 20 * 1000000;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
long id = Thread.currentThread().getId();
System.out.println("Thread " + id);
assertEquals(0, id >>> 24);
try {
DirectBytes slice1 = store1.createSlice();
for (int i = 0; i < lockCount; i++) {
slice1.busyLockInt(0);
int toggle1 = slice1.readInt(4);
if (toggle1 == 1) {
slice1.writeInt(4, 0);
} else {
i--;
}
slice1.unlockInt(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
long id = Thread.currentThread().getId();
assertEquals(0, id >>> 24);
System.out.println("Thread " + id);
DirectBytes slice1 = store1.createSlice();
for (int i = 0; i < lockCount; i++) {
slice1.busyLockInt(0);
int toggle1 = slice1.readInt(4);
if (toggle1 == 0) {
slice1.writeInt(4, 1);
} else {
i--;
}
slice1.unlockInt(0);
}
store1.free();
long time = System.nanoTime() - start;
System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testReadWrite() {
DirectStore ds = new DirectStore(null, 1024);
DirectBytes db = ds.createSlice();
RawCopier<A> aRawCopier = RawCopier.copies(A.class);
A a = new A();
a.i = 111;
a.j = -222;
a.k = 333;
a.s = "Hello";
aRawCopier.toBytes(a, db);
assertEquals(12, db.position());
assertEquals(111, db.readInt(0));
assertEquals(-222, db.readInt(4));
assertEquals(333, db.readInt(8));
A a2 = new A();
a2.i = 1;
a2.j = 2;
a2.k = 3;
// printInts(a2, 28);
db.position(0);
aRawCopier.fromBytes(db, a2);
// printInts(a2, 28);
assertEquals(111, a2.i);
assertEquals(-222, a2.j);
assertEquals(333, a2.k);
assertEquals(null, a2.s);
}
#location 30
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testReadWrite() {
DirectStore ds = new DirectStore(null, 1024);
DirectBytes db = ds.bytes();
RawCopier<A> aRawCopier = RawCopier.copies(A.class);
A a = new A();
a.i = 111;
a.j = -222;
a.k = 333;
a.s = "Hello";
aRawCopier.toBytes(a, db);
assertEquals(12, db.position());
assertEquals(111, db.readInt(0));
assertEquals(-222, db.readInt(4));
assertEquals(333, db.readInt(8));
A a2 = new A();
a2.i = 1;
a2.j = 2;
a2.k = 3;
// printInts(a2, 28);
db.position(0);
aRawCopier.fromBytes(db, a2);
// printInts(a2, 28);
assertEquals(111, a2.i);
assertEquals(-222, a2.j);
assertEquals(333, a2.k);
assertEquals(null, a2.s);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void manyToggles(DirectStore store1, int lockCount, int from, int to) {
long id = Thread.currentThread().getId();
assertEquals(0, id >>> 24);
System.out.println("Thread " + id);
DirectBytes slice1 = store1.createSlice();
for (int i = 0; i < lockCount; i++) {
assertTrue(
slice1.tryLockNanosInt(0L, 5 * 1000 * 1000));
int toggle1 = slice1.readInt(4);
if (toggle1 == from) {
slice1.writeInt(4L, to);
} else {
i--;
}
slice1.unlockInt(0L);
System.nanoTime(); // do something small between locks
}
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
private void manyToggles(DirectStore store1, int lockCount, int from, int to) {
long id = Thread.currentThread().getId();
assertEquals(0, id >>> 24);
System.out.println("Thread " + id);
DirectBytes slice1 = store1.createSlice();
int records = 8;
for (int i = 0; i < lockCount; i += records) {
for (long j = 0; j < records * 64; j += 64) {
slice1.positionAndSize(j, 64);
assertTrue(
slice1.tryLockNanosInt(0L, 5 * 1000 * 1000));
int toggle1 = slice1.readInt(4);
if (toggle1 == from) {
slice1.writeInt(4L, to);
} else {
i--;
}
slice1.unlockInt(0L);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testReadWrite() {
DirectStore ds = new DirectStore(null, 1024);
DirectBytes db = ds.createSlice();
RawCopier<A> aRawCopier = RawCopier.copies(A.class);
A a = new A();
a.i = 111;
a.j = -222;
a.k = 333;
a.s = "Hello";
aRawCopier.toBytes(a, db);
assertEquals(12, db.position());
assertEquals(111, db.readInt(0));
assertEquals(-222, db.readInt(4));
assertEquals(333, db.readInt(8));
A a2 = new A();
a2.i = 1;
a2.j = 2;
a2.k = 3;
// printInts(a2, 28);
db.position(0);
aRawCopier.fromBytes(db, a2);
// printInts(a2, 28);
assertEquals(111, a2.i);
assertEquals(-222, a2.j);
assertEquals(333, a2.k);
assertEquals(null, a2.s);
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testReadWrite() {
DirectStore ds = new DirectStore(null, 1024);
DirectBytes db = ds.bytes();
RawCopier<A> aRawCopier = RawCopier.copies(A.class);
A a = new A();
a.i = 111;
a.j = -222;
a.k = 333;
a.s = "Hello";
aRawCopier.toBytes(a, db);
assertEquals(12, db.position());
assertEquals(111, db.readInt(0));
assertEquals(-222, db.readInt(4));
assertEquals(333, db.readInt(8));
A a2 = new A();
a2.i = 1;
a2.j = 2;
a2.k = 3;
// printInts(a2, 28);
db.position(0);
aRawCopier.fromBytes(db, a2);
// printInts(a2, 28);
assertEquals(111, a2.i);
assertEquals(-222, a2.j);
assertEquals(333, a2.k);
assertEquals(null, a2.s);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@Ignore
public void benchmarkByteLargeArray() {
long length = 1L << 32;
long start = System.nanoTime();
DirectBytes array = DirectStore.allocateLazy(length).createSlice();
System.out.println("Constructor time: " + (System.nanoTime() - start) / 1e9 + " sec");
int iters = 2;
byte one = 1;
start = System.nanoTime();
for (int it = 0; it < iters; it++) {
for (long i = 0; i < length; i++) {
array.writeByte(i, one);
array.writeByte(i, (byte) (array.readByte(i) + one));
}
}
System.out.println("Computation time: " + (System.nanoTime() - start) / 1e9 / iters + " sec");
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
@Ignore
public void benchmarkByteLargeArray() {
long length = 1L << 32;
long start = System.nanoTime();
DirectBytes array = DirectStore.allocateLazy(length).bytes();
System.out.println("Constructor time: " + (System.nanoTime() - start) / 1e9 + " sec");
int iters = 2;
byte one = 1;
start = System.nanoTime();
for (int it = 0; it < iters; it++) {
for (long i = 0; i < length; i++) {
array.writeByte(i, one);
array.writeByte(i, (byte) (array.readByte(i) + one));
}
}
System.out.println("Computation time: " + (System.nanoTime() - start) / 1e9 / iters + " sec");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSimpleLock() {
DirectBytes bytes = new DirectStore(64).createSlice();
bytes.writeLong(0, -1L);
assertFalse(bytes.tryLockLong(0));
bytes.writeLong(0, 0L);
assertTrue(bytes.tryLockLong(0));
long val1 = bytes.readLong(0);
assertTrue(bytes.tryLockLong(0));
bytes.unlockLong(0);
assertEquals(val1, bytes.readLong(0));
bytes.unlockLong(0);
assertEquals(0L, bytes.readLong(0));
try {
bytes.unlockLong(0);
fail();
} catch (IllegalMonitorStateException e) {
// expected.
}
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSimpleLock() {
DirectBytes bytes = new DirectStore(64).bytes();
bytes.writeLong(0, -1L);
assertFalse(bytes.tryLockLong(0));
bytes.writeLong(0, 0L);
assertTrue(bytes.tryLockLong(0));
long val1 = bytes.readLong(0);
assertTrue(bytes.tryLockLong(0));
bytes.unlockLong(0);
assertEquals(val1, bytes.readLong(0));
bytes.unlockLong(0);
assertEquals(0L, bytes.readLong(0));
try {
bytes.unlockLong(0);
fail();
} catch (IllegalMonitorStateException e) {
// expected.
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@NotNull
@Override
public String parseUtf8(@NotNull StopCharTester tester) {
StringBuilder utfReader = acquireStringBuilder();
parseUtf8(utfReader, tester);
return stringInterner().intern(utfReader);
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@NotNull
@Override
public String parseUtf8(@NotNull StopCharTester tester) {
StringBuilder utfReader = acquireStringBuilder();
parseUtf8(utfReader, tester);
return SI.intern(utfReader);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
StringInterner stringInterner() {
if (stringInterner == null)
stringInterner = new StringInterner(8 * 1024);
return stringInterner;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
AbstractBytes() {
this(new VanillaBytesMarshallerFactory(), new AtomicInteger(1));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAllocate() throws Exception {
long size = 1L << 24; // 31; don't overload cloud-bees
DirectStore store = DirectStore.allocate(size);
assertEquals(size, store.size());
DirectBytes slice = store.createSlice();
slice.positionAndSize(0, size);
slice.writeLong(0, size);
slice.writeLong(size - 8, size);
store.free();
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAllocate() throws Exception {
long size = 1L << 24; // 31; don't overload cloud-bees
DirectStore store = DirectStore.allocate(size);
assertEquals(size, store.size());
DirectBytes slice = store.bytes();
slice.positionAndSize(0, size);
slice.writeLong(0, size);
slice.writeLong(size - 8, size);
store.free();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreate() throws Exception {
File f1 = newTempraryFile("vmf-create-1");
File f2 = newTempraryFile("vmf-create-2");
VanillaMappedFile vmf1 = new VanillaMappedFile(f1,VanillaMappedMode.RW);
VanillaMappedFile vmf2 = new VanillaMappedFile(f2,VanillaMappedMode.RW,128);
assertTrue(f1.exists());
assertTrue(f2.exists());
assertEquals( 0, vmf1.size());
assertEquals(128, vmf2.size());
vmf1.close();
vmf2.close();
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCreate() throws Exception {
File f1 = newTempraryFile("vmf-create-1");
File f2 = newTempraryFile("vmf-create-2");
VanillaMappedFile vmf1 = VanillaMappedFile.readWrite(f1);
VanillaMappedFile vmf2 = VanillaMappedFile.readWrite(f2,128);
assertTrue(f1.exists());
assertTrue(f2.exists());
assertEquals(0, vmf1.size());
assertEquals(128, vmf2.size());
vmf1.close();
vmf2.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUnmap() throws IOException, InterruptedException {
String TMP = System.getProperty("java.io.tmpdir");
String basePath = TMP + "/testUnmap";
File file = new File(basePath);
File dir = file.getParentFile();
long free0 = dir.getFreeSpace();
MappedFile mfile = new MappedFile(basePath, 1024 * 1024);
MappedMemory map0 = mfile.acquire(0);
fill(map0.buffer());
MappedMemory map1 = mfile.acquire(1);
fill(map1.buffer().force());
long free1 = dir.getFreeSpace();
map1.release();
map0.release();
mfile.close();
// printMappings();
long free2 = dir.getFreeSpace();
delete(file);
long free3 = 0;
for (int i = 0; i < 100; i++) {
free3 = dir.getFreeSpace();
System.out.println("Freed " + free0 + " ~ " + free1 + " ~ " + free2 + " ~ " + free3 + ", delete = " + file.delete());
if (free3 > free1)
break;
Thread.sleep(500);
}
assertTrue("free3-free1: " + (free3 - free1), free3 > free1);
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUnmap() throws IOException, InterruptedException {
String TMP = System.getProperty("java.io.tmpdir");
String basePath = TMP + "/testUnmap";
File file = new File(basePath);
File dir = file.getParentFile();
long free0 = dir.getFreeSpace();
MappedFile mfile = new MappedFile(basePath, 1024 * 1024);
MappedMemory map0 = mfile.acquire(0);
fill(map0.buffer());
MappedMemory map1 = mfile.acquire(1);
fill(map1.buffer().force());
long free1 = dir.getFreeSpace();
mfile.release(map1);
mfile.release(map0);
mfile.close();
// printMappings();
long free2 = dir.getFreeSpace();
delete(file);
long free3 = 0;
for (int i = 0; i < 100; i++) {
free3 = dir.getFreeSpace();
System.out.println("Freed " + free0 + " ~ " + free1 + " ~ " + free2 + " ~ " + free3 + ", delete = " + file.delete());
if (free3 > free1)
break;
Thread.sleep(500);
}
assertTrue("free3-free1: " + (free3 - free1), free3 > free1);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void manyToggles(@NotNull DirectStore store1, int lockCount, int from, int to) {
long id = Thread.currentThread().getId();
assertEquals(0, id >>> 24);
System.out.println("Thread " + id);
DirectBytes slice1 = store1.createSlice();
int records = 64;
for (int i = 0; i < lockCount; i += records) {
for (long j = 0; j < records * 64; j += 64) {
slice1.positionAndSize(j, 64);
boolean condition = false;
for (int k = 0; k < 20; k++) {
condition = slice1.tryLockInt(0L) || slice1.tryLockNanosInt(0L, 5 * 1000 * 1000);
if (condition)
break;
if (k > 0)
System.out.println("k: " + (5 + k * 5));
}
if (!condition)
assertTrue("i= " + i, condition);
int toggle1 = slice1.readInt(4);
if (toggle1 == from) {
slice1.writeInt(4L, to);
} else {
// noinspection AssignmentToForLoopParameter,AssignmentToForLoopParameter
i--;
}
slice1.unlockInt(0L);
System.currentTimeMillis(); // small delay
}
}
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
private static void manyToggles(@NotNull DirectStore store1, int lockCount, int from, int to) {
long id = Thread.currentThread().getId();
assertEquals(0, id >>> 24);
System.out.println("Thread " + id);
DirectBytes slice1 = store1.bytes();
int records = 64;
for (int i = 0; i < lockCount; i += records) {
for (long j = 0; j < records * 64; j += 64) {
slice1.positionAndSize(j, 64);
boolean condition = false;
for (int k = 0; k < 20; k++) {
condition = slice1.tryLockInt(0L) || slice1.tryLockNanosInt(0L, 5 * 1000 * 1000);
if (condition)
break;
if (k > 0)
System.out.println("k: " + (5 + k * 5));
}
if (!condition)
assertTrue("i= " + i, condition);
int toggle1 = slice1.readInt(4);
if (toggle1 == from) {
slice1.writeInt(4L, to);
} else {
// noinspection AssignmentToForLoopParameter,AssignmentToForLoopParameter
i--;
}
slice1.unlockInt(0L);
System.currentTimeMillis(); // small delay
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAllocate() throws Exception {
long size = 1L << 24; // 31; don't overload cloud-bees
DirectStore store = DirectStore.allocate(size);
assertEquals(size, store.size());
DirectBytes slice = store.createSlice();
slice.positionAndSize(0, size);
slice.writeLong(0, size);
slice.writeLong(size - 8, size);
store.free();
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAllocate() throws Exception {
long size = 1L << 24; // 31; don't overload cloud-bees
DirectStore store = DirectStore.allocate(size);
assertEquals(size, store.size());
DirectBytes slice = store.bytes();
slice.positionAndSize(0, size);
slice.writeLong(0, size);
slice.writeLong(size - 8, size);
store.free();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAcquireOverlap() throws Exception {
VanillaMappedFile vmf = new VanillaMappedFile(
newTempraryFile("vmf-acquire-overlap"),
VanillaMappedMode.RW);
VanillaMappedBlocks blocks = vmf.blocks(128);
VanillaMappedBuffer b1 = blocks.acquire(0);
b1.writeLong(1);
b1.release();
assertEquals(0,b1.refCount());
assertTrue(b1.unmapped());
VanillaMappedBuffer b2 = blocks.acquire(1);
b2.writeLong(2);
b2.release();
assertEquals(0,b2.refCount());
assertTrue(b2.unmapped());
VanillaMappedBuffer b3 = blocks.acquire(2);
b3.writeLong(3);
b3.release();
assertEquals(0,b3.refCount());
assertTrue(b3.unmapped());
VanillaMappedBuffer b4 = vmf.sliceAt(0, 128 * 3);
assertEquals( 1, b4.refCount());
assertEquals(384, b4.size());
assertEquals( 1L, b4.readLong(0));
assertEquals( 2L, b4.readLong(128));
assertEquals( 3L, b4.readLong(256));
vmf.close();
}
#location 38
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAcquireOverlap() throws Exception {
File path = newTempraryFile("vmf-acquire-overlap");
VanillaMappedFile vmf = VanillaMappedFile.readWrite(path);
VanillaMappedBlocks blocks = VanillaMappedBlocks.readWrite(path,128);
VanillaMappedBuffer b1 = blocks.acquire(0);
b1.writeLong(1);
b1.release();
assertEquals(0, b1.refCount());
assertTrue(b1.unmapped());
VanillaMappedBuffer b2 = blocks.acquire(1);
b2.writeLong(2);
b2.release();
assertEquals(0, b2.refCount());
assertTrue(b2.unmapped());
VanillaMappedBuffer b3 = blocks.acquire(2);
b3.writeLong(3);
b3.release();
assertEquals(0, b3.refCount());
assertTrue(b3.unmapped());
VanillaMappedBuffer b4 = vmf.sliceAt(0, 128 * 3);
assertEquals(1, b4.refCount());
assertEquals(384, b4.size());
assertEquals(1L, b4.readLong(0));
assertEquals(2L, b4.readLong(128));
assertEquals(3L, b4.readLong(256));
vmf.close();
blocks.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@NotNull
@Override
public String readUTF() {
try {
int len = readUnsignedShort();
StringBuilder utfReader = acquireStringBuilder();
readUTF0(utfReader, len);
return utfReader.length() == 0 ? "" : stringInterner().intern(utfReader);
} catch (IOException unexpected) {
throw new AssertionError(unexpected);
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@NotNull
@Override
public String readUTF() {
try {
int len = readUnsignedShort();
StringBuilder utfReader = acquireStringBuilder();
readUTF0(utfReader, len);
return utfReader.length() == 0 ? "" : SI.intern(utfReader);
} catch (IOException unexpected) {
throw new AssertionError(unexpected);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public VanillaMappedBuffer sliceOf(long size) throws IOException {
return sliceAtWithId(this.address, size, -1);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public VanillaMappedBuffer sliceOf(long size) throws IOException {
return sliceAt(this.address, size, -1);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public VanillaMappedBytes put(T key, File path, long size, long index) {
DataHolder data = this.cache.get(key);
if(data != null) {
data.close();
} else {
data = new DataHolder();
}
try {
final Iterator<Map.Entry<T,DataHolder>> it = this.cache.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<T,DataHolder> entry = it.next();
if(entry.getValue().bytes().unmapped()) {
entry.getValue().close();
it.remove();
}
}
data.recycle(
VanillaMappedFile.readWrite(path, size),
0,
size,
index);
this.cache.put(key,data);
} catch(IOException e) {
LOGGER.warn("",e);
}
return data.bytes();
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
public VanillaMappedBytes put(T key, File path, long size, long index) {
DataHolder data = this.cache.get(key);
if(data != null) {
data.close();
} else {
data = new DataHolder();
}
try {
cleanup();
data.recycle(
VanillaMappedFile.readWrite(path, size),
0,
size,
index);
this.cache.put(key,data);
} catch(IOException e) {
LOGGER.warn("",e);
}
return data.bytes();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void manyLongToggles(@NotNull DirectStore store1, int lockCount, int from, int to) {
long id = Thread.currentThread().getId();
assertEquals(0, id >>> 32);
System.out.println("Thread " + id);
DirectBytes slice1 = store1.createSlice();
int records = 64;
for (int i = 0; i < lockCount; i += records) {
for (long j = 0; j < records * 64; j += 64) {
slice1.positionAndSize(j, 64);
boolean condition = false;
for (int k = 0; k < 20; k++) {
condition = slice1.tryLockLong(0L) || slice1.tryLockNanosLong(0L, 5 * 1000 * 1000);
if (condition)
break;
if (k > 0)
System.out.println("k: " + (5 + k * 5));
}
if (!condition)
assertTrue("i= " + i, condition);
long toggle1 = slice1.readLong(8);
if (toggle1 == from) {
slice1.writeLong(8L, to);
} else {
// noinspection AssignmentToForLoopParameter,AssignmentToForLoopParameter
i--;
}
slice1.unlockLong(0L);
System.currentTimeMillis(); // small delay
}
}
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
private static void manyLongToggles(@NotNull DirectStore store1, int lockCount, int from, int to) {
long id = Thread.currentThread().getId();
assertEquals(0, id >>> 32);
System.out.println("Thread " + id);
DirectBytes slice1 = store1.bytes();
int records = 64;
for (int i = 0; i < lockCount; i += records) {
for (long j = 0; j < records * 64; j += 64) {
slice1.positionAndSize(j, 64);
boolean condition = false;
for (int k = 0; k < 20; k++) {
condition = slice1.tryLockLong(0L) || slice1.tryLockNanosLong(0L, 5 * 1000 * 1000);
if (condition)
break;
if (k > 0)
System.out.println("k: " + (5 + k * 5));
}
if (!condition)
assertTrue("i= " + i, condition);
long toggle1 = slice1.readLong(8);
if (toggle1 == from) {
slice1.writeLong(8L, to);
} else {
// noinspection AssignmentToForLoopParameter,AssignmentToForLoopParameter
i--;
}
slice1.unlockLong(0L);
System.currentTimeMillis(); // small delay
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAcquireBlocks2() throws Exception {
VanillaMappedFile vmf = new VanillaMappedFile(
newTempraryFile("vmf-acquire-blocks-2"),
VanillaMappedMode.RW);
final long nblocks = 50 * 100 * 1000;
final VanillaMappedBlocks blocks = vmf.blocks(64);
for(long i=0; i<nblocks; i++) {
VanillaMappedBuffer b = blocks.acquire(i);
assertEquals(1, b.refCount());
b.release();
assertEquals(0,b.refCount());
assertTrue(b.unmapped());
}
vmf.close();
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAcquireBlocks2() throws Exception {
VanillaMappedBlocks blocks = VanillaMappedBlocks.readWrite(
newTempraryFile("vmf-acquire-blocks-2"),
64);
final long nblocks = 50 * 100 * 1000;
for (long i = 0; i < nblocks; i++) {
VanillaMappedBuffer b = blocks.acquire(i);
assertEquals(1, b.refCount());
b.release();
assertEquals(0, b.refCount());
assertTrue(b.unmapped());
}
blocks.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testToString() {
NativeBytes bytes = new DirectStore(32).createSlice();
assertEquals("[pos: 0, lim: 32, cap: 32 ] ٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(1);
assertEquals("[pos: 1, lim: 32, cap: 32 ] ⒈‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(2);
assertEquals("[pos: 2, lim: 32, cap: 32 ] ⒈⒉‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(3);
assertEquals("[pos: 3, lim: 32, cap: 32 ] ⒈⒉⒊‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(4);
assertEquals("[pos: 4, lim: 32, cap: 32 ] ⒈⒉⒊⒋‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(5);
assertEquals("[pos: 5, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(6);
assertEquals("[pos: 6, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(7);
assertEquals("[pos: 7, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍⒎‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(8);
assertEquals("[pos: 8, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍⒎⒏‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
}
#location 20
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testToString() {
NativeBytes bytes = new DirectStore(32).bytes();
assertEquals("[pos: 0, lim: 32, cap: 32 ] ٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(1);
assertEquals("[pos: 1, lim: 32, cap: 32 ] ⒈‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(2);
assertEquals("[pos: 2, lim: 32, cap: 32 ] ⒈⒉‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(3);
assertEquals("[pos: 3, lim: 32, cap: 32 ] ⒈⒉⒊‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(4);
assertEquals("[pos: 4, lim: 32, cap: 32 ] ⒈⒉⒊⒋‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(5);
assertEquals("[pos: 5, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(6);
assertEquals("[pos: 6, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(7);
assertEquals("[pos: 7, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍⒎‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
bytes.writeByte(8);
assertEquals("[pos: 8, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍⒎⒏‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@NotNull
@Override
public String readLine() {
StringBuilder input = acquireStringBuilder();
EOL:
while (position() < capacity()) {
int c = readUnsignedByteOrThrow();
switch (c) {
case END_OF_BUFFER:
case '\n':
break EOL;
case '\r':
long cur = position();
if (cur < capacity() && readByte(cur) == '\n')
position(cur + 1);
break EOL;
default:
input.append((char) c);
break;
}
}
return stringInterner().intern(input);
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@NotNull
@Override
public String readLine() {
StringBuilder input = acquireStringBuilder();
EOL:
while (position() < capacity()) {
int c = readUnsignedByteOrThrow();
switch (c) {
case END_OF_BUFFER:
case '\n':
break EOL;
case '\r':
long cur = position();
if (cur < capacity() && readByte(cur) == '\n')
position(cur + 1);
break EOL;
default:
input.append((char) c);
break;
}
}
return SI.intern(input);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLocking() throws Exception {
// a page
long start = System.nanoTime();
final DirectStore store1 = DirectStore.allocate(1 << 12);
final int lockCount = 20 * 1000000;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
long id = Thread.currentThread().getId();
System.out.println("Thread " + id);
assertEquals(0, id >>> 24);
try {
DirectBytes slice1 = store1.createSlice();
for (int i = 0; i < lockCount; i++) {
slice1.busyLockInt(0);
int toggle1 = slice1.readInt(4);
if (toggle1 == 1) {
slice1.writeInt(4, 0);
} else {
i--;
}
slice1.unlockInt(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
long id = Thread.currentThread().getId();
assertEquals(0, id >>> 24);
System.out.println("Thread " + id);
DirectBytes slice1 = store1.createSlice();
for (int i = 0; i < lockCount; i++) {
slice1.busyLockInt(0);
int toggle1 = slice1.readInt(4);
if (toggle1 == 0) {
slice1.writeInt(4, 1);
} else {
i--;
}
slice1.unlockInt(0);
}
store1.free();
long time = System.nanoTime() - start;
System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time));
}
#location 50
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testLocking() {
// a page
long start = System.nanoTime();
final DirectStore store1 = DirectStore.allocate(1 << 12);
final int lockCount = 20 * 1000 * 1000;
new Thread(new Runnable() {
@Override
public void run() {
manyToggles(store1, lockCount, 1, 0);
}
}).start();
manyToggles(store1, lockCount, 0, 1);
store1.free();
long time = System.nanoTime() - start;
System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void readXml(String fname) throws CoreException {
printX("Loading "+fname+"\n");
resetErrors();
resetWarnings();
// close existing substream
if (substream != null) {
substream.close();
}
supXml = new SupXml(fname);
substream = supXml;
inMode = InputMode.XML;
// decode first frame
substream.decode(0);
subVobTrg = new SubPictureDVD();
// automatically set luminance thresholds for VobSub conversion
int maxLum = substream.getPalette().getY()[substream.getPrimaryColorIndex()] & 0xff;
int[] luminanceThreshold = new int[2];
configuration.setLuminanceThreshold(luminanceThreshold);
if (maxLum > 30) {
luminanceThreshold[0] = maxLum*2/3;
luminanceThreshold[1] = maxLum/3;
} else {
luminanceThreshold[0] = 210;
luminanceThreshold[1] = 160;
}
// find language idx
for (int i=0; i < LANGUAGES.length; i++) {
if (LANGUAGES[i][2].equalsIgnoreCase(supXml.getLanguage())) {
configuration.setLanguageIdx(i);
break;
}
}
// set frame rate
configuration.setFpsSrc(supXml.getFps());
configuration.setFpsSrcCertain(true);
if (Core.keepFps) {
configuration.setFpsTrg(configuration.getFPSSrc());
}
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void readXml(String fname) throws CoreException {
printX("Loading "+fname+"\n");
resetErrors();
resetWarnings();
// close existing subtitleStream
if (subtitleStream != null) {
subtitleStream.close();
}
supXml = new SupXml(fname);
subtitleStream = supXml;
inMode = InputMode.XML;
// decode first frame
subtitleStream.decode(0);
subVobTrg = new SubPictureDVD();
// automatically set luminance thresholds for VobSub conversion
int maxLum = subtitleStream.getPalette().getY()[subtitleStream.getPrimaryColorIndex()] & 0xff;
int[] luminanceThreshold = new int[2];
configuration.setLuminanceThreshold(luminanceThreshold);
if (maxLum > 30) {
luminanceThreshold[0] = maxLum*2/3;
luminanceThreshold[1] = maxLum/3;
} else {
luminanceThreshold[0] = 210;
luminanceThreshold[1] = 160;
}
// find language idx
for (int i=0; i < LANGUAGES.length; i++) {
if (LANGUAGES[i][2].equalsIgnoreCase(supXml.getLanguage())) {
configuration.setLanguageIdx(i);
break;
}
}
// set frame rate
configuration.setFpsSrc(supXml.getFps());
configuration.setFpsSrcCertain(true);
if (Core.keepFps) {
configuration.setFpsTrg(configuration.getFPSSrc());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void setCurSrcDVDPalette(Palette pal) {
currentSourceDVDPalette = pal;
SubstreamDVD substreamDVD = null;
if (inMode == InputMode.VOBSUB) {
substreamDVD = subDVD;
} else if (inMode == InputMode.SUPIFO) {
substreamDVD = supDVD;
}
substreamDVD.setSrcPalette(currentSourceDVDPalette);
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void setCurSrcDVDPalette(Palette pal) {
currentSourceDVDPalette = pal;
DvdSubtitleStream substreamDvd = null;
if (inMode == InputMode.VOBSUB) {
substreamDvd = subDVD;
} else if (inMode == InputMode.SUPIFO) {
substreamDvd = supDVD;
}
substreamDvd.setSrcPalette(currentSourceDVDPalette);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
if (args.length < 4 || args.length > 5) {
System.err.println("Usage: QueryDriver <topicsFile> <qrelsFile> <submissionFile> <indexDir> [querySpec]");
System.err.println("topicsFile: input file containing queries");
System.err.println("qrelsFile: input file containing relevance judgements");
System.err.println("submissionFile: output submission file for trec_eval");
System.err.println("indexDir: index directory");
System.err.println("querySpec: string composed of fields to use in query consisting of T=title,D=description,N=narrative:");
System.err.println("\texample: TD (query on Title + Description). The default is T (title only)");
System.exit(1);
}
Path topicsFile = Paths.get(args[0]);
Path qrelsFile = Paths.get(args[1]);
Path submissionFile = Paths.get(args[2]);
SubmissionReport submitLog = new SubmissionReport(new PrintWriter(Files.newBufferedWriter(submissionFile, StandardCharsets.UTF_8)), "lucene");
MMapDirectory dir = new MMapDirectory(Paths.get(args[3]));
dir.setPreload(true);
String fieldSpec = args.length == 5 ? args[4] : "T"; // default to Title-only if not specified.
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
//searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
int maxResults = 1000;
String docNameField = "docid";
PrintWriter logger = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()), true);
// use trec utilities to read trec topics into quality queries
TrecTopicsReader qReader = new TrecTopicsReader();
QualityQuery qqs[] = qReader.readQueries(Files.newBufferedReader(topicsFile, StandardCharsets.UTF_8));
// prepare judge, with trec utilities that read from a QRels file
//Judge judge = new TrecJudge(Files.newBufferedReader(qrelsFile, StandardCharsets.UTF_8));
// validate topics & judgments match each other
//judge.validateData(qqs, logger);
Set<String> fieldSet = new HashSet<>();
if (fieldSpec.indexOf('T') >= 0) fieldSet.add("title");
if (fieldSpec.indexOf('D') >= 0) fieldSet.add("description");
if (fieldSpec.indexOf('N') >= 0) fieldSet.add("narrative");
// set the parsing of quality queries into Lucene queries.
QualityQueryParser qqParser = new EnglishQQParser(fieldSet.toArray(new String[0]), "body");
PrintStream out = new PrintStream(System.out, true, "UTF-8");
for (QualityQuery qq : qqs) {
//System.out.println(qq.getValue("title"));
Query query = AnalyzerUtils.buildBagOfWordsQuery("body", new EnglishAnalyzer(), qq.getValue("title"));
//System.out.println(query);
TopDocs rs = searcher.search(query, maxResults);
RerankerContext context = new RerankerContext(searcher, query, qq.getValue("title"), null);
RerankerCascade cascade = new RerankerCascade(context);
cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body"));
ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher));
for (int i=0; i<docs.documents.length; i++) {
String qid = qq.getQueryID();
out.println(String.format("%s Q0 %s %d %f %s", qid,
docs.documents[i].getField("docid").stringValue(), (i+1), docs.scores[i], "Lucene"));
}
}
// // run the benchmark
// QualityBenchmark qrun = new QualityBenchmark(qqs, qqParser, searcher, docNameField);
// qrun.setMaxResults(maxResults);
// QualityStats stats[] = qrun.execute(judge, submitLog, logger);
//
// // print an avarage sum of the results
// QualityStats avg = QualityStats.average(stats);
// avg.log("SUMMARY", 2, logger, " ");
reader.close();
dir.close();
out.close();
}
#location 62
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
long curTime = System.nanoTime();
SearchArgs searchArgs = new SearchArgs();
CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90));
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.err.println("Example: SearchGov2" + parser.printExample(OptionHandlerFilter.REQUIRED));
return;
}
Path topicsFile = Paths.get(searchArgs.topics);
LOG.info("Reading index at " + searchArgs.index);
Directory dir;
if (searchArgs.inmem) {
LOG.info("Using MMapDirectory with preload");
dir = new MMapDirectory(Paths.get(searchArgs.index));
((MMapDirectory) dir).setPreload(true);
} else {
LOG.info("Using default FSDirectory");
dir = FSDirectory.open(Paths.get(searchArgs.index));
}
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
if (searchArgs.ql) {
LOG.info("Using QL scoring model");
searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
} else if (searchArgs.rm3) {
LOG.info("Using RM3 query expansion");
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
} else if (searchArgs.bm25) {
LOG.info("Using BM25 scoring model");
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
} else {
LOG.error("Error: Must specify scoring model!");
System.exit(-1);
}
int maxResults = 1000;
TrecTopicsReader qReader = new TrecTopicsReader();
QualityQuery qqs[] = qReader.readQueries(Files.newBufferedReader(topicsFile, StandardCharsets.UTF_8));
PrintStream out = new PrintStream(new FileOutputStream(new File(searchArgs.output)));
LOG.info("Writing output to " + searchArgs.output);
LOG.info("Initialized complete! (elapsed time = " + (System.nanoTime()-curTime)/1000000 + "ms)");
long totalTime = 0;
for (QualityQuery qq : qqs) {
long curQueryTime = System.nanoTime();
Query query = AnalyzerUtils.buildBagOfWordsQuery("body", new EnglishAnalyzer(), qq.getValue("title"));
TopDocs rs = searcher.search(query, maxResults);
RerankerContext context = new RerankerContext(searcher, query, qq.getValue("title"), null);
RerankerCascade cascade = new RerankerCascade(context);
if (searchArgs.rm3) {
cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body"));
} else {
cascade.add(new IdentityReranker());
}
ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher));
for (int i=0; i<docs.documents.length; i++) {
String qid = qq.getQueryID();
out.println(String.format("%s Q0 %s %d %f %s", qid,
docs.documents[i].getField("docid").stringValue(), (i+1), docs.scores[i], "Lucene"));
}
long qtime = (System.nanoTime()-curQueryTime)/1000000;
LOG.info("Query " + qq.getQueryID() + " (elapsed time = " + qtime + "ms)");
totalTime += qtime;
}
LOG.info("All queries completed!");
LOG.info("Total elapsed time = " + totalTime + "ms");
LOG.info("Average query latency = " + (totalTime/qqs.length) + "ms");
reader.close();
dir.close();
out.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws IOException, ParseException {
if (args.length != 1) {
System.err.println("Usage: SearchTimeUtil <indexDir>");
System.err.println("indexDir: index directory");
System.exit(1);
}
String[] topics = {"topics.web.1-50.txt", "topics.web.51-100.txt", "topics.web.101-150.txt", "topics.web.151-200.txt", "topics.web.201-250.txt", "topics.web.251-300.txt"};
SearchClueWeb09b searcher = new SearchClueWeb09b(args[0]);
for (String topicFile : topics) {
Path topicsFile = Paths.get("src/resources/topics-and-qrels/", topicFile);
SortedMap<Integer, String> queries = SearchClueWeb09b.readWebTrackQueries(topicsFile);
for (int i = 1; i <= 3; i++) {
final long start = System.nanoTime();
String submissionFile = File.createTempFile(topicFile + "_" + i, ".tmp").getAbsolutePath();
searcher.search(queries, submissionFile, new BM25Similarity(0.9f, 0.4f), 1000);
final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
System.out.println(topicFile + "_" + i + " search completed in " + DurationFormatUtils.formatDuration(durationMillis, "mm:ss:SSS"));
}
}
searcher.close();
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws IOException, ParseException {
if (args.length != 1) {
System.err.println("Usage: SearchTimeUtil <indexDir>");
System.err.println("indexDir: index directory");
System.exit(1);
}
String[] topics = {"topics.web.1-50.txt", "topics.web.51-100.txt", "topics.web.101-150.txt", "topics.web.151-200.txt", "topics.web.201-250.txt", "topics.web.251-300.txt"};
SearchWebCollection searcher = new SearchWebCollection(args[0]);
for (String topicFile : topics) {
Path topicsFile = Paths.get("src/resources/topics-and-qrels/", topicFile);
SortedMap<Integer, String> queries = SearchWebCollection.readWebTrackQueries(topicsFile);
for (int i = 1; i <= 3; i++) {
final long start = System.nanoTime();
String submissionFile = File.createTempFile(topicFile + "_" + i, ".tmp").getAbsolutePath();
searcher.search(queries, submissionFile, new BM25Similarity(0.9f, 0.4f), 1000);
final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
System.out.println(topicFile + "_" + i + " search completed in " + DurationFormatUtils.formatDuration(durationMillis, "mm:ss:SSS"));
}
}
searcher.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
if (args.length < 4 || args.length > 5) {
System.err.println("Usage: QueryDriver <topicsFile> <qrelsFile> <submissionFile> <indexDir> [querySpec]");
System.err.println("topicsFile: input file containing queries");
System.err.println("qrelsFile: input file containing relevance judgements");
System.err.println("submissionFile: output submission file for trec_eval");
System.err.println("indexDir: index directory");
System.err.println("querySpec: string composed of fields to use in query consisting of T=title,D=description,N=narrative:");
System.err.println("\texample: TD (query on Title + Description). The default is T (title only)");
System.exit(1);
}
Path topicsFile = Paths.get(args[0]);
Path qrelsFile = Paths.get(args[1]);
Path submissionFile = Paths.get(args[2]);
SubmissionReport submitLog = new SubmissionReport(new PrintWriter(Files.newBufferedWriter(submissionFile, StandardCharsets.UTF_8)), "lucene");
MMapDirectory dir = new MMapDirectory(Paths.get(args[3]));
dir.setPreload(true);
String fieldSpec = args.length == 5 ? args[4] : "T"; // default to Title-only if not specified.
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
//searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
int maxResults = 1000;
String docNameField = "docid";
PrintWriter logger = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()), true);
// use trec utilities to read trec topics into quality queries
TrecTopicsReader qReader = new TrecTopicsReader();
QualityQuery qqs[] = qReader.readQueries(Files.newBufferedReader(topicsFile, StandardCharsets.UTF_8));
// prepare judge, with trec utilities that read from a QRels file
//Judge judge = new TrecJudge(Files.newBufferedReader(qrelsFile, StandardCharsets.UTF_8));
// validate topics & judgments match each other
//judge.validateData(qqs, logger);
Set<String> fieldSet = new HashSet<>();
if (fieldSpec.indexOf('T') >= 0) fieldSet.add("title");
if (fieldSpec.indexOf('D') >= 0) fieldSet.add("description");
if (fieldSpec.indexOf('N') >= 0) fieldSet.add("narrative");
// set the parsing of quality queries into Lucene queries.
QualityQueryParser qqParser = new EnglishQQParser(fieldSet.toArray(new String[0]), "body");
PrintStream out = new PrintStream(System.out, true, "UTF-8");
for (QualityQuery qq : qqs) {
//System.out.println(qq.getValue("title"));
Query query = AnalyzerUtils.buildBagOfWordsQuery("body", new EnglishAnalyzer(), qq.getValue("title"));
//System.out.println(query);
TopDocs rs = searcher.search(query, maxResults);
RerankerContext context = new RerankerContext(searcher, query, qq.getValue("title"), null);
RerankerCascade cascade = new RerankerCascade(context);
cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body"));
ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher));
for (int i=0; i<docs.documents.length; i++) {
String qid = qq.getQueryID();
out.println(String.format("%s Q0 %s %d %f %s", qid,
docs.documents[i].getField("docid").stringValue(), (i+1), docs.scores[i], "Lucene"));
}
}
// // run the benchmark
// QualityBenchmark qrun = new QualityBenchmark(qqs, qqParser, searcher, docNameField);
// qrun.setMaxResults(maxResults);
// QualityStats stats[] = qrun.execute(judge, submitLog, logger);
//
// // print an avarage sum of the results
// QualityStats avg = QualityStats.average(stats);
// avg.log("SUMMARY", 2, logger, " ");
reader.close();
dir.close();
out.close();
}
#location 30
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
long curTime = System.nanoTime();
SearchArgs searchArgs = new SearchArgs();
CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90));
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.err.println("Example: SearchGov2" + parser.printExample(OptionHandlerFilter.REQUIRED));
return;
}
Path topicsFile = Paths.get(searchArgs.topics);
LOG.info("Reading index at " + searchArgs.index);
Directory dir;
if (searchArgs.inmem) {
LOG.info("Using MMapDirectory with preload");
dir = new MMapDirectory(Paths.get(searchArgs.index));
((MMapDirectory) dir).setPreload(true);
} else {
LOG.info("Using default FSDirectory");
dir = FSDirectory.open(Paths.get(searchArgs.index));
}
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
if (searchArgs.ql) {
LOG.info("Using QL scoring model");
searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
} else if (searchArgs.rm3) {
LOG.info("Using RM3 query expansion");
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
} else if (searchArgs.bm25) {
LOG.info("Using BM25 scoring model");
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
} else {
LOG.error("Error: Must specify scoring model!");
System.exit(-1);
}
int maxResults = 1000;
TrecTopicsReader qReader = new TrecTopicsReader();
QualityQuery qqs[] = qReader.readQueries(Files.newBufferedReader(topicsFile, StandardCharsets.UTF_8));
PrintStream out = new PrintStream(new FileOutputStream(new File(searchArgs.output)));
LOG.info("Writing output to " + searchArgs.output);
LOG.info("Initialized complete! (elapsed time = " + (System.nanoTime()-curTime)/1000000 + "ms)");
long totalTime = 0;
for (QualityQuery qq : qqs) {
long curQueryTime = System.nanoTime();
Query query = AnalyzerUtils.buildBagOfWordsQuery("body", new EnglishAnalyzer(), qq.getValue("title"));
TopDocs rs = searcher.search(query, maxResults);
RerankerContext context = new RerankerContext(searcher, query, qq.getValue("title"), null);
RerankerCascade cascade = new RerankerCascade(context);
if (searchArgs.rm3) {
cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body"));
} else {
cascade.add(new IdentityReranker());
}
ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher));
for (int i=0; i<docs.documents.length; i++) {
String qid = qq.getQueryID();
out.println(String.format("%s Q0 %s %d %f %s", qid,
docs.documents[i].getField("docid").stringValue(), (i+1), docs.scores[i], "Lucene"));
}
long qtime = (System.nanoTime()-curQueryTime)/1000000;
LOG.info("Query " + qq.getQueryID() + " (elapsed time = " + qtime + "ms)");
totalTime += qtime;
}
LOG.info("All queries completed!");
LOG.info("Total elapsed time = " + totalTime + "ms");
LOG.info("Average query latency = " + (totalTime/qqs.length) + "ms");
reader.close();
dir.close();
out.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws IOException, ParseException {
if (args.length != 3) {
System.err.println("Usage: SearcherCW09B <topicsFile> <submissionFile> <indexDir>");
System.err.println("topicsFile: input file containing queries. One of: topics.web.1-50.txt topics.web.51-100.txt topics.web.101-150.txt topics.web.151-200.txt");
System.err.println("submissionFile: redirect stdout to capture the submission file for trec_eval or gdeval.pl");
System.err.println("indexDir: index directory");
System.exit(1);
}
String topicsFile = args[0];
String submissionFile = args[1];
String indexDir = args[2];
SearchClueWeb09b searcher = new SearchClueWeb09b(indexDir);
searcher.search(topicsFile, submissionFile, QueryParser.Operator.OR);
searcher.close();
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws IOException, ParseException {
long curTime = System.nanoTime();
SearchArgs searchArgs = new SearchArgs();
CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90));
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.err.println("Example: SearchGov2" + parser.printExample(OptionHandlerFilter.REQUIRED));
return;
}
LOG.info("Reading index at " + searchArgs.index);
Directory dir;
if (searchArgs.inmem) {
LOG.info("Using MMapDirectory with preload");
dir = new MMapDirectory(Paths.get(searchArgs.index));
((MMapDirectory) dir).setPreload(true);
} else {
LOG.info("Using default FSDirectory");
dir = FSDirectory.open(Paths.get(searchArgs.index));
}
Similarity similarity = null;
if (searchArgs.ql) {
LOG.info("Using QL scoring model");
similarity = new LMDirichletSimilarity(searchArgs.mu);
} else if (searchArgs.bm25) {
LOG.info("Using BM25 scoring model");
similarity = new BM25Similarity(searchArgs.k1, searchArgs.b);
} else {
LOG.error("Error: Must specify scoring model!");
System.exit(-1);
}
RerankerCascade cascade = new RerankerCascade();
if (searchArgs.rm3) {
cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body", "src/main/resources/io/anserini/rerank/rm3/rm3-stoplist.gov2.txt"));
} else {
cascade.add(new IdentityReranker());
}
Path topicsFile = Paths.get(searchArgs.topics);
if (!Files.exists(topicsFile) || !Files.isRegularFile(topicsFile) || !Files.isReadable(topicsFile)) {
throw new IllegalArgumentException("Topics file : " + topicsFile + " does not exist or is not a (readable) file.");
}
SortedMap<Integer, String> topics = io.anserini.document.Collection.GOV2.equals(searchArgs.collection) ? readTeraByteTackQueries(topicsFile) : readWebTrackQueries(topicsFile);
SearchClueWeb09b searcher = new SearchClueWeb09b(searchArgs.index);
searcher.search(topics, searchArgs.output, similarity);
searcher.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = NoSuchElementException.class)
public void test1() throws Exception {
Freebase freebase = new Freebase(Paths.get("src/test/resources/freebase-rdf-head100.gz"));
FreebaseNode node;
Iterator<FreebaseNode> iter = freebase.iterator();
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/american_football.football_player.footballdb_id>", node.uri());
assertEquals(9, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/astronomy.astronomical_observatory.discoveries>", node.uri());
assertEquals(9, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/automotive.body_style.fuel_tank_capacity>", node.uri());
assertEquals(9, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/automotive.engine.engine_type>", node.uri());
assertEquals(10, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/automotive.trim_level.max_passengers>", node.uri());
assertEquals(9, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/aviation.aircraft.first_flight>", node.uri());
assertEquals(9, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/award.award_winner>", node.uri());
Map<String, List<String>> map = node.getPredicateValues();
assertEquals(1, node.getPredicateValues().size());
assertEquals(45, map.get("<http://rdf.freebase.com/ns/type.type.instance>").size());
assertFalse(iter.hasNext());
iter.next();
}
#location 45
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = NoSuchElementException.class)
public void test1() throws Exception {
Freebase freebase = new Freebase(Paths.get("src/test/resources/freebase-rdf-head100.gz"));
FreebaseNode node;
Iterator<FreebaseNode> iter = freebase.iterator();
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/american_football.football_player.footballdb_id>", node.uri());
assertEquals(9, node.getPredicateValues().size());
assertEquals("fb:american_football.football_player.footballdb_id",
FreebaseNode.cleanUri("fb:american_football.football_player.footballdb_id"));
assertEquals("fb:type.object.name",
FreebaseNode.cleanUri(node.getPredicateValues().keySet().iterator().next()));
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/astronomy.astronomical_observatory.discoveries>", node.uri());
assertEquals(9, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/automotive.body_style.fuel_tank_capacity>", node.uri());
assertEquals(9, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/automotive.engine.engine_type>", node.uri());
assertEquals(10, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/automotive.trim_level.max_passengers>", node.uri());
assertEquals(9, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/aviation.aircraft.first_flight>", node.uri());
assertEquals(9, node.getPredicateValues().size());
assertTrue(iter.hasNext());
node = iter.next();
assertEquals("<http://rdf.freebase.com/ns/award.award_winner>", node.uri());
Map<String, List<String>> map = node.getPredicateValues();
assertEquals(1, node.getPredicateValues().size());
assertEquals(45, map.get("<http://rdf.freebase.com/ns/type.type.instance>").size());
assertFalse(iter.hasNext());
iter.next();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException, InterruptedException {
final long start = System.nanoTime();
LOG.info("Starting indexer...");
int numThreads = args.threads;
final Directory dir = FSDirectory.open(indexPath);
final EnglishAnalyzer englishAnalyzer= args.keepStopwords ?
new EnglishAnalyzer(CharArraySet.EMPTY_SET) : new EnglishAnalyzer();
final TweetAnalyzer tweetAnalyzer = new TweetAnalyzer(args.tweetStemming);
final IndexWriterConfig config = args.collectionClass.equals("TweetCollection") ?
new IndexWriterConfig(tweetAnalyzer) : new IndexWriterConfig(englishAnalyzer);
config.setSimilarity(new BM25Similarity());
config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
config.setRAMBufferSizeMB(args.memorybufferSize);
config.setUseCompoundFile(false);
config.setMergeScheduler(new ConcurrentMergeScheduler());
final IndexWriter writer = new IndexWriter(dir, config);
final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numThreads);
final List segmentPaths = collection.getFileSegmentPaths();
final int segmentCnt = segmentPaths.size();
LOG.info(segmentCnt + " files found in " + collectionPath.toString());
for (int i = 0; i < segmentCnt; i++) {
executor.execute(new IndexerThread(writer, collection, (Path) segmentPaths.get(i)));
}
executor.shutdown();
try {
// Wait for existing tasks to terminate
while (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
LOG.info(String.format("%.2f percent completed",
(double) executor.getCompletedTaskCount() / segmentCnt * 100.0d));
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
executor.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
if (segmentCnt != executor.getCompletedTaskCount()) {
throw new RuntimeException("totalFiles = " + segmentCnt +
" is not equal to completedTaskCount = " + executor.getCompletedTaskCount());
}
int numIndexed = writer.maxDoc();
try {
writer.commit();
if (args.optimize)
writer.forceMerge(1);
} finally {
try {
writer.close();
} catch (IOException e) {
// It is possible that this happens... but nothing much we can do at this point,
// so just log the error and move on.
LOG.error(e);
}
}
LOG.info("Indexed documents: " + counters.indexedDocuments.get());
LOG.info("Empty documents: " + counters.emptyDocuments.get());
LOG.info("Errors: " + counters.errors.get());
final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
LOG.info("Total " + numIndexed + " documents indexed in " +
DurationFormatUtils.formatDuration(durationMillis, "HH:mm:ss"));
}
#location 46
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() throws IOException, InterruptedException {
final long start = System.nanoTime();
LOG.info("Starting indexer...");
int numThreads = args.threads;
final Directory dir = FSDirectory.open(indexPath);
final EnglishAnalyzer englishAnalyzer= args.keepStopwords ?
new EnglishAnalyzer(CharArraySet.EMPTY_SET) : new EnglishAnalyzer();
final TweetAnalyzer tweetAnalyzer = new TweetAnalyzer(args.tweetStemming);
final IndexWriterConfig config = args.collectionClass.equals("TweetCollection") ?
new IndexWriterConfig(tweetAnalyzer) : new IndexWriterConfig(englishAnalyzer);
config.setSimilarity(new BM25Similarity());
config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
config.setRAMBufferSizeMB(args.memorybufferSize);
config.setUseCompoundFile(false);
config.setMergeScheduler(new ConcurrentMergeScheduler());
final IndexWriter writer = new IndexWriter(dir, config);
final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numThreads);
final List segmentPaths = collection.getFileSegmentPaths();
final int segmentCnt = segmentPaths.size();
LOG.info(segmentCnt + " files found in " + collectionPath.toString());
for (int i = 0; i < segmentCnt; i++) {
executor.execute(new IndexerThread(writer, collection, (Path) segmentPaths.get(i)));
}
executor.shutdown();
try {
// Wait for existing tasks to terminate
while (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
LOG.info(String.format("%.2f percent completed",
(double) executor.getCompletedTaskCount() / segmentCnt * 100.0d));
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
executor.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
if (segmentCnt != executor.getCompletedTaskCount()) {
throw new RuntimeException("totalFiles = " + segmentCnt +
" is not equal to completedTaskCount = " + executor.getCompletedTaskCount());
}
int numIndexed = writer.maxDoc();
try {
writer.commit();
if (args.optimize)
writer.forceMerge(1);
} finally {
try {
writer.close();
} catch (IOException e) {
// It is possible that this happens... but nothing much we can do at this point,
// so just log the error and move on.
LOG.error(e);
}
}
if (numIndexed != counters.indexed.get()) {
LOG.warn("Unexpected difference between number of indexed documents and index maxDoc.");
}
LOG.info("# Final Counter Values");
LOG.info(String.format("indexed: %,12d", counters.indexed.get()));
LOG.info(String.format("empty: %,12d", counters.empty.get()));
LOG.info(String.format("unindexed: %,12d", counters.unindexed.get()));
LOG.info(String.format("unindexable: %,12d", counters.unindexable.get()));
LOG.info(String.format("skipped: %,12d", counters.errors.get()));
LOG.info(String.format("errors: %,12d", counters.errors.get()));
final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
LOG.info(String.format("Total %,d documents indexed in %s", numIndexed,
DurationFormatUtils.formatDuration(durationMillis, "HH:mm:ss")));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
Args searchArgs = new Args();
// Parse args
CmdLineParser parser = new CmdLineParser(searchArgs,
ParserProperties.defaults().withUsageWidth(90));
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.err.println("Example command: "+ LookupNode.class.getSimpleName() +
parser.printExample(OptionHandlerFilter.REQUIRED));
return;
}
new LookupNode(searchArgs.index).search(searchArgs.subject, searchArgs.predicate);
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
Args searchArgs = new Args();
CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90));
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.err.println("Example: "+ LookupNode.class.getSimpleName() +
parser.printExample(OptionHandlerFilter.REQUIRED));
return;
}
LookupNode lookup = new LookupNode(searchArgs.index);
lookup.search(searchArgs.subject);
lookup.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
Args searchArgs = new Args();
// Parse args
CmdLineParser parser = new CmdLineParser(searchArgs,
ParserProperties.defaults().withUsageWidth(90));
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.err.println("Example command: "+ LookupTopic.class.getSimpleName() +
parser.printExample(OptionHandlerFilter.REQUIRED));
return;
}
new LookupTopic(searchArgs.index).search(searchArgs.query);
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
Args searchArgs = new Args();
CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90));
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.err.println("Example: "+ LookupNode.class.getSimpleName() +
parser.printExample(OptionHandlerFilter.REQUIRED));
return;
}
LOG.info(String.format("Index: %s", searchArgs.index));
LOG.info(String.format("Query: %s", searchArgs.query));
LOG.info(String.format("Hits: %s", searchArgs.numHits));
LookupTopic lookup = new LookupTopic(searchArgs.index);
lookup.search(searchArgs.query, searchArgs.numHits);
lookup.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
if (args.length < 4 || args.length > 5) {
System.err.println("Usage: QueryDriver <topicsFile> <qrelsFile> <submissionFile> <indexDir> [querySpec]");
System.err.println("topicsFile: input file containing queries");
System.err.println("qrelsFile: input file containing relevance judgements");
System.err.println("submissionFile: output submission file for trec_eval");
System.err.println("indexDir: index directory");
System.err.println("querySpec: string composed of fields to use in query consisting of T=title,D=description,N=narrative:");
System.err.println("\texample: TD (query on Title + Description). The default is T (title only)");
System.exit(1);
}
Path topicsFile = Paths.get(args[0]);
Path qrelsFile = Paths.get(args[1]);
Path submissionFile = Paths.get(args[2]);
SubmissionReport submitLog = new SubmissionReport(new PrintWriter(Files.newBufferedWriter(submissionFile, StandardCharsets.UTF_8)), "lucene");
MMapDirectory dir = new MMapDirectory(Paths.get(args[3]));
dir.setPreload(true);
String fieldSpec = args.length == 5 ? args[4] : "T"; // default to Title-only if not specified.
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
//searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
int maxResults = 1000;
String docNameField = "docid";
PrintWriter logger = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()), true);
// use trec utilities to read trec topics into quality queries
TrecTopicsReader qReader = new TrecTopicsReader();
QualityQuery qqs[] = qReader.readQueries(Files.newBufferedReader(topicsFile, StandardCharsets.UTF_8));
// prepare judge, with trec utilities that read from a QRels file
//Judge judge = new TrecJudge(Files.newBufferedReader(qrelsFile, StandardCharsets.UTF_8));
// validate topics & judgments match each other
//judge.validateData(qqs, logger);
Set<String> fieldSet = new HashSet<>();
if (fieldSpec.indexOf('T') >= 0) fieldSet.add("title");
if (fieldSpec.indexOf('D') >= 0) fieldSet.add("description");
if (fieldSpec.indexOf('N') >= 0) fieldSet.add("narrative");
// set the parsing of quality queries into Lucene queries.
QualityQueryParser qqParser = new EnglishQQParser(fieldSet.toArray(new String[0]), "body");
PrintStream out = new PrintStream(System.out, true, "UTF-8");
for (QualityQuery qq : qqs) {
//System.out.println(qq.getValue("title"));
Query query = AnalyzerUtils.buildBagOfWordsQuery("body", new EnglishAnalyzer(), qq.getValue("title"));
//System.out.println(query);
TopDocs rs = searcher.search(query, maxResults);
RerankerContext context = new RerankerContext(searcher, query, qq.getValue("title"), null);
RerankerCascade cascade = new RerankerCascade(context);
cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body"));
ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher));
for (int i=0; i<docs.documents.length; i++) {
String qid = qq.getQueryID();
out.println(String.format("%s Q0 %s %d %f %s", qid,
docs.documents[i].getField("docid").stringValue(), (i+1), docs.scores[i], "Lucene"));
}
}
// // run the benchmark
// QualityBenchmark qrun = new QualityBenchmark(qqs, qqParser, searcher, docNameField);
// qrun.setMaxResults(maxResults);
// QualityStats stats[] = qrun.execute(judge, submitLog, logger);
//
// // print an avarage sum of the results
// QualityStats avg = QualityStats.average(stats);
// avg.log("SUMMARY", 2, logger, " ");
reader.close();
dir.close();
out.close();
}
#location 55
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
long curTime = System.nanoTime();
SearchArgs searchArgs = new SearchArgs();
CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90));
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.err.println("Example: SearchGov2" + parser.printExample(OptionHandlerFilter.REQUIRED));
return;
}
Path topicsFile = Paths.get(searchArgs.topics);
LOG.info("Reading index at " + searchArgs.index);
Directory dir;
if (searchArgs.inmem) {
LOG.info("Using MMapDirectory with preload");
dir = new MMapDirectory(Paths.get(searchArgs.index));
((MMapDirectory) dir).setPreload(true);
} else {
LOG.info("Using default FSDirectory");
dir = FSDirectory.open(Paths.get(searchArgs.index));
}
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
if (searchArgs.ql) {
LOG.info("Using QL scoring model");
searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
} else if (searchArgs.rm3) {
LOG.info("Using RM3 query expansion");
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
} else if (searchArgs.bm25) {
LOG.info("Using BM25 scoring model");
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
} else {
LOG.error("Error: Must specify scoring model!");
System.exit(-1);
}
int maxResults = 1000;
TrecTopicsReader qReader = new TrecTopicsReader();
QualityQuery qqs[] = qReader.readQueries(Files.newBufferedReader(topicsFile, StandardCharsets.UTF_8));
PrintStream out = new PrintStream(new FileOutputStream(new File(searchArgs.output)));
LOG.info("Writing output to " + searchArgs.output);
LOG.info("Initialized complete! (elapsed time = " + (System.nanoTime()-curTime)/1000000 + "ms)");
long totalTime = 0;
for (QualityQuery qq : qqs) {
long curQueryTime = System.nanoTime();
Query query = AnalyzerUtils.buildBagOfWordsQuery("body", new EnglishAnalyzer(), qq.getValue("title"));
TopDocs rs = searcher.search(query, maxResults);
RerankerContext context = new RerankerContext(searcher, query, qq.getValue("title"), null);
RerankerCascade cascade = new RerankerCascade(context);
if (searchArgs.rm3) {
cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body"));
} else {
cascade.add(new IdentityReranker());
}
ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher));
for (int i=0; i<docs.documents.length; i++) {
String qid = qq.getQueryID();
out.println(String.format("%s Q0 %s %d %f %s", qid,
docs.documents[i].getField("docid").stringValue(), (i+1), docs.scores[i], "Lucene"));
}
long qtime = (System.nanoTime()-curQueryTime)/1000000;
LOG.info("Query " + qq.getQueryID() + " (elapsed time = " + qtime + "ms)");
totalTime += qtime;
}
LOG.info("All queries completed!");
LOG.info("Total elapsed time = " + totalTime + "ms");
LOG.info("Average query latency = " + (totalTime/qqs.length) + "ms");
reader.close();
dir.close();
out.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private OMElement efetuaConsulta(final OMElement omElementConsulta, final NotaFiscalChaveParser notaFiscalChaveParser) throws AxisFault, RemoteException {
final NfeConsulta2Stub.NfeCabecMsg cabec = new NfeConsulta2Stub.NfeCabecMsg();
cabec.setCUF(notaFiscalChaveParser.getNFUnidadeFederativa().getCodigoIbge());
cabec.setVersaoDados("2.01");
final NfeConsulta2Stub.NfeCabecMsgE cabecE = new NfeConsulta2Stub.NfeCabecMsgE();
cabecE.setNfeCabecMsg(cabec);
final NfeConsulta2Stub.NfeDadosMsg dados = new NfeConsulta2Stub.NfeDadosMsg();
dados.setExtraElement(omElementConsulta);
final NfeConsultaNF2Result consultaNF2Result = new NfeConsulta2Stub(NFAutorizador.valueOfCodigoUF(this.config.getCUF()).getNfeConsultaProtocolo(this.config.getAmbiente())).nfeConsultaNF2(dados, cabecE);
return consultaNF2Result.getExtraElement();
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
private OMElement efetuaConsulta(final OMElement omElementConsulta, final NotaFiscalChaveParser notaFiscalChaveParser) throws AxisFault, RemoteException {
final NfeConsulta2Stub.NfeCabecMsg cabec = new NfeConsulta2Stub.NfeCabecMsg();
cabec.setCUF(notaFiscalChaveParser.getNFUnidadeFederativa().getCodigoIbge());
cabec.setVersaoDados("2.01");
final NfeConsulta2Stub.NfeCabecMsgE cabecE = new NfeConsulta2Stub.NfeCabecMsgE();
cabecE.setNfeCabecMsg(cabec);
final NfeConsulta2Stub.NfeDadosMsg dados = new NfeConsulta2Stub.NfeDadosMsg();
dados.setExtraElement(omElementConsulta);
final NfeConsultaNF2Result consultaNF2Result = new NfeConsulta2Stub(NFAutorizador.valueOfCodigoUF(notaFiscalChaveParser.getNFUnidadeFederativa()).getNfeConsultaProtocolo(this.config.getAmbiente())).nfeConsultaNF2(dados, cabecE);
return consultaNF2Result.getExtraElement();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
}
if (!GuildUtils.tagExists(args[0])) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
GuildUtils.deleteGuild(guild);
sender.sendMessage(messages.deleteSuccessful.replace("{GUILD}", guild.getName()).replace("{TAG}", guild.getTag()));
Player owner = guild.getOwner().getPlayer();
if (owner != null) {
owner.sendMessage(messages.adminGuildBroken.replace("{ADMIN}", sender.getName()));
}
Bukkit.getServer().broadcastMessage(messages.broadcastDelete.replace("{PLAYER}", sender.getName()).replace("{GUILD}", guild.getName()).replace("{TAG}", guild.getTag()));
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
if (guild == null) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
GuildUtils.deleteGuild(guild);
Player owner = guild.getOwner().getPlayer();
MessageTranslator translator = new MessageTranslator()
.register("{GUILD}", guild.getName())
.register("{TAG}", guild.getTag())
.register("{ADMIN}", sender.getName())
.register("{PLAYER}", sender.getName());
if (owner != null) {
owner.sendMessage(translator.translate(messages.adminGuildBroken));
}
sender.sendMessage(translator.translate(messages.deleteSuccessful));
Bukkit.getServer().broadcastMessage(translator.translate(messages.broadcastDelete));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig msg = Messages.getInstance();
String tag = null;
if (args.length > 0) {
tag = args[0];
} else if (sender instanceof Player) {
User user = User.get((Player) sender);
if (user.hasGuild()) {
tag = user.getGuild().getTag();
}
}
if (tag == null || tag.isEmpty()) {
sender.sendMessage(msg.infoTag);
return;
}
if (!GuildUtils.tagExists(tag)) {
sender.sendMessage(msg.infoExists);
return;
}
Guild guild = GuildUtils.byTag(tag);
if (guild == null) {
sender.sendMessage(msg.infoExists);
return;
}
String validity = Settings.getConfig().dateFormat.format(new Date(guild.getValidity()));
for (String m : msg.infoList) {
m = StringUtils.replace(m, "{GUILD}", guild.getName());
m = StringUtils.replace(m, "{TAG}", guild.getTag());
m = StringUtils.replace(m, "{OWNER}", guild.getOwner().getName());
m = StringUtils.replace(m, "{MEMBERS}", StringUtils.toString(UserUtils.getOnlineNames(guild.getMembers()), true));
m = StringUtils.replace(m, "{POINTS}", Integer.toString(guild.getRank().getPoints()));
m = StringUtils.replace(m, "{KILLS}", Integer.toString(guild.getRank().getKills()));
m = StringUtils.replace(m, "{DEATHS}", Integer.toString(guild.getRank().getDeaths()));
m = StringUtils.replace(m, "{KDR}", String.format(Locale.US, "%.2f", guild.getRank().getKDR()));
m = StringUtils.replace(m, "{RANK}", Integer.toString(RankManager.getInstance().getPosition(guild)));
m = StringUtils.replace(m, "{VALIDITY}", validity);
m = StringUtils.replace(m, "{LIVES}", Integer.toString(guild.getLives()));
if (guild.getAllies().size() > 0) {
m = StringUtils.replace(m, "{ALLIES}", StringUtils.toString(GuildUtils.getNames(guild.getAllies()), true));
} else {
m = StringUtils.replace(m, "{ALLIES}", "Brak");
}
if (m.contains("<online>")) {
String color = ChatColor.getLastColors(m.split("<online>")[0]);
m = StringUtils.replace(m, "<online>", ChatColor.GREEN + "");
m = StringUtils.replace(m, "</online>", color);
}
sender.sendMessage(m);
}
}
#location 32
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
String tag = null;
if (args.length > 0) {
tag = args[0];
}
else if (sender instanceof Player) {
User user = User.get((Player) sender);
if (user.hasGuild()) {
tag = user.getGuild().getTag();
}
}
if (tag == null || tag.isEmpty()) {
sender.sendMessage(messages.infoTag);
return;
}
if (!GuildUtils.tagExists(tag)) {
sender.sendMessage(messages.infoExists);
return;
}
Guild guild = GuildUtils.byTag(tag);
if (guild == null) {
sender.sendMessage(messages.infoExists);
return;
}
String validity = Settings.getConfig().dateFormat.format(new Date(guild.getValidity()));
for (String messageLine : messages.infoList) {
messageLine = StringUtils.replace(messageLine, "{GUILD}", guild.getName());
messageLine = StringUtils.replace(messageLine, "{TAG}", guild.getTag());
messageLine = StringUtils.replace(messageLine, "{OWNER}", guild.getOwner().getName());
messageLine = StringUtils.replace(messageLine, "{MEMBERS}", StringUtils.toString(UserUtils.getOnlineNames(guild.getMembers()), true));
messageLine = StringUtils.replace(messageLine, "{POINTS}", Integer.toString(guild.getRank().getPoints()));
messageLine = StringUtils.replace(messageLine, "{KILLS}", Integer.toString(guild.getRank().getKills()));
messageLine = StringUtils.replace(messageLine, "{DEATHS}", Integer.toString(guild.getRank().getDeaths()));
messageLine = StringUtils.replace(messageLine, "{KDR}", String.format(Locale.US, "%.2f", guild.getRank().getKDR()));
messageLine = StringUtils.replace(messageLine, "{RANK}", Integer.toString(RankManager.getInstance().getPosition(guild)));
messageLine = StringUtils.replace(messageLine, "{VALIDITY}", validity);
messageLine = StringUtils.replace(messageLine, "{LIVES}", Integer.toString(guild.getLives()));
if (guild.getAllies().size() > 0) {
messageLine = StringUtils.replace(messageLine, "{ALLIES}", StringUtils.toString(GuildUtils.getNames(guild.getAllies()), true));
} else {
messageLine = StringUtils.replace(messageLine, "{ALLIES}", "Brak");
}
if (messageLine.contains("<online>")) {
String color = ChatColor.getLastColors(messageLine.split("<online>")[0]);
messageLine = StringUtils.replace(messageLine, "<online>", ChatColor.GREEN + "");
messageLine = StringUtils.replace(messageLine, "</online>", color);
}
sender.sendMessage(messageLine);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static RankManager getInstance() {
if (instance == null) {
new RankManager();
}
return instance;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public static RankManager getInstance() {
return INSTANCE;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler
public void onExplode(EntityExplodeEvent event) {
List<Block> destroyed = event.blockList();
Location loc = event.getLocation();
Settings s = Settings.getInstance();
List<Location> sphere = SpaceUtils.sphere(loc, s.explodeRadius, s.explodeRadius, false, true, 0);
Map<Material, Double> materials = s.explodeMaterials;
for (Location l : sphere) {
Material material = l.getBlock().getType();
if (!materials.containsKey(material)) {
continue;
}
if (material == Material.WATER || material == Material.LAVA) {
if (RandomizationUtils.chance(materials.get(material))) {
l.getBlock().setType(Material.AIR);
}
}
else {
if (RandomizationUtils.chance(materials.get(material))) {
l.getBlock().breakNaturally();
}
}
}
if (!RegionUtils.isIn(loc)) {
return;
}
Region region = RegionUtils.getAt(loc);
Location protect = region.getCenter().getBlock().getRelative(BlockFace.DOWN).getLocation();
Iterator<Block> it = destroyed.iterator();
while (it.hasNext()) {
if (it.next().getLocation().equals(protect)) {
it.remove();
}
}
Guild guild = region.getGuild();
guild.setBuild(System.currentTimeMillis() + Settings.getInstance().regionExplode * 1000L);
for (User user : guild.getMembers()) {
Player player = this.plugin.getServer().getPlayer(user.getName());
if (player != null) {
player.sendMessage(Messages.getInstance().getMessage("regionExplode")
.replace("{TIME}", Integer.toString(Settings.getInstance().regionExplode)));
}
}
}
#location 31
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler
public void onExplode(EntityExplodeEvent event) {
List<Block> destroyed = event.blockList();
Location loc = event.getLocation();
Settings s = Settings.getInstance();
List<Location> sphere = SpaceUtils.sphere(loc, s.explodeRadius, s.explodeRadius, false, true, 0);
Map<Material, Double> materials = s.explodeMaterials;
if (RegionUtils.isIn(loc)) {
Region region = RegionUtils.getAt(loc);
Guild guild = region.getGuild();
if (guild.isValid()) {
event.setCancelled(true);
return;
}
Location protect = region.getCenter().getBlock().getRelative(BlockFace.DOWN).getLocation();
destroyed.removeIf(block -> block.getLocation().equals(protect));
guild.setBuild(System.currentTimeMillis() + Settings.getInstance().regionExplode * 1000L);
for (User user : guild.getMembers()) {
Player player = this.plugin.getServer().getPlayer(user.getName());
if (player != null) {
player.sendMessage(Messages.getInstance().getMessage("regionExplode")
.replace("{TIME}", Integer.toString(Settings.getInstance().regionExplode)));
}
}
}
for (Location l : sphere) {
Material material = l.getBlock().getType();
if (!materials.containsKey(material)) {
continue;
}
if (material == Material.WATER || material == Material.LAVA) {
if (RandomizationUtils.chance(materials.get(material))) {
l.getBlock().setType(Material.AIR);
}
}
else {
if (RandomizationUtils.chance(materials.get(material))) {
l.getBlock().breakNaturally();
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static int spawnPacket(Location loc) throws Exception {
Object world = Reflections.getHandle(loc.getWorld());
Object crystal = enderCrystalClass.getConstructor(Reflections.getCraftClass("World")).newInstance(world);
Reflections.getMethod(enderCrystalClass, "setLocation", double.class, double.class, double.class, float.class, float.class).invoke(crystal, loc.getX(), loc.getY(), loc.getZ(), 0, 0);
Object packet = spawnEntityClass.getConstructor(new Class<?>[]{entityClass, int.class}).newInstance(crystal, 51);
int id = (int) Reflections.getMethod(enderCrystalClass, "getId").invoke(crystal);
ids.put(id, packet);
return id;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
private static int spawnPacket(Location loc) throws Exception {
Object world = Reflections.getHandle(loc.getWorld());
Object crystal = enderCrystalConstructor.newInstance(world);
setLocation.invoke(crystal, loc.getX(), loc.getY(), loc.getZ(), 0, 0);
Object packet = spawnEntityConstructor.newInstance(crystal, 51);
int id = (int) getId.invoke(crystal);
ids.put(id, packet);
return id;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static IndependentThread getInstance() {
if (instance == null) {
new IndependentThread().start();
}
return instance;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public static IndependentThread getInstance() {
if (instance == null) {
new IndependentThread().start();
}
return instance;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig msg = Messages.getInstance();
String tag = null;
if (args.length > 0) {
tag = args[0];
} else if (sender instanceof Player) {
User user = User.get((Player) sender);
if (user.hasGuild()) {
tag = user.getGuild().getTag();
}
}
if (tag == null || tag.isEmpty()) {
sender.sendMessage(msg.infoTag);
return;
}
if (!GuildUtils.tagExists(tag)) {
sender.sendMessage(msg.infoExists);
return;
}
Guild guild = GuildUtils.byTag(tag);
if (guild == null) {
sender.sendMessage(msg.infoExists);
return;
}
String validity = Settings.getConfig().dateFormat.format(new Date(guild.getValidity()));
for (String m : msg.infoList) {
m = StringUtils.replace(m, "{GUILD}", guild.getName());
m = StringUtils.replace(m, "{TAG}", guild.getTag());
m = StringUtils.replace(m, "{OWNER}", guild.getOwner().getName());
m = StringUtils.replace(m, "{MEMBERS}", StringUtils.toString(UserUtils.getOnlineNames(guild.getMembers()), true));
m = StringUtils.replace(m, "{POINTS}", Integer.toString(guild.getRank().getPoints()));
m = StringUtils.replace(m, "{KILLS}", Integer.toString(guild.getRank().getKills()));
m = StringUtils.replace(m, "{DEATHS}", Integer.toString(guild.getRank().getDeaths()));
m = StringUtils.replace(m, "{KDR}", String.format(Locale.US, "%.2f", guild.getRank().getKDR()));
m = StringUtils.replace(m, "{RANK}", Integer.toString(RankManager.getInstance().getPosition(guild)));
m = StringUtils.replace(m, "{VALIDITY}", validity);
m = StringUtils.replace(m, "{LIVES}", Integer.toString(guild.getLives()));
if (guild.getAllies().size() > 0) {
m = StringUtils.replace(m, "{ALLIES}", StringUtils.toString(GuildUtils.getNames(guild.getAllies()), true));
} else {
m = StringUtils.replace(m, "{ALLIES}", "Brak");
}
if (m.contains("<online>")) {
String color = ChatColor.getLastColors(m.split("<online>")[0]);
m = StringUtils.replace(m, "<online>", ChatColor.GREEN + "");
m = StringUtils.replace(m, "</online>", color);
}
sender.sendMessage(m);
}
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
String tag = null;
if (args.length > 0) {
tag = args[0];
}
else if (sender instanceof Player) {
User user = User.get((Player) sender);
if (user.hasGuild()) {
tag = user.getGuild().getTag();
}
}
if (tag == null || tag.isEmpty()) {
sender.sendMessage(messages.infoTag);
return;
}
if (!GuildUtils.tagExists(tag)) {
sender.sendMessage(messages.infoExists);
return;
}
Guild guild = GuildUtils.byTag(tag);
if (guild == null) {
sender.sendMessage(messages.infoExists);
return;
}
String validity = Settings.getConfig().dateFormat.format(new Date(guild.getValidity()));
for (String messageLine : messages.infoList) {
messageLine = StringUtils.replace(messageLine, "{GUILD}", guild.getName());
messageLine = StringUtils.replace(messageLine, "{TAG}", guild.getTag());
messageLine = StringUtils.replace(messageLine, "{OWNER}", guild.getOwner().getName());
messageLine = StringUtils.replace(messageLine, "{MEMBERS}", StringUtils.toString(UserUtils.getOnlineNames(guild.getMembers()), true));
messageLine = StringUtils.replace(messageLine, "{POINTS}", Integer.toString(guild.getRank().getPoints()));
messageLine = StringUtils.replace(messageLine, "{KILLS}", Integer.toString(guild.getRank().getKills()));
messageLine = StringUtils.replace(messageLine, "{DEATHS}", Integer.toString(guild.getRank().getDeaths()));
messageLine = StringUtils.replace(messageLine, "{KDR}", String.format(Locale.US, "%.2f", guild.getRank().getKDR()));
messageLine = StringUtils.replace(messageLine, "{RANK}", Integer.toString(RankManager.getInstance().getPosition(guild)));
messageLine = StringUtils.replace(messageLine, "{VALIDITY}", validity);
messageLine = StringUtils.replace(messageLine, "{LIVES}", Integer.toString(guild.getLives()));
if (guild.getAllies().size() > 0) {
messageLine = StringUtils.replace(messageLine, "{ALLIES}", StringUtils.toString(GuildUtils.getNames(guild.getAllies()), true));
} else {
messageLine = StringUtils.replace(messageLine, "{ALLIES}", "Brak");
}
if (messageLine.contains("<online>")) {
String color = ChatColor.getLastColors(messageLine.split("<online>")[0]);
messageLine = StringUtils.replace(messageLine, "<online>", ChatColor.GREEN + "");
messageLine = StringUtils.replace(messageLine, "</online>", color);
}
sender.sendMessage(messageLine);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
} else if (args.length < 2) {
sender.sendMessage(messages.adminNoValidityTimeGiven);
return;
}
if (!GuildUtils.tagExists(args[0])) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
if (guild.isBanned()) {
sender.sendMessage(messages.adminGuildBanned);
return;
}
long time = Parser.parseTime(args[1]);
if (time < 1) {
sender.sendMessage(messages.adminTimeError);
return;
}
long validity = guild.getValidity();
if (validity == 0) {
validity = System.currentTimeMillis();
}
validity += time;
guild.setValidity(validity);
sender.sendMessage(messages.adminNewValidity.replace("{GUILD}", guild.getName()).replace("{VALIDITY}", Settings.getConfig().dateFormat.format(new Date(validity))));
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
PluginConfig config = Settings.getConfig();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
} else if (args.length < 2) {
sender.sendMessage(messages.adminNoValidityTimeGiven);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
if (guild == null) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
if (guild.isBanned()) {
sender.sendMessage(messages.adminGuildBanned);
return;
}
long time = Parser.parseTime(args[1]);
if (time < 1) {
sender.sendMessage(messages.adminTimeError);
return;
}
long validity = guild.getValidity();
if (validity == 0) {
validity = System.currentTimeMillis();
}
validity += time;
guild.setValidity(validity);
String date = config.dateFormat.format(new Date(validity));
sender.sendMessage(messages.adminNewValidity.replace("{GUILD}", guild.getName()).replace("{VALIDITY}", date));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void onLoad() {
this.logger = new FunnyGuildsLogger(this);
try {
Class.forName("net.md_5.bungee.api.ChatColor");
}
catch (Exception spigotNeeded) {
FunnyGuilds.getInstance().getPluginLogger().info("FunnyGuilds requires spigot to work, your server seems to be using something else");
FunnyGuilds.getInstance().getPluginLogger().info("If you think that is not true - contact plugin developers");
FunnyGuilds.getInstance().getPluginLogger().info("https://github.com/FunnyGuilds/FunnyGuilds");
getServer().getPluginManager().disablePlugin(this);
this.forceDisabling = true;
return;
}
if (! this.getDataFolder().exists()) {
this.getDataFolder().mkdir();
}
try {
this.pluginConfiguration = ConfigHelper.loadConfig(this.pluginConfigurationFile, PluginConfiguration.class);
this.messageConfiguration = ConfigHelper.loadConfig(this.messageConfigurationFile, MessageConfiguration.class);
this.pluginConfiguration.load();
this.messageConfiguration.load();
}
catch (Exception ex) {
this.getPluginLogger().error("Could not load plugin configuration", ex);
this.getServer().getPluginManager().disablePlugin(this);
this.forceDisabling = true;
return;
}
DescriptionChanger descriptionChanger = new DescriptionChanger(super.getDescription());
String[] versions = descriptionChanger.extractVersion();
this.fullVersion = versions[0];
this.mainVersion = versions[1];
PluginConfiguration settings = FunnyGuilds.getInstance().getPluginConfiguration();
descriptionChanger.rename(settings.pluginName);
this.concurrencyManager = new ConcurrencyManager(settings.concurrencyThreads);
this.concurrencyManager.printStatus();
Commands commands = new Commands();
commands.register();
this.dynamicListenerManager = new DynamicListenerManager(this);
}
#location 44
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void onLoad() {
funnyguilds = this;
this.logger = new FunnyGuildsLogger(this);
try {
Class.forName("net.md_5.bungee.api.ChatColor");
}
catch (Exception spigotNeeded) {
FunnyGuilds.getInstance().getPluginLogger().info("FunnyGuilds requires spigot to work, your server seems to be using something else");
FunnyGuilds.getInstance().getPluginLogger().info("If you think that is not true - contact plugin developers");
FunnyGuilds.getInstance().getPluginLogger().info("https://github.com/FunnyGuilds/FunnyGuilds");
getServer().getPluginManager().disablePlugin(this);
this.forceDisabling = true;
return;
}
if (! this.getDataFolder().exists()) {
this.getDataFolder().mkdir();
}
try {
this.pluginConfiguration = ConfigHelper.loadConfig(this.pluginConfigurationFile, PluginConfiguration.class);
this.messageConfiguration = ConfigHelper.loadConfig(this.messageConfigurationFile, MessageConfiguration.class);
this.pluginConfiguration.load();
this.messageConfiguration.load();
}
catch (Exception ex) {
this.getPluginLogger().error("Could not load plugin configuration", ex);
this.getServer().getPluginManager().disablePlugin(this);
this.forceDisabling = true;
return;
}
DescriptionChanger descriptionChanger = new DescriptionChanger(super.getDescription());
String[] versions = descriptionChanger.extractVersion();
this.fullVersion = versions[0];
this.mainVersion = versions[1];
PluginConfiguration settings = FunnyGuilds.getInstance().getPluginConfiguration();
descriptionChanger.rename(settings.pluginName);
this.concurrencyManager = new ConcurrencyManager(settings.concurrencyThreads);
this.concurrencyManager.printStatus();
Commands commands = new Commands();
commands.register();
this.dynamicListenerManager = new DynamicListenerManager(this);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
}
if (!GuildUtils.tagExists(args[0])) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
if (!guild.isBanned()) {
sender.sendMessage(messages.adminGuildNotBanned);
return;
}
BanUtils.unban(guild);
sender.sendMessage(messages.adminGuildUnban.replace("{GUILD}", guild.getName()));
Bukkit.broadcastMessage(Messages.getInstance().broadcastUnban.replace("{GUILD}", guild.getName()).replace("{TAG}", guild.getTag()));
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
if (guild == null) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
if (!guild.isBanned()) {
sender.sendMessage(messages.adminGuildNotBanned);
return;
}
BanUtils.unban(guild);
MessageTranslator translator = new MessageTranslator()
.register("{GUILD}", guild.getName())
.register("{TAG}", guild.getName())
.register("{ADMIN}", sender.getName());
sender.sendMessage(translator.translate(messages.adminGuildUnban));
Bukkit.broadcastMessage(translator.translate(messages.broadcastUnban));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static RankManager getInstance() {
if (instance == null) {
new RankManager();
}
return instance;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public static RankManager getInstance() {
return INSTANCE;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private int[] getEloValues(int vP, int aP) {
PluginConfig config = Settings.getConfig();
int[] rankChanges = new int[2];
int aC = IntegerRange.inRange(aP, config.eloConstants);
int vC = IntegerRange.inRange(vP, config.eloConstants);
rankChanges[0] = (int) Math.round(aC * (1 - (1.0D / (1.0D + Math.pow(config.eloExponent, (vP - aP) / config.eloDivider)))));
rankChanges[1] = (int) Math.round(vC * (0 - (1.0D / (1.0D + Math.pow(config.eloExponent, (aP - vP) / config.eloDivider)))) * -1);
return rankChanges;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
private int[] getEloValues(int vP, int aP) {
PluginConfig config = Settings.getConfig();
int[] rankChanges = new int[2];
int aC = IntegerRange.inRange(aP, config.eloConstants, "ELO_CONSTANTS");
int vC = IntegerRange.inRange(vP, config.eloConstants, "ELO_CONSTANTS");
rankChanges[0] = (int) Math.round(aC * (1 - (1.0D / (1.0D + Math.pow(config.eloExponent, (vP - aP) / config.eloDivider)))));
rankChanges[1] = (int) Math.round(vC * (0 - (1.0D / (1.0D + Math.pow(config.eloExponent, (aP - vP) / config.eloDivider)))) * -1);
return rankChanges;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler
public void onJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
User user = User.get(player);
if (user == null) {
user = User.create(player);
}
user.updateReference(player);
PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration();
if (config.playerListEnable && ! AbstractTablist.hasTablist(player)) {
AbstractTablist.createTablist(config.playerList, config.playerListHeader, config.playerListFooter, config.playerListPing, player);
}
UserCache cache = user.getCache();
if (cache.getScoreboard() == null) {
cache.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
if (cache.getIndividualPrefix() == null && config.guildTagEnabled) {
IndividualPrefix prefix = new IndividualPrefix(user);
prefix.initialize();
cache.setIndividualPrefix(prefix);
}
ConcurrencyManager concurrencyManager = FunnyGuilds.getInstance().getConcurrencyManager();
concurrencyManager.postRequests(
new PrefixGlobalUpdatePlayer(player),
new DummyGlobalUpdateUserRequest(user),
new RankUpdateUserRequest(user)
);
this.plugin.getServer().getScheduler().runTaskLaterAsynchronously(this.plugin, () -> {
PacketExtension.registerPlayer(player);
FunnyGuildsVersion.isNewAvailable(player, false);
Region region = RegionUtils.getAt(player.getLocation());
if (region == null || region.getGuild() == null) {
return;
}
if (config.createEntityType != null) {
GuildEntityHelper.spawnGuildHeart(region.getGuild(), player);
}
}, 30L);
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler
public void onJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
User user = User.get(player);
if (user == null) {
user = User.create(player);
} else {
if (! user.getName().equals(player.getName())) {
user.setName(player.getName());
}
}
user.updateReference(player);
PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration();
if (config.playerListEnable && ! AbstractTablist.hasTablist(player)) {
AbstractTablist.createTablist(config.playerList, config.playerListHeader, config.playerListFooter, config.playerListPing, player);
}
UserCache cache = user.getCache();
if (cache.getScoreboard() == null) {
cache.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
if (cache.getIndividualPrefix() == null && config.guildTagEnabled) {
IndividualPrefix prefix = new IndividualPrefix(user);
prefix.initialize();
cache.setIndividualPrefix(prefix);
}
ConcurrencyManager concurrencyManager = FunnyGuilds.getInstance().getConcurrencyManager();
concurrencyManager.postRequests(
new PrefixGlobalUpdatePlayer(player),
new DummyGlobalUpdateUserRequest(user),
new RankUpdateUserRequest(user)
);
this.plugin.getServer().getScheduler().runTaskLaterAsynchronously(this.plugin, () -> {
PacketExtension.registerPlayer(player);
FunnyGuildsVersion.isNewAvailable(player, false);
Region region = RegionUtils.getAt(player.getLocation());
if (region == null || region.getGuild() == null) {
return;
}
if (config.createEntityType != null) {
GuildEntityHelper.spawnGuildHeart(region.getGuild(), player);
}
}, 30L);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static int spawnPacket(Location loc) throws Exception {
Object world = Reflections.getHandle(loc.getWorld());
Object crystal = enderCrystalClass.getConstructor(Reflections.getCraftClass("World")).newInstance(world);
Reflections.getMethod(enderCrystalClass, "setLocation", double.class, double.class, double.class, float.class, float.class).invoke(crystal, loc.getX(), loc.getY(), loc.getZ(), 0, 0);
Object packet = spawnEntityClass.getConstructor(new Class<?>[]{entityClass, int.class}).newInstance(crystal, 51);
int id = (int) Reflections.getMethod(enderCrystalClass, "getId").invoke(crystal);
ids.put(id, packet);
return id;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
private static int spawnPacket(Location loc) throws Exception {
Object world = Reflections.getHandle(loc.getWorld());
Object crystal = enderCrystalConstructor.newInstance(world);
setLocation.invoke(crystal, loc.getX(), loc.getY(), loc.getZ(), 0, 0);
Object packet = spawnEntityConstructor.newInstance(crystal, 51);
int id = (int) getId.invoke(crystal);
ids.put(id, packet);
return id;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void update(User user) {
if (!this.users.contains(user.getRank())) {
this.users.add(user.getRank());
}
synchronized (users) {
Collections.sort(users);
}
if (user.hasGuild()) {
update(user.getGuild());
}
for (int i = 0; i < users.size(); i++) {
Rank rank = users.get(i);
rank.setPosition(i + 1);
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void update(User user) {
if (! this.users.contains(user.getRank())) {
this.users.add(user.getRank());
}
Collections.sort(users);
if (user.hasGuild()) {
update(user.getGuild());
}
for (int i = 0; i < users.size(); i++) {
Rank rank = users.get(i);
rank.setPosition(i + 1);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
PluginConfig c = Settings.getConfig();
MessagesConfig m = Messages.getInstance();
Player p = (Player) sender;
User user = User.get(p);
if (!c.baseEnable) {
p.sendMessage(m.baseTeleportationDisabled);
return;
}
if (!user.hasGuild()) {
p.sendMessage(m.baseHasNotGuild);
return;
}
Guild guild = user.getGuild();
if (user.getTeleportation() != null) {
p.sendMessage(m.baseIsTeleportation);
return;
}
ItemStack[] items = Settings.getConfig().baseItems.toArray(new ItemStack[0]);
for (ItemStack is : items) {
if (!p.getInventory().containsAtLeast(is, is.getAmount())) {
String msg = m.baseItems;
if (msg.contains("{ITEM}")) {
StringBuilder sb = new StringBuilder();
sb.append(is.getAmount());
sb.append(" ");
sb.append(is.getType().toString().toLowerCase());
msg = msg.replace("{ITEM}", sb.toString());
}
if (msg.contains("{ITEMS}")) {
ArrayList<String> list = new ArrayList<String>();
for (ItemStack it : items) {
StringBuilder sb = new StringBuilder();
sb.append(it.getAmount());
sb.append(" ");
sb.append(it.getType().toString().toLowerCase());
list.add(sb.toString());
}
msg = msg.replace("{ITEMS}", StringUtils.toString(list, true));
}
p.sendMessage(msg);
return;
}
}
p.getInventory().removeItem(items);
int time = Settings.getConfig().baseDelay;
if (time < 1) {
p.teleport(guild.getHome());
p.sendMessage(m.baseTeleport);
return;
}
p.sendMessage(m.baseDontMove.replace("{TIME}", Integer.toString(time)));
Location before = p.getLocation();
AtomicInteger i = new AtomicInteger(1);
user.setTeleportation(Bukkit.getScheduler().runTaskTimer(FunnyGuilds.getInstance(), () -> {
if (!p.isOnline()) {
user.getTeleportation().cancel();
user.setTeleportation(null);
return;
}
if (!LocationUtils.equals(p.getLocation(), before)) {
user.getTeleportation().cancel();
p.sendMessage(m.baseMove);
user.setTeleportation(null);
p.getInventory().addItem(items);
return;
}
if (i.getAndIncrement() > time) {
user.getTeleportation().cancel();
p.sendMessage(m.baseTeleport);
p.teleport(guild.getHome());
user.setTeleportation(null);
}
}, 0L, 20L));
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
PluginConfig config = Settings.getConfig();
MessagesConfig messages = Messages.getInstance();
Player player = (Player) sender;
User user = User.get(player);
if (!config.baseEnable) {
player.sendMessage(messages.baseTeleportationDisabled);
return;
}
if (!user.hasGuild()) {
player.sendMessage(messages.baseHasNotGuild);
return;
}
Guild guild = user.getGuild();
if (user.getTeleportation() != null) {
player.sendMessage(messages.baseIsTeleportation);
return;
}
ItemStack[] items = Settings.getConfig().baseItems.toArray(new ItemStack[0]);
for (ItemStack is : items) {
if (!player.getInventory().containsAtLeast(is, is.getAmount())) {
String msg = messages.baseItems;
if (msg.contains("{ITEM}")) {
StringBuilder sb = new StringBuilder();
sb.append(is.getAmount());
sb.append(" ");
sb.append(is.getType().toString().toLowerCase());
msg = msg.replace("{ITEM}", sb.toString());
}
if (msg.contains("{ITEMS}")) {
ArrayList<String> list = new ArrayList<String>();
for (ItemStack it : items) {
StringBuilder sb = new StringBuilder();
sb.append(it.getAmount());
sb.append(" ");
sb.append(it.getType().toString().toLowerCase());
list.add(sb.toString());
}
msg = msg.replace("{ITEMS}", StringUtils.toString(list, true));
}
player.sendMessage(msg);
return;
}
}
player.getInventory().removeItem(items);
int time = Settings.getConfig().baseDelay;
if (time < 1) {
player.teleport(guild.getHome());
player.sendMessage(messages.baseTeleport);
return;
}
player.sendMessage(messages.baseDontMove.replace("{TIME}", Integer.toString(time)));
Location before = player.getLocation();
AtomicInteger i = new AtomicInteger(1);
user.setTeleportation(Bukkit.getScheduler().runTaskTimer(FunnyGuilds.getInstance(), () -> {
if (!player.isOnline()) {
user.getTeleportation().cancel();
user.setTeleportation(null);
return;
}
if (!LocationUtils.equals(player.getLocation(), before)) {
user.getTeleportation().cancel();
player.sendMessage(messages.baseMove);
user.setTeleportation(null);
player.getInventory().addItem(items);
return;
}
if (i.getAndIncrement() > time) {
user.getTeleportation().cancel();
player.sendMessage(messages.baseTeleport);
player.teleport(guild.getHome());
user.setTeleportation(null);
}
}, 0L, 20L));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
PluginConfig config = Settings.getConfig();
MessagesConfig messages = Messages.getInstance();
Player player = (Player) sender;
User user = User.get(player);
if (!config.baseEnable) {
player.sendMessage(messages.baseTeleportationDisabled);
return;
}
if (!user.hasGuild()) {
player.sendMessage(messages.baseHasNotGuild);
return;
}
Guild guild = user.getGuild();
if (user.getTeleportation() != null) {
player.sendMessage(messages.baseIsTeleportation);
return;
}
ItemStack[] items = Settings.getConfig().baseItems.toArray(new ItemStack[0]);
for (ItemStack is : items) {
if (!player.getInventory().containsAtLeast(is, is.getAmount())) {
String msg = messages.baseItems;
if (msg.contains("{ITEM}")) {
StringBuilder sb = new StringBuilder();
sb.append(is.getAmount());
sb.append(" ");
sb.append(is.getType().toString().toLowerCase());
msg = msg.replace("{ITEM}", sb.toString());
}
if (msg.contains("{ITEMS}")) {
ArrayList<String> list = new ArrayList<String>();
for (ItemStack it : items) {
StringBuilder sb = new StringBuilder();
sb.append(it.getAmount());
sb.append(" ");
sb.append(it.getType().toString().toLowerCase());
list.add(sb.toString());
}
msg = msg.replace("{ITEMS}", StringUtils.toString(list, true));
}
player.sendMessage(msg);
return;
}
}
player.getInventory().removeItem(items);
int time = Settings.getConfig().baseDelay;
if (time < 1) {
player.teleport(guild.getHome());
player.sendMessage(messages.baseTeleport);
return;
}
player.sendMessage(messages.baseDontMove.replace("{TIME}", Integer.toString(time)));
Location before = player.getLocation();
AtomicInteger i = new AtomicInteger(1);
user.setTeleportation(Bukkit.getScheduler().runTaskTimer(FunnyGuilds.getInstance(), () -> {
if (!player.isOnline()) {
user.getTeleportation().cancel();
user.setTeleportation(null);
return;
}
if (!LocationUtils.equals(player.getLocation(), before)) {
user.getTeleportation().cancel();
player.sendMessage(messages.baseMove);
user.setTeleportation(null);
player.getInventory().addItem(items);
return;
}
if (i.getAndIncrement() > time) {
user.getTeleportation().cancel();
player.sendMessage(messages.baseTeleport);
player.teleport(guild.getHome());
user.setTeleportation(null);
}
}, 0L, 20L));
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
PluginConfig config = Settings.getConfig();
MessagesConfig messages = Messages.getInstance();
Player player = (Player) sender;
User user = User.get(player);
if (!config.baseEnable) {
player.sendMessage(messages.baseTeleportationDisabled);
return;
}
if (!user.hasGuild()) {
player.sendMessage(messages.baseHasNotGuild);
return;
}
Guild guild = user.getGuild();
if (user.getTeleportation() != null) {
player.sendMessage(messages.baseIsTeleportation);
return;
}
Collection<ItemStack> requiredItems = config.baseItems;
for (ItemStack requiredItem : requiredItems) {
if (player.getInventory().containsAtLeast(requiredItem, requiredItem.getAmount())) {
continue;
}
String msg = ItemUtils.translatePlaceholder(messages.baseItems, requiredItems, requiredItem);
player.sendMessage(msg);
return;
}
ItemStack[] items = ItemUtils.toArray(requiredItems);
player.getInventory().removeItem(items);
if (config.baseDelay < 1) {
player.teleport(guild.getHome());
player.sendMessage(messages.baseTeleport);
return;
}
int time = config.baseDelay;
Location before = player.getLocation();
AtomicInteger i = new AtomicInteger(1);
user.setTeleportation(Bukkit.getScheduler().runTaskTimer(FunnyGuilds.getInstance(), () -> {
if (!player.isOnline()) {
user.getTeleportation().cancel();
user.setTeleportation(null);
return;
}
if (!LocationUtils.equals(player.getLocation(), before)) {
user.getTeleportation().cancel();
player.sendMessage(messages.baseMove);
user.setTeleportation(null);
player.getInventory().addItem(items);
return;
}
if (i.getAndIncrement() > time) {
user.getTeleportation().cancel();
player.sendMessage(messages.baseTeleport);
player.teleport(guild.getHome());
user.setTeleportation(null);
}
}, 0L, 20L));
player.sendMessage(messages.baseDontMove.replace("{TIME}", Integer.toString(time)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendMessageToGuild(Guild guild, Player player, String message) {
if (guild == null || player == null || !player.isOnline()) {
return;
}
for (User user : guild.getOnlineMembers()) {
Player p = user.getPlayer();
if (!p.equals(player) || !user.isSpy()) {
p.sendMessage(message);
}
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
private void sendMessageToGuild(Guild guild, Player player, String message) {
if (guild == null || player == null || !player.isOnline()) {
return;
}
for (User user : guild.getOnlineMembers()) {
Player p = user.getPlayer();
if (p == null) {
return;
}
if (!p.equals(player) || !user.isSpy()) {
p.sendMessage(message);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig m = Messages.getInstance();
Player p = (Player) sender;
User user = User.get(p);
if (user.hasGuild()) {
p.sendMessage(m.joinHasGuild);
return;
}
List<InvitationList.Invitation> invitations = InvitationList.getInvitationsFor(p);
if (invitations.size() == 0) {
p.sendMessage(m.joinHasNotInvitation);
return;
}
if (args.length < 1) {
String guildNames = StringUtils.toString(InvitationList.getInvitationGuildNames(p), false);
for (String msg : m.joinInvitationList) {
p.sendMessage(msg.replace("{GUILDS}", guildNames));
}
return;
}
String tag = args[0];
if (!GuildUtils.tagExists(tag)) {
p.sendMessage(m.joinTagExists);
return;
}
if (!InvitationList.hasInvitationFrom(p, GuildUtils.byTag(tag))) {
p.sendMessage(m.joinHasNotInvitationTo);
return;
}
List<ItemStack> itemsList = Settings.getConfig().joinItems;
for (ItemStack itemStack : itemsList) {
if (!p.getInventory().containsAtLeast(itemStack, itemStack.getAmount())) {
String msg = m.joinItems;
if (msg.contains("{ITEM}")) {
StringBuilder sb = new StringBuilder();
sb.append(itemStack.getAmount());
sb.append(" ");
sb.append(itemStack.getType().toString().toLowerCase());
msg = msg.replace("{ITEM}", sb.toString());
}
if (msg.contains("{ITEMS}")) {
ArrayList<String> list = new ArrayList<String>();
for (ItemStack it : itemsList) {
StringBuilder sb = new StringBuilder();
sb.append(it.getAmount());
sb.append(" ");
sb.append(it.getType().toString().toLowerCase());
list.add(sb.toString());
}
msg = msg.replace("{ITEMS}", StringUtils.toString(list, true));
}
p.sendMessage(msg);
return;
}
p.getInventory().removeItem(itemStack);
}
Guild guild = GuildUtils.byTag(tag);
InvitationList.expireInvitation(guild, p);
guild.addMember(user);
user.setGuild(guild);
IndependentThread.action(ActionType.PREFIX_GLOBAL_ADD_PLAYER, user.getOfflineUser());
p.sendMessage(m.joinToMember.replace("{GUILD}", guild.getName()).replace("{TAG}", guild.getTag()));
Player owner = guild.getOwner().getPlayer();
if (owner != null) {
owner.sendMessage(m.joinToOwner.replace("{PLAYER}", p.getName()));
}
Bukkit.broadcastMessage(m.broadcastJoin.replace("{PLAYER}", p.getName()).replace("{GUILD}", guild.getName()).replace("{TAG}", tag));
}
#location 74
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
Player player = (Player) sender;
User user = User.get(player);
if (user.hasGuild()) {
player.sendMessage(messages.joinHasGuild);
return;
}
List<InvitationList.Invitation> invitations = InvitationList.getInvitationsFor(player);
if (invitations.size() == 0) {
player.sendMessage(messages.joinHasNotInvitation);
return;
}
if (args.length < 1) {
String guildNames = StringUtils.toString(InvitationList.getInvitationGuildNames(player), false);
for (String msg : messages.joinInvitationList) {
player.sendMessage(msg.replace("{GUILDS}", guildNames));
}
return;
}
String tag = args[0];
Guild guild = Guild.get(tag);
if (guild == null) {
player.sendMessage(messages.joinTagExists);
return;
}
if (!InvitationList.hasInvitationFrom(player, GuildUtils.byTag(tag))) {
player.sendMessage(messages.joinHasNotInvitationTo);
return;
}
List<ItemStack> itemsList = Settings.getConfig().joinItems;
for (ItemStack itemStack : itemsList) {
if (!player.getInventory().containsAtLeast(itemStack, itemStack.getAmount())) {
String msg = messages.joinItems;
if (msg.contains("{ITEM}")) {
StringBuilder sb = new StringBuilder();
sb.append(itemStack.getAmount());
sb.append(" ");
sb.append(itemStack.getType().toString().toLowerCase());
msg = msg.replace("{ITEM}", sb.toString());
}
if (msg.contains("{ITEMS}")) {
ArrayList<String> list = new ArrayList<String>();
for (ItemStack it : itemsList) {
StringBuilder sb = new StringBuilder();
sb.append(it.getAmount());
sb.append(" ");
sb.append(it.getType().toString().toLowerCase());
list.add(sb.toString());
}
msg = msg.replace("{ITEMS}", StringUtils.toString(list, true));
}
player.sendMessage(msg);
return;
}
player.getInventory().removeItem(itemStack);
}
InvitationList.expireInvitation(guild, player);
guild.addMember(user);
user.setGuild(guild);
IndependentThread.action(ActionType.PREFIX_GLOBAL_ADD_PLAYER, user.getOfflineUser());
MessageTranslator translator = new MessageTranslator()
.register("{GUILD}", guild.getName())
.register("{TAG}", guild.getTag())
.register("{PLAYER}", player.getName());
player.sendMessage(translator.translate(messages.joinToMember));
Bukkit.broadcastMessage(translator.translate(messages.broadcastJoin));
Player owner = guild.getOwner().getPlayer();
if (owner != null) {
owner.sendMessage(translator.translate(messages.joinToOwner));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private int[] getEloValues(int vP, int aP) {
PluginConfig config = Settings.getConfig();
int[] rankChanges = new int[2];
int aC = IntegerRange.inRange(aP, config.eloConstants);
int vC = IntegerRange.inRange(vP, config.eloConstants);
rankChanges[0] = (int) Math.round(aC * (1 - (1.0D / (1.0D + Math.pow(config.eloExponent, (vP - aP) / config.eloDivider)))));
rankChanges[1] = (int) Math.round(vC * (0 - (1.0D / (1.0D + Math.pow(config.eloExponent, (aP - vP) / config.eloDivider)))) * -1);
return rankChanges;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
private int[] getEloValues(int vP, int aP) {
PluginConfig config = Settings.getConfig();
int[] rankChanges = new int[2];
int aC = IntegerRange.inRange(aP, config.eloConstants, "ELO_CONSTANTS");
int vC = IntegerRange.inRange(vP, config.eloConstants, "ELO_CONSTANTS");
rankChanges[0] = (int) Math.round(aC * (1 - (1.0D / (1.0D + Math.pow(config.eloExponent, (vP - aP) / config.eloDivider)))));
rankChanges[1] = (int) Math.round(vC * (0 - (1.0D / (1.0D + Math.pow(config.eloExponent, (aP - vP) / config.eloDivider)))) * -1);
return rankChanges;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
}
if (args.length < 2) {
sender.sendMessage(messages.adminNoLivesGiven);
return;
}
if (!GuildUtils.tagExists(args[0])) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
int lives;
try {
lives = Integer.valueOf(args[1]);
} catch (NumberFormatException e) {
sender.sendMessage(messages.adminErrorInNumber.replace("{ERROR}", args[1]));;
return;
}
guild.setLives(lives);
sender.sendMessage(messages.adminLivesChanged.replace("{GUILD}", guild.getTag()).replace("{LIVES}", Integer.toString(lives)));
}
#location 30
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
}
if (args.length < 2) {
sender.sendMessage(messages.adminNoLivesGiven);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
if (guild == null) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
int lives;
try {
lives = Integer.valueOf(args[1]);
} catch (NumberFormatException e) {
sender.sendMessage(messages.adminErrorInNumber.replace("{ERROR}", args[1]));
return;
}
guild.setLives(lives);
sender.sendMessage(messages.adminLivesChanged.replace("{GUILD}", guild.getTag()).replace("{LIVES}", Integer.toString(lives)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
}
if (!GuildUtils.tagExists(args[0])) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
if (args.length < 2) {
sender.sendMessage(messages.generalNoNickGiven);
return;
}
if (!UserUtils.playedBefore(args[1])) {
sender.sendMessage(messages.generalNotPlayedBefore);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
User user = User.get(args[1]);
if (!guild.getMembers().contains(user)) {
sender.sendMessage(messages.adminUserNotMemberOf);
return;
}
Player player = user.getPlayer();
if (user.isDeputy()) {
guild.setDeputy(null);
sender.sendMessage(messages.deputyRemove);
if (player != null) {
player.sendMessage(messages.deputyMember);
}
for (User member : guild.getOnlineMembers()) {
member.getPlayer().sendMessage(messages.deputyNoLongerMembers.replace("{PLAYER}", user.getName()));
}
return;
}
guild.setDeputy(user);
sender.sendMessage(messages.deputySet);
if (player != null) {
player.sendMessage(messages.deputyOwner);
}
for (User member : guild.getOnlineMembers()) {
member.getPlayer().sendMessage(messages.deputyMembers.replace("{PLAYER}", user.getName()));
}
}
#location 28
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
if (guild == null) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
if (args.length < 2) {
sender.sendMessage(messages.generalNoNickGiven);
return;
}
if (!UserUtils.playedBefore(args[1])) {
sender.sendMessage(messages.generalNotPlayedBefore);
return;
}
User user = User.get(args[1]);
Player player = user.getPlayer();
if (!guild.getMembers().contains(user)) {
sender.sendMessage(messages.adminUserNotMemberOf);
return;
}
MessageTranslator translator = new MessageTranslator()
.register("{PLAYER}", user.getName());
if (user.isDeputy()) {
guild.setDeputy(null);
sender.sendMessage(messages.deputyRemove);
if (player != null) {
player.sendMessage(messages.deputyMember);
}
String message = translator.translate(messages.deputyNoLongerMembers);
for (User member : guild.getOnlineMembers()) {
member.getPlayer().sendMessage(message);
}
return;
}
guild.setDeputy(user);
sender.sendMessage(messages.deputySet);
if (player != null) {
player.sendMessage(messages.deputyOwner);
}
String message = translator.translate(messages.deputyMembers);
for (User member : guild.getOnlineMembers()) {
member.getPlayer().sendMessage(message);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean isInIgnoredRegion(Location location) {
if (! isInRegion(location)) {
return false;
}
PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration();
return getRegionSet(location).getRegions()
.stream()
.anyMatch(region -> config.assistsRegionsIgnored.contains(region.getId()));
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public boolean isInIgnoredRegion(Location location) {
PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration();
ApplicableRegionSet regionSet = getRegionSet(location);
if (regionSet == null) {
return false;
}
return regionSet.getRegions()
.stream()
.anyMatch(region -> config.assistsRegionsIgnored.contains(region.getId()));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void update(User user) {
if (!this.users.contains(user.getRank())) {
this.users.add(user.getRank());
}
synchronized (users) {
Collections.sort(users);
}
if (user.hasGuild()) {
update(user.getGuild());
}
for (int i = 0; i < users.size(); i++) {
Rank rank = users.get(i);
rank.setPosition(i + 1);
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void update(User user) {
if (! this.users.contains(user.getRank())) {
this.users.add(user.getRank());
}
Collections.sort(users);
if (user.hasGuild()) {
update(user.getGuild());
}
for (int i = 0; i < users.size(); i++) {
Rank rank = users.get(i);
rank.setPosition(i + 1);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
PluginConfig pc = Settings.getConfig();
MessagesConfig m = Messages.getInstance();
Player p = (Player) sender;
User user = User.get(p);
Guild guild = user.getGuild();
if (!user.hasGuild()) {
p.sendMessage(m.validityHasNotGuild);
return;
}
if (!user.isOwner() && !user.isDeputy()) {
p.sendMessage(m.validityIsNotOwner);
return;
}
if (pc.validityWhen != 0) {
long c = guild.getValidity();
long d = c - System.currentTimeMillis();
if (d > pc.validityWhen) {
long when = d - pc.validityWhen;
p.sendMessage(m.validityWhen.replace("{TIME}", TimeUtils.getDurationBreakdown(when)));
return;
}
}
List<ItemStack> itemsList = pc.validityItems;
for (ItemStack itemStack : itemsList) {
if (!p.getInventory().containsAtLeast(itemStack, itemStack.getAmount())) {
String msg = m.validityItems;
if (msg.contains("{ITEM}")) {
StringBuilder sb = new StringBuilder();
sb.append(itemStack.getAmount());
sb.append(" ");
sb.append(itemStack.getType().toString().toLowerCase());
msg = msg.replace("{ITEM}", sb.toString());
}
if (msg.contains("{ITEMS}")) {
ArrayList<String> list = new ArrayList<String>();
for (ItemStack it : itemsList) {
StringBuilder sb = new StringBuilder();
sb.append(it.getAmount());
sb.append(" ");
sb.append(it.getType().toString().toLowerCase());
list.add(sb.toString());
}
msg = msg.replace("{ITEMS}", StringUtils.toString(list, true));
}
p.sendMessage(msg);
return;
}
p.getInventory().removeItem(itemStack);
}
long c = guild.getValidity();
if (c == 0) {
c = System.currentTimeMillis();
}
c += pc.validityTime;
guild.setValidity(c);
p.sendMessage(m.validityDone.replace("{DATE}", pc.dateFormat.format(new Date(c))));
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
PluginConfig config = Settings.getConfig();
MessagesConfig messages = Messages.getInstance();
Player player = (Player) sender;
User user = User.get(player);
Guild guild = user.getGuild();
if (!user.hasGuild()) {
player.sendMessage(messages.validityHasNotGuild);
return;
}
if (!user.isOwner() && !user.isDeputy()) {
player.sendMessage(messages.validityIsNotOwner);
return;
}
if (config.validityWhen != 0) {
long c = guild.getValidity();
long d = c - System.currentTimeMillis();
if (d > config.validityWhen) {
long when = d - config.validityWhen;
player.sendMessage(messages.validityWhen.replace("{TIME}", TimeUtils.getDurationBreakdown(when)));
return;
}
}
List<ItemStack> itemsList = config.validityItems;
for (ItemStack itemStack : itemsList) {
if (!player.getInventory().containsAtLeast(itemStack, itemStack.getAmount())) {
String msg = messages.validityItems;
if (msg.contains("{ITEM}")) {
StringBuilder sb = new StringBuilder();
sb.append(itemStack.getAmount());
sb.append(" ");
sb.append(itemStack.getType().toString().toLowerCase());
msg = msg.replace("{ITEM}", sb.toString());
}
if (msg.contains("{ITEMS}")) {
ArrayList<String> list = new ArrayList<String>();
for (ItemStack it : itemsList) {
StringBuilder sb = new StringBuilder();
sb.append(it.getAmount());
sb.append(" ");
sb.append(it.getType().toString().toLowerCase());
list.add(sb.toString());
}
msg = msg.replace("{ITEMS}", StringUtils.toString(list, true));
}
player.sendMessage(msg);
return;
}
player.getInventory().removeItem(itemStack);
}
long c = guild.getValidity();
if (c == 0) {
c = System.currentTimeMillis();
}
c += config.validityTime;
guild.setValidity(c);
player.sendMessage(messages.validityDone.replace("{DATE}", config.dateFormat.format(new Date(c))));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendMessageToGuild(Guild guild, Player player, String message) {
for (User user : guild.getMembers()) {
Player loopedPlayer = this.plugin.getServer().getPlayer(user.getName());
if (loopedPlayer != null) {
if (user.getPlayer().equals(player)) {
if (!user.isSpy()) {
loopedPlayer.sendMessage(message);
}
} else {
loopedPlayer.sendMessage(message);
}
}
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
private void sendMessageToGuild(Guild guild, Player player, String message) {
for (User user : guild.getOnlineMembers()) {
Player p = user.getPlayer();
if(!p.equals(player) || !user.isSpy()) {
p.sendMessage(message);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
} else if (args.length < 2) {
sender.sendMessage(messages.adminNoNewNameGiven);
return;
}
if (!GuildUtils.tagExists(args[0])) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
if (GuildUtils.nameExists(args[1])) {
sender.sendMessage(messages.createNameExists);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
Region region = RegionUtils.get(guild.getRegion());
PluginConfig.DataType dataType = Settings.getConfig().dataType;
Manager.getInstance().stop();
if (dataType.flat) {
Flat.getGuildFile(guild).delete();
Flat.getRegionFile(region).delete();
}
if (dataType.mysql) {
new DatabaseGuild(guild).delete();
new DatabaseRegion(region).delete();
}
guild.setName(args[1]);
region.setName(args[1]);
Manager.getInstance().start();
sender.sendMessage(messages.adminNameChanged.replace("{GUILD}", guild.getName()));
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
} else if (args.length < 2) {
sender.sendMessage(messages.adminNoNewNameGiven);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
if (guild == null) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
if (GuildUtils.nameExists(args[1])) {
sender.sendMessage(messages.createNameExists);
return;
}
Manager.getInstance().stop();
PluginConfig.DataType dataType = Settings.getConfig().dataType;
Region region = RegionUtils.get(guild.getRegion());
if (dataType.flat) {
Flat.getGuildFile(guild).delete();
Flat.getRegionFile(region).delete();
}
if (dataType.mysql) {
new DatabaseGuild(guild).delete();
new DatabaseRegion(region).delete();
}
guild.setName(args[1]);
region.setName(args[1]);
Manager.getInstance().start();
sender.sendMessage(messages.adminNameChanged.replace("{GUILD}", guild.getName()));
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.