instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(expected = CannotParseException.class)
public void parseXml_bad_latitude() {
parseXCalProperty("<latitude>bad</latitude><longitude>56.78</longitude>", marshaller);
} | #vulnerable code
@Test(expected = CannotParseException.class)
public void parseXml_bad_latitude() {
ICalParameters params = new ICalParameters();
Element element = xcalPropertyElement(marshaller, "<latitude>bad</latitude><longitude>56.78</longitude>");
marshaller.parseXml(element, params);
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void parseXml() {
Result<DateTimePropertyImpl> result = parseXCalProperty("<date-time>2013-06-11T13:43:02Z</date-time>", marshaller);
DateTimePropertyImpl prop = result.getValue();
assertEquals(datetime, prop.getValue());
assertWarnings(0, result.getWarnings());
} | #vulnerable code
@Test
public void parseXml() {
ICalParameters params = new ICalParameters();
Element element = xcalPropertyElement(marshaller, "<date-time>2013-06-11T13:43:02Z</date-time>");
Result<DateTimePropertyImpl> result = marshaller.parseXml(element, params);
DateTimePropertyImpl prop = result.getValue();
assertEquals(datetime, prop.getValue());
assertWarnings(0, result.getWarnings());
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void writeXml_data_type() {
TextPropertyMarshallerImpl marshaller = new TextPropertyMarshallerImpl(Value.CAL_ADDRESS);
TextPropertyImpl prop = new TextPropertyImpl("mailto:[email protected]");
assertWriteXml("<cal-address>mailto:[email protected]</cal-address>", prop, marshaller);
} | #vulnerable code
@Test
public void writeXml_data_type() {
TextPropertyMarshallerImpl marshaller = new TextPropertyMarshallerImpl(Value.CAL_ADDRESS);
TextPropertyImpl prop = new TextPropertyImpl("mailto:[email protected]");
Document actual = xcalProperty(marshaller);
marshaller.writeXml(prop, XmlUtils.getRootElement(actual));
Document expected = xcalProperty(marshaller, "<cal-address>mailto:[email protected]</cal-address>");
assertXMLEqual(expected, actual);
}
#location 7
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void parseXml_missing_longitude() {
Result<Geo> result = parseXCalProperty("<latitude>12.34</latitude>", marshaller);
Geo prop = result.getValue();
assertEquals(12.34, prop.getLatitude(), 0.001);
assertNull(prop.getLongitude());
assertWarnings(0, result.getWarnings());
} | #vulnerable code
@Test
public void parseXml_missing_longitude() {
ICalParameters params = new ICalParameters();
Element element = xcalPropertyElement(marshaller, "<latitude>12.34</latitude>");
Result<Geo> result = marshaller.parseXml(element, params);
Geo prop = result.getValue();
assertEquals(12.34, prop.getLatitude(), 0.001);
assertNull(prop.getLongitude());
assertWarnings(0, result.getWarnings());
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(expected = CannotParseException.class)
public void parseXml_bad_longitude() {
parseXCalProperty("<latitude>12.34</latitude><longitude>bad</longitude>", marshaller);
} | #vulnerable code
@Test(expected = CannotParseException.class)
public void parseXml_bad_longitude() {
ICalParameters params = new ICalParameters();
Element element = xcalPropertyElement(marshaller, "<latitude>12.34</latitude><longitude>bad</longitude>");
marshaller.parseXml(element, params);
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void writeXml_missing_latitude() {
Geo prop = new Geo(null, 56.78);
assertWriteXml("<longitude>56.78</longitude>", prop, marshaller);
} | #vulnerable code
@Test
public void writeXml_missing_latitude() {
Geo prop = new Geo(null, 56.78);
Document actual = xcalProperty(marshaller);
marshaller.writeXml(prop, XmlUtils.getRootElement(actual));
Document expected = xcalProperty(marshaller, "<longitude>56.78</longitude>");
assertXMLEqual(expected, actual);
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void writeXml_null() {
TextPropertyImpl prop = new TextPropertyImpl(null);
assertWriteXml("<text></text>", prop, marshaller);
} | #vulnerable code
@Test
public void writeXml_null() {
TextPropertyImpl prop = new TextPropertyImpl(null);
Document actual = xcalProperty(marshaller);
marshaller.writeXml(prop, XmlUtils.getRootElement(actual));
Document expected = xcalProperty(marshaller, "<text></text>");
assertXMLEqual(expected, actual);
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void parseXml() {
Result<IntegerProperty> result = parseXCalProperty("<integer>5</integer>", marshaller);
IntegerProperty prop = result.getValue();
assertIntEquals(5, prop.getValue());
assertWarnings(0, result.getWarnings());
} | #vulnerable code
@Test
public void parseXml() {
ICalParameters params = new ICalParameters();
Element element = xcalPropertyElement(marshaller, "<integer>5</integer>");
Result<IntegerProperty> result = marshaller.parseXml(element, params);
IntegerProperty prop = result.getValue();
assertIntEquals(5, prop.getValue());
assertWarnings(0, result.getWarnings());
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void writeXml() {
Geo prop = new Geo(12.34, 56.78);
assertWriteXml("<latitude>12.34</latitude><longitude>56.78</longitude>", prop, marshaller);
} | #vulnerable code
@Test
public void writeXml() {
Geo prop = new Geo(12.34, 56.78);
Document actual = xcalProperty(marshaller);
marshaller.writeXml(prop, XmlUtils.getRootElement(actual));
Document expected = xcalProperty(marshaller, "<latitude>12.34</latitude><longitude>56.78</longitude>");
assertXMLEqual(expected, actual);
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void example2() throws Throwable {
VTimezone usEasternTz;
ICalendar ical = new ICalendar();
ical.getProperties().clear();
ical.setProductId("-//RDU Software//NONSGML HandCal//EN");
ical.setVersion(Version.v2_0());
{
usEasternTz = new VTimezone(null);
usEasternTz.setTimezoneId("America/New_York");
{
StandardTime standard = new StandardTime();
standard.setDateStart(localFormatter.parse("19981025T020000"));
standard.setTimezoneOffsetFrom(-4, 0);
standard.setTimezoneOffsetTo(-5, 0);
standard.addTimezoneName("EST");
usEasternTz.addStandardTime(standard);
}
{
DaylightSavingsTime daylight = new DaylightSavingsTime();
daylight.setDateStart(localFormatter.parse("19990404T020000"));
daylight.setTimezoneOffsetFrom(-5, 0);
daylight.setTimezoneOffsetTo(-4, 0);
daylight.addTimezoneName("EDT");
usEasternTz.addDaylightSavingsTime(daylight);
}
ical.addTimezone(usEasternTz);
}
{
VEvent event = new VEvent();
event.setDateTimeStamp(utcFormatter.parse("19980309T231000"));
event.setUid("guid-1.example.com");
event.setOrganizer("[email protected]");
Attendee attendee = Attendee.email("[email protected]");
attendee.setRsvp(true);
attendee.setRole(Role.REQ_PARTICIPANT);
attendee.setCalendarUserType(CalendarUserType.GROUP);
event.addAttendee(attendee);
event.setDescription("Project XYZ Review Meeting");
event.addCategories("MEETING");
event.setClassification(Classification.public_());
event.setCreated(utcFormatter.parse("19980309T130000"));
event.setSummary("XYZ Project Review");
event.setDateStart(usEasternFormatter.parse("19980312T083000")).setTimezone(usEasternTz);
event.setDateEnd(usEasternFormatter.parse("19980312T093000")).setTimezone(usEasternTz);
event.setLocation("1CP Conference Room 4350");
ical.addEvent(event);
}
assertWarnings(0, ical.validate());
assertExample(ical, "rfc5545-example2.ics");
} | #vulnerable code
@Test
public void example2() throws Throwable {
VTimezone usEasternTz;
ICalendar ical = new ICalendar();
ical.getProperties().clear();
ical.setProductId("-//RDU Software//NONSGML HandCal//EN");
ical.setVersion(Version.v2_0());
{
usEasternTz = new VTimezone(null);
usEasternTz.setTimezoneId("America/New_York");
{
StandardTime standard = new StandardTime();
standard.setDateStart(localFormatter.parse("19981025T020000")).setLocalTime(true);
standard.setTimezoneOffsetFrom(-4, 0);
standard.setTimezoneOffsetTo(-5, 0);
standard.addTimezoneName("EST");
usEasternTz.addStandardTime(standard);
}
{
DaylightSavingsTime daylight = new DaylightSavingsTime();
daylight.setDateStart(localFormatter.parse("19990404T020000")).setLocalTime(true);
daylight.setTimezoneOffsetFrom(-5, 0);
daylight.setTimezoneOffsetTo(-4, 0);
daylight.addTimezoneName("EDT");
usEasternTz.addDaylightSavingsTime(daylight);
}
ical.addTimezone(usEasternTz);
}
{
VEvent event = new VEvent();
event.setDateTimeStamp(utcFormatter.parse("19980309T231000"));
event.setUid("guid-1.example.com");
event.setOrganizer("[email protected]");
Attendee attendee = Attendee.email("[email protected]");
attendee.setRsvp(true);
attendee.setRole(Role.REQ_PARTICIPANT);
attendee.setCalendarUserType(CalendarUserType.GROUP);
event.addAttendee(attendee);
event.setDescription("Project XYZ Review Meeting");
event.addCategories("MEETING");
event.setClassification(Classification.public_());
event.setCreated(utcFormatter.parse("19980309T130000"));
event.setSummary("XYZ Project Review");
event.setDateStart(usEasternFormatter.parse("19980312T083000")).setTimezone(usEasternTz);
event.setDateEnd(usEasternFormatter.parse("19980312T093000")).setTimezone(usEasternTz);
event.setLocation("1CP Conference Room 4350");
ical.addEvent(event);
}
assertWarnings(0, ical.validate());
assertExample(ical, "rfc5545-example2.ics");
}
#location 13
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void write_example2() throws Throwable {
//see: RFC 6321 p.51
VTimezone usEasternTz;
ICalendar ical = new ICalendar();
ical.getProperties().clear();
ical.setProductId("-//Example Inc.//Example Client//EN");
ical.setVersion(Version.v2_0());
{
usEasternTz = new VTimezone(null);
usEasternTz.setLastModified(utcFormatter.parse("2004-01-10T03:28:45"));
usEasternTz.setTimezoneId("US/Eastern");
{
DaylightSavingsTime daylight = new DaylightSavingsTime();
daylight.setDateStart(localFormatter.parse("2000-04-04T02:00:00"));
RecurrenceRule rrule = new RecurrenceRule(Frequency.YEARLY);
rrule.addByDay(1, DayOfWeek.SUNDAY);
rrule.addByMonth(4);
daylight.setRecurrenceRule(rrule);
daylight.addTimezoneName("EDT");
daylight.setTimezoneOffsetFrom(-5, 0);
daylight.setTimezoneOffsetTo(-4, 0);
usEasternTz.addDaylightSavingsTime(daylight);
}
{
StandardTime standard = new StandardTime();
standard.setDateStart(localFormatter.parse("2000-10-26T02:00:00"));
RecurrenceRule rrule = new RecurrenceRule(Frequency.YEARLY);
rrule.addByDay(-1, DayOfWeek.SUNDAY);
rrule.addByMonth(10);
standard.setRecurrenceRule(rrule);
standard.addTimezoneName("EST");
standard.setTimezoneOffsetFrom(-4, 0);
standard.setTimezoneOffsetTo(-5, 0);
usEasternTz.addStandardTime(standard);
}
ical.addTimezone(usEasternTz);
}
{
VEvent event = new VEvent();
event.setDateTimeStamp(utcFormatter.parse("2006-02-06T00:11:21"));
event.setDateStart(usEasternFormatter.parse("2006-01-02T12:00:00")).setTimezone(usEasternTz);
event.setDuration(new Duration.Builder().hours(1).build());
RecurrenceRule rrule = new RecurrenceRule(Frequency.DAILY);
rrule.setCount(5);
event.setRecurrenceRule(rrule);
RecurrenceDates rdate = new RecurrenceDates(Arrays.asList(new Period(usEasternFormatter.parse("2006-01-02T15:00:00"), new Duration.Builder().hours(2).build())));
rdate.setTimezone(usEasternTz);
event.addRecurrenceDates(rdate);
event.setSummary("Event #2");
event.setDescription("We are having a meeting all this week at 12pm for one hour, with an additional meeting on the first day 2 hours long.\nPlease bring your own lunch for the 12 pm meetings.");
event.setUid("[email protected]");
ical.addEvent(event);
}
{
VEvent event = new VEvent();
event.setDateTimeStamp(utcFormatter.parse("2006-02-06T00:11:21"));
event.setDateStart(usEasternFormatter.parse("2006-01-04T14:00:00")).setTimezone(usEasternTz);
event.setDuration(new Duration.Builder().hours(1).build());
event.setRecurrenceId(usEasternFormatter.parse("2006-01-04T12:00:00")).setTimezone(usEasternTz);
event.setSummary("Event #2 bis");
event.setUid("[email protected]");
ical.addEvent(event);
}
assertWarnings(0, ical.validate());
assertExample(ical, "rfc6321-example2.xml");
} | #vulnerable code
@Test
public void write_example2() throws Throwable {
//see: RFC 6321 p.51
VTimezone usEasternTz;
ICalendar ical = new ICalendar();
ical.getProperties().clear();
ical.setProductId("-//Example Inc.//Example Client//EN");
ical.setVersion(Version.v2_0());
{
usEasternTz = new VTimezone(null);
usEasternTz.setLastModified(utcFormatter.parse("2004-01-10T03:28:45"));
usEasternTz.setTimezoneId("US/Eastern");
{
DaylightSavingsTime daylight = new DaylightSavingsTime();
daylight.setDateStart(localFormatter.parse("2000-04-04T02:00:00")).setLocalTime(true);
RecurrenceRule rrule = new RecurrenceRule(Frequency.YEARLY);
rrule.addByDay(1, DayOfWeek.SUNDAY);
rrule.addByMonth(4);
daylight.setRecurrenceRule(rrule);
daylight.addTimezoneName("EDT");
daylight.setTimezoneOffsetFrom(-5, 0);
daylight.setTimezoneOffsetTo(-4, 0);
usEasternTz.addDaylightSavingsTime(daylight);
}
{
StandardTime standard = new StandardTime();
standard.setDateStart(localFormatter.parse("2000-10-26T02:00:00")).setLocalTime(true);
RecurrenceRule rrule = new RecurrenceRule(Frequency.YEARLY);
rrule.addByDay(-1, DayOfWeek.SUNDAY);
rrule.addByMonth(10);
standard.setRecurrenceRule(rrule);
standard.addTimezoneName("EST");
standard.setTimezoneOffsetFrom(-4, 0);
standard.setTimezoneOffsetTo(-5, 0);
usEasternTz.addStandardTime(standard);
}
ical.addTimezone(usEasternTz);
}
{
VEvent event = new VEvent();
event.setDateTimeStamp(utcFormatter.parse("2006-02-06T00:11:21"));
event.setDateStart(usEasternFormatter.parse("2006-01-02T12:00:00")).setTimezone(usEasternTz);
event.setDuration(new Duration.Builder().hours(1).build());
RecurrenceRule rrule = new RecurrenceRule(Frequency.DAILY);
rrule.setCount(5);
event.setRecurrenceRule(rrule);
RecurrenceDates rdate = new RecurrenceDates(Arrays.asList(new Period(usEasternFormatter.parse("2006-01-02T15:00:00"), new Duration.Builder().hours(2).build())));
rdate.setTimezone(usEasternTz);
event.addRecurrenceDates(rdate);
event.setSummary("Event #2");
event.setDescription("We are having a meeting all this week at 12pm for one hour, with an additional meeting on the first day 2 hours long.\nPlease bring your own lunch for the 12 pm meetings.");
event.setUid("[email protected]");
ical.addEvent(event);
}
{
VEvent event = new VEvent();
event.setDateTimeStamp(utcFormatter.parse("2006-02-06T00:11:21"));
event.setDateStart(usEasternFormatter.parse("2006-01-04T14:00:00")).setTimezone(usEasternTz);
event.setDuration(new Duration.Builder().hours(1).build());
event.setRecurrenceId(usEasternFormatter.parse("2006-01-04T12:00:00")).setTimezone(usEasternTz);
event.setSummary("Event #2 bis");
event.setUid("[email protected]");
ical.addEvent(event);
}
assertWarnings(0, ical.validate());
assertExample(ical, "rfc6321-example2.xml");
}
#location 15
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void caret_encoding() throws Exception {
ICalendar ical = new ICalendar();
ical.getProductId().addParameter("X-TEST", "\"test\"");
StringWriter sw = new StringWriter();
ICalWriter writer = new ICalWriter(sw);
writer.setCaretEncodingEnabled(true);
writer.write(ical);
writer.close();
//@formatter:off
String expected =
"BEGIN:VCALENDAR\r\n" +
"VERSION:2\\.0\r\n" +
"PRODID;X-TEST=\\^'test\\^':.*?\r\n" +
"END:VCALENDAR\r\n";
//@formatter:on
String actual = sw.toString();
assertRegex(expected, actual);
} | #vulnerable code
@Test
public void caret_encoding() throws Exception {
ICalendar ical = new ICalendar();
ical.getProductId().addParameter("X-TEST", "\"test\"");
StringWriter sw = new StringWriter();
ICalWriter writer = new ICalWriter(sw);
writer.setCaretEncodingEnabled(true);
writer.write(ical);
writer.close();
//@formatter:off
String expected =
"BEGIN:VCALENDAR\r\n" +
"VERSION:2\\.0\r\n" +
"PRODID;X-TEST=\\^'test\\^':.*?\r\n" +
"END:VCALENDAR\r\n";
//@formatter:on
String actual = sw.toString();
assertRegex(expected, actual);
assertWarnings(0, writer.getWarnings());
}
#location 23
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void experimental_component_marshaller() throws Exception {
ICalendar ical = new ICalendar();
ical.addComponent(new Party());
StringWriter sw = new StringWriter();
ICalWriter writer = new ICalWriter(sw);
writer.registerMarshaller(new PartyMarshaller());
writer.write(ical);
writer.close();
//@formatter:off
String expected =
"BEGIN:VCALENDAR\r\n" +
"VERSION:2\\.0\r\n" +
"PRODID:.*?\r\n" +
"BEGIN:X-VPARTY\r\n" +
"END:X-VPARTY\r\n" +
"END:VCALENDAR\r\n";
//@formatter:on
String actual = sw.toString();
assertRegex(expected, actual);
} | #vulnerable code
@Test
public void experimental_component_marshaller() throws Exception {
ICalendar ical = new ICalendar();
ical.addComponent(new Party());
StringWriter sw = new StringWriter();
ICalWriter writer = new ICalWriter(sw);
writer.registerMarshaller(new PartyMarshaller());
writer.write(ical);
writer.close();
//@formatter:off
String expected =
"BEGIN:VCALENDAR\r\n" +
"VERSION:2\\.0\r\n" +
"PRODID:.*?\r\n" +
"BEGIN:X-VPARTY\r\n" +
"END:X-VPARTY\r\n" +
"END:VCALENDAR\r\n";
//@formatter:on
String actual = sw.toString();
assertRegex(expected, actual);
assertWarnings(0, writer.getWarnings());
}
#location 25
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void writeXml_data() {
Attachment prop = new Attachment("image/png", "data".getBytes());
assertWriteXml("<binary>" + Base64.encodeBase64String("data".getBytes()) + "</binary>", prop, marshaller);
} | #vulnerable code
@Test
public void writeXml_data() {
Attachment prop = new Attachment("image/png", "data".getBytes());
Document actual = xcalProperty(marshaller);
marshaller.writeXml(prop, XmlUtils.getRootElement(actual));
Document expected = xcalProperty(marshaller, "<binary>" + Base64.encodeBase64String("data".getBytes()) + "</binary>");
assertXMLEqual(expected, actual);
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void parseXml() {
Result<TextPropertyImpl> result = parseXCalProperty("<text>text</text>", marshaller);
TextPropertyImpl prop = result.getValue();
assertEquals("text", prop.getValue());
assertWarnings(0, result.getWarnings());
} | #vulnerable code
@Test
public void parseXml() {
ICalParameters params = new ICalParameters();
Element element = xcalPropertyElement(marshaller, "<text>text</text>");
Result<TextPropertyImpl> result = marshaller.parseXml(element, params);
TextPropertyImpl prop = result.getValue();
assertEquals("text", prop.getValue());
assertWarnings(0, result.getWarnings());
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void createInvertedIndex() {
if (currentIndex == null)
{
currentIndex = Index.createIndex(path,prefix);
if (currentIndex == null)
{
logger.error("No index at ("+path+","+prefix+") to build an inverted index for ");
return;
}
}
long beginTimestamp = System.currentTimeMillis();
if (currentIndex.getCollectionStatistics().getNumberOfUniqueTerms() == 0)
{
logger.error("Index has no terms. Inverted index creation aborted.");
return;
}
if (currentIndex.getCollectionStatistics().getNumberOfDocuments() == 0)
{
logger.error("Index has no documents. Inverted index creation aborted.");
return;
}
logger.info("Started building the block inverted index...");
invertedIndexBuilder = new BlockInvertedIndexBuilder(currentIndex, "inverted", compressionInvertedConfig);
invertedIndexBuilder.createInvertedIndex();
this.finishedInvertedIndexBuild();
try{
currentIndex.flush();
} catch (IOException ioe) {
logger.error("Cannot flush index: ", ioe);
}
long endTimestamp = System.currentTimeMillis();
logger.info("Finished building the block inverted index...");
long seconds = (endTimestamp - beginTimestamp) / 1000;
logger.info("Time elapsed for inverted file: " + seconds);
} | #vulnerable code
public void createInvertedIndex() {
if (currentIndex == null)
{
currentIndex = Index.createIndex(path,prefix);
if (currentIndex == null)
{
logger.error("No index at ("+path+","+prefix+") to build an inverted index for ");
}
}
long beginTimestamp = System.currentTimeMillis();
if (currentIndex.getCollectionStatistics().getNumberOfUniqueTerms() == 0)
{
logger.error("Index has no terms. Inverted index creation aborted.");
return;
}
if (currentIndex.getCollectionStatistics().getNumberOfDocuments() == 0)
{
logger.error("Index has no documents. Inverted index creation aborted.");
return;
}
logger.info("Started building the block inverted index...");
invertedIndexBuilder = new BlockInvertedIndexBuilder(currentIndex, "inverted", compressionInvertedConfig);
invertedIndexBuilder.createInvertedIndex();
this.finishedInvertedIndexBuild();
try{
currentIndex.flush();
} catch (IOException ioe) {
logger.error("Cannot flush index: ", ioe);
}
long endTimestamp = System.currentTimeMillis();
logger.info("Finished building the block inverted index...");
long seconds = (endTimestamp - beginTimestamp) / 1000;
logger.info("Time elapsed for inverted file: " + seconds);
}
#location 12
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
protected void doEvaluation(int expectedQueryCount, String qrels, float expectedMAP) throws Exception
{
// Writer w = Files.writeFileWriter(ApplicationSetup.TREC_QRELS);
// System.err.println("Writing qrel files files to " + ApplicationSetup.TREC_QRELS);
// w.write(qrels + "\n");
// w.close();
TrecTerrier.main(new String[]{"-e", "-Dtrec.qrels=" + qrels});
float MAP = -1.0f;
int queryCount = 0;
File[] fs = new File(ApplicationSetup.TREC_RESULTS).listFiles();
assertNotNull(fs);
for (File f : fs)
{
if (f.getName().endsWith(".eval"))
{
BufferedReader br = Files.openFileReader(f);
String line = null;
while((line = br.readLine()) != null )
{
//System.out.println(line);
if (line.startsWith("Average Precision:"))
{
MAP = Float.parseFloat(line.split(":")[1].trim());
}
else if (line.startsWith("Number of queries ="))
{
queryCount = Integer.parseInt(line.split("\\s+=\\s+")[1].trim());
}
}
br.close();
break;
}
}
assertEquals("Query count was "+ queryCount + " instead of "+ expectedQueryCount, expectedQueryCount, queryCount);
assertEquals("MAP was "+MAP + " instead of "+expectedMAP, expectedMAP, MAP, 0.0d);
//System.err.println("Tidying results folder:");
//System.err.println("ls "+ ApplicationSetup.TREC_RESULTS);
//System.err.println(Arrays.deepToString(new File(ApplicationSetup.TREC_RESULTS).listFiles()));
//delete all runs and evaluations
fs = new File(ApplicationSetup.TREC_RESULTS).listFiles();
assertNotNull(fs);
for (File f :fs)
{
//System.err.println("Checking file for possible deletion: "+f);
if (f.getName().endsWith(".res") || f.getName().endsWith(".eval"))
{
System.err.println("Removing finished file "+f);
if (! f.delete())
System.err.println("Could not remove finished file "+f);
}
}
} | #vulnerable code
protected void doEvaluation(int expectedQueryCount, String qrels, float expectedMAP) throws Exception
{
// Writer w = Files.writeFileWriter(ApplicationSetup.TREC_QRELS);
// System.err.println("Writing qrel files files to " + ApplicationSetup.TREC_QRELS);
// w.write(qrels + "\n");
// w.close();
TrecTerrier.main(new String[]{"-e", "-Dtrec.qrels=" + qrels});
float MAP = -1.0f;
int queryCount = 0;
for (File f : new File(ApplicationSetup.TREC_RESULTS).listFiles())
{
if (f.getName().endsWith(".eval"))
{
BufferedReader br = Files.openFileReader(f);
String line = null;
while((line = br.readLine()) != null )
{
//System.out.println(line);
if (line.startsWith("Average Precision:"))
{
MAP = Float.parseFloat(line.split(":")[1].trim());
}
else if (line.startsWith("Number of queries ="))
{
queryCount = Integer.parseInt(line.split("\\s+=\\s+")[1].trim());
}
}
br.close();
break;
}
}
assertEquals("Query count was "+ queryCount + " instead of "+ expectedQueryCount, expectedQueryCount, queryCount);
assertEquals("MAP was "+MAP + " instead of "+expectedMAP, expectedMAP, MAP, 0.0d);
//System.err.println("Tidying results folder:");
//System.err.println("ls "+ ApplicationSetup.TREC_RESULTS);
//System.err.println(Arrays.deepToString(new File(ApplicationSetup.TREC_RESULTS).listFiles()));
//delete all runs and evaluations
for (File f : new File(ApplicationSetup.TREC_RESULTS).listFiles())
{
//System.err.println("Checking file for possible deletion: "+f);
if (f.getName().endsWith(".res") || f.getName().endsWith(".eval"))
{
System.err.println("Removing finished file "+f);
if (! f.delete())
System.err.println("Could not remove finished file "+f);
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void createInvertedIndex() {
if (currentIndex == null)
{
currentIndex = Index.createIndex(path,prefix);
if (currentIndex == null)
{
logger.error("No index at ("+path+","+prefix+") to build an inverted index for ");
return;
}
}
final long beginTimestamp = System.currentTimeMillis();
logger.info("Started building the inverted index...");
if (currentIndex.getCollectionStatistics().getNumberOfUniqueTerms() == 0)
{
logger.error("Index has no terms. Inverted index creation aborted.");
return;
}
if (currentIndex.getCollectionStatistics().getNumberOfDocuments() == 0)
{
logger.error("Index has no documents. Inverted index creation aborted.");
return;
}
//generate the inverted index
logger.info("Started building the inverted index...");
invertedIndexBuilder = new InvertedIndexBuilder(currentIndex, "inverted", compressionInvertedConfig);
invertedIndexBuilder.createInvertedIndex();
finishedInvertedIndexBuild();
long endTimestamp = System.currentTimeMillis();
logger.info("Finished building the inverted index...");
long seconds = (endTimestamp - beginTimestamp) / 1000;
//long minutes = seconds / 60;
logger.info("Time elapsed for inverted file: " + seconds);
try{
currentIndex.flush();
} catch (IOException ioe) {
logger.warn("Problem flushin index", ioe);
}
} | #vulnerable code
public void createInvertedIndex() {
if (currentIndex == null)
{
currentIndex = Index.createIndex(path,prefix);
if (currentIndex == null)
{
logger.error("No index at ("+path+","+prefix+") to build an inverted index for ");
}
}
final long beginTimestamp = System.currentTimeMillis();
logger.info("Started building the inverted index...");
if (currentIndex.getCollectionStatistics().getNumberOfUniqueTerms() == 0)
{
logger.error("Index has no terms. Inverted index creation aborted.");
return;
}
if (currentIndex.getCollectionStatistics().getNumberOfDocuments() == 0)
{
logger.error("Index has no documents. Inverted index creation aborted.");
return;
}
//generate the inverted index
logger.info("Started building the inverted index...");
invertedIndexBuilder = new InvertedIndexBuilder(currentIndex, "inverted", compressionInvertedConfig);
invertedIndexBuilder.createInvertedIndex();
finishedInvertedIndexBuild();
long endTimestamp = System.currentTimeMillis();
logger.info("Finished building the inverted index...");
long seconds = (endTimestamp - beginTimestamp) / 1000;
//long minutes = seconds / 60;
logger.info("Time elapsed for inverted file: " + seconds);
try{
currentIndex.flush();
} catch (IOException ioe) {
logger.warn("Problem flushin index", ioe);
}
}
#location 13
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void write(String filename) throws IOException {
FileSink output = FileSinkFactory.sinkFor(filename);
if(output != null) {
write(output, filename);
} else {
throw new IOException("No sink writer for "+filename);
}
} | #vulnerable code
public void write(String filename) throws IOException {
FileSink output = FileSinkFactory.sinkFor(filename);
write(output, filename);
}
#location 3
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void sendAttributeChangedEvent(String eltId, ElementType eltType, String attribute,
AttributeChangeEvent event, Object oldValue, Object newValue) {
//
// Attributes with name beginnig with a dot are hidden.
//
if (passYourWay || attribute.charAt(0) == '.')
return;
sendAttributeChangedEvent(sourceId, newEvent(), eltId, eltType, attribute, event, oldValue, newValue);
} | #vulnerable code
public void sendAttributeChangedEvent(String eltId, ElementType eltType, String attribute,
AttributeChangeEvent event, Object oldValue, Object newValue) {
//
// Attributes with name beginnig with a dot are hidden.
//
if (passYourWay || attribute.charAt(0) == '.')
return;
attributeLock.lock(); // Fix issue #293
try {
sendAttributeChangedEvent(sourceId, newEvent(), eltId, eltType, attribute, event, oldValue, newValue);
} finally {
attributeLock.unlock();
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void print(EventType type, Args args) {
if (!enable.get(type))
return;
String out = formats.get(type);
for (String k : args.keySet()) {
Object o = args.get(k);
out = out.replace(String.format("%%%s%%", k), o == null ? "null"
: o.toString());
}
this.out.print(out);
this.out.printf("\n");
if (autoflush)
this.out.flush();
argsPnP(args);
} | #vulnerable code
private void print(EventType type, Args args) {
if (!enable.get(type))
return;
String out = formats.get(type);
for (String k : args.keySet()) {
Object o = args.get(k);
out = out.replace(String.format("%%%s%%", k), o == null ? "null"
: o.toString());
}
this.out.printf(out);
this.out.printf("\n");
if (autoflush)
this.out.flush();
argsPnP(args);
}
#location 13
#vulnerability type CHECKERS_PRINTF_ARGS |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String... args) throws IOException {
HashMap<Option, String> options = new HashMap<Option, String>();
LinkedList<String> others = new LinkedList<String>();
for (Option option : Option.values())
if (option.defaultValue != null)
options.put(option, option.defaultValue);
if (args != null && args.length > 0) {
Pattern valueGetter = Pattern.compile("^--\\w[\\w-]*\\w?(?:=(?:\"([^\"]*)\"|([^\\s]*)))$");
for (int i = 0; i < args.length; i++) {
if (args[i].matches("^--\\w[\\w-]*\\w?(=(\"[^\"]*\"|[^\\s]*))?$")) {
boolean found = false;
for (Option option : Option.values()) {
if (args[i].startsWith("--" + option.fullopts + "=")) {
Matcher m = valueGetter.matcher(args[i]);
if (m.matches()) {
options.put(option, m.group(1) == null ? m.group(2) : m.group(1));
}
found = true;
break;
}
}
if (!found) {
LOGGER.severe(
String.format("unknown option: %s%n", args[i].substring(0, args[i].indexOf('='))));
System.exit(1);
}
} else if (args[i].matches("^-\\w$")) {
boolean found = false;
for (Option option : Option.values()) {
if (args[i].equals("-" + option.shortopts)) {
options.put(option, args[++i]);
break;
}
}
if (!found) {
LOGGER.severe(String.format("unknown option: %s%n", args[i]));
System.exit(1);
}
} else {
others.addLast(args[i]);
}
}
} else {
usage();
System.exit(0);
}
LinkedList<String> errors = new LinkedList<String>();
if (others.size() == 0) {
errors.add("dgs file name missing.");
}
String imagePrefix;
OutputType outputType = null;
OutputPolicy outputPolicy = null;
Resolution resolution = null;
Quality quality = null;
String logo;
String stylesheet;
imagePrefix = options.get(Option.IMAGE_PREFIX);
try {
outputType = OutputType.valueOf(options.get(Option.IMAGE_TYPE));
} catch (IllegalArgumentException e) {
errors.add("bad image type: " + options.get(Option.IMAGE_TYPE));
}
try {
outputPolicy = OutputPolicy.valueOf(options.get(Option.OUTPUT_POLICY));
} catch (IllegalArgumentException e) {
errors.add("bad output policy: " + options.get(Option.OUTPUT_POLICY));
}
try {
quality = Quality.valueOf(options.get(Option.QUALITY));
} catch (IllegalArgumentException e) {
errors.add("bad quality: " + options.get(Option.QUALITY));
}
logo = options.get(Option.LOGO);
stylesheet = options.get(Option.STYLESHEET);
try {
resolution = Resolutions.valueOf(options.get(Option.IMAGE_RESOLUTION));
} catch (IllegalArgumentException e) {
Pattern p = Pattern.compile("^\\s*(\\d+)\\s*x\\s*(\\d+)\\s*$");
Matcher m = p.matcher(options.get(Option.IMAGE_RESOLUTION));
if (m.matches()) {
resolution = new CustomResolution(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)));
} else {
errors.add("bad resolution: " + options.get(Option.IMAGE_RESOLUTION));
}
}
if (stylesheet != null && stylesheet.length() < 1024) {
File test = new File(stylesheet);
if (test.exists()) {
FileReader in = new FileReader(test);
char[] buffer = new char[128];
String content = "";
while (in.ready()) {
int c = in.read(buffer, 0, 128);
content += new String(buffer, 0, c);
}
stylesheet = content;
in.close();
}
}
{
File test = new File(others.peek());
if (!test.exists())
errors.add(String.format("file \"%s\" does not exist", others.peek()));
}
if (errors.size() > 0) {
LOGGER.info(String.format("error:%n"));
for (String error : errors)
LOGGER.info(String.format("- %s%n", error));
System.exit(1);
}
FileSourceDGS dgs = new FileSourceDGS();
FileSinkImages fsi = FileSinkImages.createDefault();
fsi.setOutputPolicy(outputPolicy);
fsi.setResolution(resolution);
fsi.setOutputType(outputType);
dgs.addSink(fsi);
if (logo != null)
fsi.addFilter(new AddLogoFilter(logo, 0, 0));
fsi.setQuality(quality);
if (stylesheet != null)
fsi.setStyleSheet(stylesheet);
boolean next = true;
dgs.begin(others.get(0));
while (next)
next = dgs.nextStep();
dgs.end();
} | #vulnerable code
public static void main(String... args) throws IOException {
HashMap<Option, String> options = new HashMap<Option, String>();
LinkedList<String> others = new LinkedList<String>();
for (Option option : Option.values())
if (option.defaultValue != null)
options.put(option, option.defaultValue);
if (args != null && args.length > 0) {
Pattern valueGetter = Pattern.compile("^--\\w[\\w-]*\\w?(?:=(?:\"([^\"]*)\"|([^\\s]*)))$");
for (int i = 0; i < args.length; i++) {
if (args[i].matches("^--\\w[\\w-]*\\w?(=(\"[^\"]*\"|[^\\s]*))?$")) {
boolean found = false;
for (Option option : Option.values()) {
if (args[i].startsWith("--" + option.fullopts + "=")) {
Matcher m = valueGetter.matcher(args[i]);
if (m.matches()) {
options.put(option, m.group(1) == null ? m.group(2) : m.group(1));
}
found = true;
break;
}
}
if (!found) {
LOGGER.severe(
String.format("unknown option: %s%n", args[i].substring(0, args[i].indexOf('='))));
System.exit(1);
}
} else if (args[i].matches("^-\\w$")) {
boolean found = false;
for (Option option : Option.values()) {
if (args[i].equals("-" + option.shortopts)) {
options.put(option, args[++i]);
break;
}
}
if (!found) {
LOGGER.severe(String.format("unknown option: %s%n", args[i]));
System.exit(1);
}
} else {
others.addLast(args[i]);
}
}
} else {
usage();
System.exit(0);
}
LinkedList<String> errors = new LinkedList<String>();
if (others.size() == 0) {
errors.add("dgs file name missing.");
}
String imagePrefix;
OutputType outputType = null;
OutputPolicy outputPolicy = null;
Resolution resolution = null;
Quality quality = null;
String logo;
String stylesheet;
imagePrefix = options.get(Option.IMAGE_PREFIX);
try {
outputType = OutputType.valueOf(options.get(Option.IMAGE_TYPE));
} catch (IllegalArgumentException e) {
errors.add("bad image type: " + options.get(Option.IMAGE_TYPE));
}
try {
outputPolicy = OutputPolicy.valueOf(options.get(Option.OUTPUT_POLICY));
} catch (IllegalArgumentException e) {
errors.add("bad output policy: " + options.get(Option.OUTPUT_POLICY));
}
try {
quality = Quality.valueOf(options.get(Option.QUALITY));
} catch (IllegalArgumentException e) {
errors.add("bad quality: " + options.get(Option.QUALITY));
}
logo = options.get(Option.LOGO);
stylesheet = options.get(Option.STYLESHEET);
try {
resolution = Resolutions.valueOf(options.get(Option.IMAGE_RESOLUTION));
} catch (IllegalArgumentException e) {
Pattern p = Pattern.compile("^\\s*(\\d+)\\s*x\\s*(\\d+)\\s*$");
Matcher m = p.matcher(options.get(Option.IMAGE_RESOLUTION));
if (m.matches()) {
resolution = new CustomResolution(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)));
} else {
errors.add("bad resolution: " + options.get(Option.IMAGE_RESOLUTION));
}
}
if (stylesheet != null && stylesheet.length() < 1024) {
File test = new File(stylesheet);
if (test.exists()) {
FileReader in = new FileReader(test);
char[] buffer = new char[128];
String content = "";
while (in.ready()) {
int c = in.read(buffer, 0, 128);
content += new String(buffer, 0, c);
}
stylesheet = content;
in.close();
}
}
{
File test = new File(others.peek());
if (!test.exists())
errors.add(String.format("file \"%s\" does not exist", others.peek()));
}
if (errors.size() > 0) {
LOGGER.info(String.format("error:%n"));
for (String error : errors)
LOGGER.info(String.format("- %s%n", error));
System.exit(1);
}
FileSourceDGS dgs = new FileSourceDGS();
FileSinkImages fsi = new FileSinkImages(imagePrefix, outputType, resolution, outputPolicy);
dgs.addSink(fsi);
if (logo != null)
fsi.addFilter(new AddLogoFilter(logo, 0, 0));
fsi.setQuality(quality);
if (stylesheet != null)
fsi.setStyleSheet(stylesheet);
boolean next = true;
dgs.begin(others.get(0));
while (next)
next = dgs.nextStep();
dgs.end();
}
#location 142
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@SuppressWarnings("all")
public <T extends Edge> T getEdgeToward(String id) {
List<? extends Edge> edges = mygraph.connectivity.get(this);
for (Edge edge : edges) {
if (edge.getOpposite(this).getId().equals(id))
return (T) edge;
}
return null;
} | #vulnerable code
@SuppressWarnings("all")
public <T extends Edge> T getEdgeToward(String id) {
ArrayList<? extends Edge> edges = mygraph.connectivity.get(this);
for (Edge edge : edges) {
if (edge.getOpposite(this).getId().equals(id))
return (T) edge;
}
return null;
}
#location 5
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void savePropertyGroup(String fileName, String group, InputStream inputstream) throws IOException {
List<PropertyItemVO> items = parseInputFile(inputstream);
if (!items.isEmpty()) {
String groupFullPath = ZKPaths.makePath(ZKPaths.makePath(nodeAuth.getAuthedNode(), versionMB.getSelectedVersion()), group);
String commentFullPath = ZKPaths.makePath(ZKPaths.makePath(nodeAuth.getAuthedNode(), versionMB.getSelectedVersion() + "$"), group);
boolean created = nodeService.createProperty(groupFullPath, null);
if (created) {
for (PropertyItemVO item : items) {
nodeService.createProperty(ZKPaths.makePath(groupFullPath, item.getName()), item.getValue());
nodeService.createProperty(ZKPaths.makePath(commentFullPath, item.getName()), item.getComment());
}
refreshGroup();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Succesful", fileName + " is uploaded."));
} else {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Create group with file error.", fileName));
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "File is empty.", fileName));
}
} | #vulnerable code
private void savePropertyGroup(String fileName, String group, InputStream inputstream) throws IOException {
Reader reader = new InputStreamReader(inputstream, Charsets.UTF_8);
Properties properties = new Properties();
properties.load(reader);
if (!properties.isEmpty()) {
String authedNode = ZKPaths.makePath(nodeAuth.getAuthedNode(), versionMB.getSelectedVersion());
String groupPath = ZKPaths.makePath(authedNode, group);
boolean created = nodeService.createProperty(groupPath, null);
if (created) {
Map<String, String> map = Maps.fromProperties(properties);
for (Entry<String, String> entry : map.entrySet()) {
nodeService.createProperty(ZKPaths.makePath(groupPath, entry.getKey()), entry.getValue());
}
refreshGroup();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Succesful", fileName + " is uploaded."));
} else {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Create group with file error.", fileName));
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "File is empty.", fileName));
}
}
#location 4
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static Map<String, String> loadLocalProperties(String rootNode, String group) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(rootNode) && !Strings.isNullOrEmpty(group), "rootNode or group cannot be empty.");
Map<String, String> properties = null;
final String localOverrideFile = findLocalOverrideFile();
InputStream in = null;
try {
in = LocalOverrideFileLoader.class.getClassLoader().getResourceAsStream(localOverrideFile);
if (in != null) {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.parse(in);
final Element factoriesNode = Preconditions.checkNotNull(doc.getDocumentElement(), "Root xml node node-factories not exists.");
Node factoryNode = findChild(factoriesNode, "node-factory", "root", rootNode);
if (factoryNode != null) {
Node nodeGroup = findChild(factoryNode, "group", "id", group);
if (nodeGroup != null) {
NodeList childNodes = nodeGroup.getChildNodes();
int nodeCount = childNodes.getLength();
if (nodeCount > 0) {
properties = Maps.newHashMap();
for (int i = 0; i < nodeCount; i++) {
Node item = childNodes.item(i);
if (item.hasAttributes()) {
NamedNodeMap attributes = item.getAttributes();
Node keyAttr = attributes.getNamedItem("key");
if (keyAttr != null) {
String propKey = keyAttr.getNodeValue();
String propVal = item.getFirstChild().getNodeValue();
if (propKey != null && propVal != null) {
properties.put(propKey, propVal);
}
}
}
}
}
}
}
}
} catch (ParserConfigurationException e) {
throw Throwables.propagate(e);
} catch (SAXException e) {
throw Throwables.propagate(e);
} catch (IOException e) {
throw Throwables.propagate(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// IGNORE
}
}
}
return properties;
} | #vulnerable code
public static Map<String, String> loadLocalProperties(String rootNode, String group) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(rootNode) && !Strings.isNullOrEmpty(group), "rootNode or group cannot be empty.");
Map<String, String> properties = null;
final String localOverrideFile = findLocalOverrideFile();
InputStream in = null;
try {
in = LocalOverrideFileLoader.class.getClassLoader().getResourceAsStream(localOverrideFile);
if (in != null) {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.parse(in);
final Element factoriesNode = Preconditions.checkNotNull(doc.getDocumentElement(), "Root xml node node-factories not exists.");
Node factoryNode = findChild(factoriesNode, "node-factory", "root", rootNode);
if (factoriesNode != null) {
Node nodeGroup = findChild(factoryNode, "group", "id", group);
if (nodeGroup != null) {
NodeList childNodes = nodeGroup.getChildNodes();
int nodeCount = childNodes.getLength();
if (nodeCount > 0) {
properties = Maps.newHashMap();
for (int i = 0; i < nodeCount; i++) {
Node item = childNodes.item(i);
if (item.hasAttributes()) {
NamedNodeMap attributes = item.getAttributes();
Node keyAttr = attributes.getNamedItem("key");
if (keyAttr != null) {
String propKey = keyAttr.getNodeValue();
String propVal = item.getFirstChild().getNodeValue();
if (propKey != null && propVal != null) {
properties.put(propKey, propVal);
}
}
}
}
}
}
}
}
} catch (ParserConfigurationException e) {
throw Throwables.propagate(e);
} catch (SAXException e) {
throw Throwables.propagate(e);
} catch (IOException e) {
throw Throwables.propagate(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// IGNORE
}
}
}
return properties;
}
#location 18
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String[] args) {
String rootNode = "/projectx/modulex";
ZookeeperConfigProfile profile = new ZookeeperConfigProfile("zk.host", rootNode, true);
ZookeeperConfigGroup dbConfigs = new ZookeeperConfigGroup(null, profile, "db");
dbConfigs.setConfigLocalCache(new ConfigLocalCache("/your/local/config/folder", rootNode));
} | #vulnerable code
public static void main(String[] args) {
ZookeeperConfigProfile profile = new ZookeeperConfigProfile("zk.host", "/projectx/modulex", true);
profile.setLocalCacheFolder("/your/local/config/folder");
ConfigGroup dbConfigs = new ZookeeperConfigGroup(null, profile, "db");
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private String normalizePem(String data) {
PEMKeyPair pemKeyPair = null;
try (PEMParser pemParser = new PEMParser(new StringReader(data))) {
pemKeyPair = (PEMKeyPair) pemParser.readObject();
PrivateKeyInfo privateKeyInfo = pemKeyPair.getPrivateKeyInfo();
StringWriter textWriter = new StringWriter();
try (PemWriter pemWriter = new PemWriter(textWriter)) {
PemObjectGenerator pemObjectGenerator = new MiscPEMGenerator(
privateKeyInfo);
pemWriter.writeObject(pemObjectGenerator);
pemWriter.flush();
return textWriter.toString();
}
}
catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
} | #vulnerable code
private String normalizePem(String data) {
PEMParser pemParser = new PEMParser(new StringReader(data));
PEMKeyPair pemKeyPair = null;
try {
pemKeyPair = (PEMKeyPair) pemParser.readObject();
PrivateKeyInfo privateKeyInfo = pemKeyPair.getPrivateKeyInfo();
StringWriter textWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(textWriter);
PemObjectGenerator pemObjectGenerator = new MiscPEMGenerator(privateKeyInfo);
pemWriter.writeObject(pemObjectGenerator);
pemWriter.flush();
return textWriter.toString();
}
catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
#location 13
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public void close() {
executorService.shutdown();
} | #vulnerable code
@Override
public void close() {
if (executorService != null) {
synchronized (InetUtils.class) {
if (executorService != null) {
executorService.shutdown();
executorService = null;
}
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public HostInfo convertAddress(final InetAddress address) {
HostInfo hostInfo = new HostInfo();
Future<String> result = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return address.getHostName();
}
});
String hostname;
try {
hostname = result.get(this.properties.getTimeoutSeconds(), TimeUnit.SECONDS);
}
catch (Exception e) {
log.info("Cannot determine local hostname");
hostname = "localhost";
}
hostInfo.setHostname(hostname);
hostInfo.setIpAddress(address.getHostAddress());
return hostInfo;
} | #vulnerable code
public HostInfo convertAddress(final InetAddress address) {
HostInfo hostInfo = new HostInfo();
Future<String> result = getExecutor().submit(new Callable<String>() {
@Override
public String call() throws Exception {
return address.getHostName();
}
});
String hostname;
try {
hostname = result.get(this.properties.getTimeoutSeconds(), TimeUnit.SECONDS);
}
catch (Exception e) {
log.info("Cannot determine local hostname");
hostname = "localhost";
}
hostInfo.setHostname(hostname);
hostInfo.setIpAddress(address.getHostAddress());
return hostInfo;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void free()
{
logger.fine("Free ICE agent");
shutdown = true;
//stop sending keep alives (STUN Binding Indications).
if (stunKeepAliveThread != null)
stunKeepAliveThread.interrupt();
// cancel termination timer in case agent is freed
// before termination timer is triggered
synchronized (terminationFutureSyncRoot)
{
if (terminationFuture != null)
{
terminationFuture.cancel(true);
terminationFuture = null;
}
}
//stop responding to STUN Binding Requests.
connCheckServer.stop();
/*
* Set the IceProcessingState#TERMINATED state on this Agent unless it
* is in a termination state already.
*/
IceProcessingState state = getState();
if (!IceProcessingState.FAILED.equals(state)
&& !IceProcessingState.TERMINATED.equals(state))
{
terminate(IceProcessingState.TERMINATED);
}
// Free its IceMediaStreams, Components and Candidates.
boolean interrupted = false;
logger.fine("remove streams");
for (IceMediaStream stream : getStreams())
{
try
{
removeStream(stream);
logger.fine("remove stream " + stream.getName());
}
catch (Throwable t)
{
logger.fine(
"remove stream " + stream.getName() + " failed: " + t);
if (t instanceof InterruptedException)
interrupted = true;
else if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
}
if (interrupted)
Thread.currentThread().interrupt();
getStunStack().shutDown();
logger.fine("ICE agent freed");
} | #vulnerable code
public void free()
{
logger.fine("Free ICE agent");
shutdown = true;
//stop sending keep alives (STUN Binding Indications).
if (stunKeepAliveThread != null)
stunKeepAliveThread.interrupt();
//stop responding to STUN Binding Requests.
connCheckServer.stop();
/*
* Set the IceProcessingState#TERMINATED state on this Agent unless it
* is in a termination state already.
*/
IceProcessingState state = getState();
if (!IceProcessingState.FAILED.equals(state)
&& !IceProcessingState.TERMINATED.equals(state))
{
terminate(IceProcessingState.TERMINATED);
}
// Free its IceMediaStreams, Components and Candidates.
boolean interrupted = false;
logger.fine("remove streams");
for (IceMediaStream stream : getStreams())
{
try
{
removeStream(stream);
logger.fine("remove stream " + stream.getName());
}
catch (Throwable t)
{
logger.fine(
"remove stream " + stream.getName() + " failed: " + t);
if (t instanceof InterruptedException)
interrupted = true;
else if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
}
if (interrupted)
Thread.currentThread().interrupt();
getStunStack().shutDown();
logger.fine("ICE agent freed");
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void validateRequestAttributes(StunMessageEvent evt)
throws IllegalArgumentException, StunException, IOException
{
Message request = evt.getMessage();
//assert valid username
UsernameAttribute unameAttr = (UsernameAttribute)request
.getAttribute(Attribute.USERNAME);
String username = null;
if (unameAttr != null)
{
username = LongTermCredential.toString(unameAttr.getUsername());
if (!validateUsername(username))
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNAUTHORIZED,
"unknown user " + username);
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),
evt.getRemoteAddress());
throw new IllegalArgumentException(
"Non-recognized username: " + username);
}
}
//assert Message Integrity
MessageIntegrityAttribute msgIntAttr
= (MessageIntegrityAttribute)
request.getAttribute(Attribute.MESSAGE_INTEGRITY);
if (msgIntAttr != null)
{
//we should complain if we have msg integrity and no username.
if (unameAttr == null)
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.BAD_REQUEST,
"missing username");
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),
evt.getRemoteAddress());
throw new IllegalArgumentException(
"Missing USERNAME in the presence of MESSAGE-INTEGRITY: ");
}
if (!validateMessageIntegrity(
msgIntAttr,
username,
true,
evt.getRawMessage()))
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNAUTHORIZED,
"Wrong MESSAGE-INTEGRITY value");
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),
evt.getRemoteAddress());
throw new IllegalArgumentException(
"Wrong MESSAGE-INTEGRITY value.");
}
}
else if(Boolean.getBoolean(StackProperties.REQUIRE_MESSAGE_INTEGRITY))
{
// no message integrity
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNAUTHORIZED,
"Missing MESSAGE-INTEGRITY.");
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),
evt.getRemoteAddress());
throw new IllegalArgumentException(
"Missing MESSAGE-INTEGRITY.");
}
//look for unknown attributes.
List<Attribute> allAttributes = request.getAttributes();
StringBuffer sBuff = new StringBuffer();
for(Attribute attr : allAttributes)
{
if(attr instanceof OptionalAttribute
&& attr.getAttributeType()
< Attribute.UNKNOWN_OPTIONAL_ATTRIBUTE)
sBuff.append(attr.getAttributeType());
}
if (sBuff.length() > 0)
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNKNOWN_ATTRIBUTE,
"unknown attribute ", sBuff.toString().toCharArray());
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),
evt.getRemoteAddress());
throw new IllegalArgumentException(
"Missing MESSAGE-INTEGRITY.");
}
} | #vulnerable code
private void validateRequestAttributes(StunMessageEvent evt)
throws IllegalArgumentException, StunException, IOException
{
Message request = evt.getMessage();
//assert valid username
UsernameAttribute unameAttr = (UsernameAttribute)request
.getAttribute(Attribute.USERNAME);
String username;
if (unameAttr != null)
{
username = new String(unameAttr.getUsername());
if (!validateUsername( unameAttr))
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNAUTHORIZED,
"unknown user " + username);
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),
evt.getRemoteAddress());
throw new IllegalArgumentException(
"Non-recognized username: "
+ new String(unameAttr.getUsername()));
}
}
//assert Message Integrity
MessageIntegrityAttribute msgIntAttr
= (MessageIntegrityAttribute)
request.getAttribute(Attribute.MESSAGE_INTEGRITY);
if (msgIntAttr != null)
{
//we should complain if we have msg integrity and no username.
if (unameAttr == null)
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.BAD_REQUEST,
"missing username");
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),
evt.getRemoteAddress());
throw new IllegalArgumentException(
"Missing USERNAME in the presence of MESSAGE-INTEGRITY: ");
}
if (!validateMessageIntegrity(msgIntAttr,
new String(unameAttr.getUsername()),
evt.getRawMessage()))
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNAUTHORIZED,
"Wrong MESSAGE-INTEGRITY value");
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),
evt.getRemoteAddress());
throw new IllegalArgumentException(
"Wrong MESSAGE-INTEGRITY value.");
}
}
else if(Boolean.getBoolean(StackProperties.REQUIRE_MESSAGE_INTEGRITY))
{
// no message integrity
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNAUTHORIZED,
"Missing MESSAGE-INTEGRITY.");
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),
evt.getRemoteAddress());
throw new IllegalArgumentException(
"Missing MESSAGE-INTEGRITY.");
}
//look for unknown attributes.
List<Attribute> allAttributes = request.getAttributes();
StringBuffer sBuff = new StringBuffer();
for(Attribute attr : allAttributes)
{
if(attr instanceof OptionalAttribute
&& attr.getAttributeType()
< Attribute.UNKNOWN_OPTIONAL_ATTRIBUTE)
sBuff.append(attr.getAttributeType());
}
if (sBuff.length() > 0)
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNKNOWN_ATTRIBUTE,
"unknown attribute ", sBuff.toString().toCharArray());
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),
evt.getRemoteAddress());
throw new IllegalArgumentException(
"Missing MESSAGE-INTEGRITY.");
}
}
#location 13
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static String[] getBlockedInterfaces() {
if (!interfaceFiltersInitialized)
{
try
{
initializeInterfaceFilters();
}
catch (Exception e)
{
logger.log(Level.WARNING, "There were errors during host " +
"candidate interface filters initialization.", e);
}
}
return blockedInterfaces;
} | #vulnerable code
public static String[] getBlockedInterfaces() {
if (!interfaceFiltersinitialized)
{
try
{
initializeInterfaceFilters();
}
catch (Exception e)
{
logger.log(Level.WARNING, "There were errors during host " +
"candidate interface filters initialization.", e);
}
}
return blockedInterfaces;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
protected void incomingCheckReceived(TransportAddress remoteAddress,
TransportAddress localAddress,
long priority,
String remoteUFrag,
String localUFrag,
boolean useCandidate)
{
String ufrag = null;
LocalCandidate localCandidate = findLocalCandidate(localAddress);
if (localCandidate == null)
{
logger.info("No localAddress for this incoming checks: " +
localAddress);
return;
}
Component parentComponent = localCandidate.getParentComponent();
RemoteCandidate remoteCandidate
= new RemoteCandidate(
remoteAddress,
parentComponent,
CandidateType.PEER_REFLEXIVE_CANDIDATE,
foundationsRegistry.obtainFoundationForPeerReflexiveCandidate(),
priority,
// We can not know the related candidate of a remote peer
// reflexive candidate. We must set it to "null".
null,
ufrag);
CandidatePair triggeredPair
= createCandidatePair(localCandidate, remoteCandidate);
logger.fine("set use-candidate " + useCandidate + " for pair " +
triggeredPair.toShortString());
if (useCandidate)
{
triggeredPair.setUseCandidateReceived();
}
synchronized(startLock)
{
if (state == IceProcessingState.WAITING)
{
logger.fine("Receive STUN checks before our ICE has started");
//we are not started yet so we'd better wait until we get the
//remote candidates in case we are holding to a new PR one.
this.preDiscoveredPairsQueue.add(triggeredPair);
}
else if (state == IceProcessingState.FAILED)
{
// Failure is permanent, currently.
}
else //Running, Connected or Terminated.
{
if (logger.isLoggable(Level.FINE))
{
logger.debug("Received check from "
+ triggeredPair.toShortString() + " triggered a check. "
+ "Local ufrag " + getLocalUfrag());
}
// We have been started, and have not failed (yet). If this is
// a new pair, handle it (even if we have already completed).
triggerCheck(triggeredPair);
}
}
} | #vulnerable code
protected void incomingCheckReceived(TransportAddress remoteAddress,
TransportAddress localAddress,
long priority,
String remoteUFrag,
String localUFrag,
boolean useCandidate)
{
if (isOver())
{
//means we already completed ICE and are happily running media
//the only reason we are called is most probably because the remote
//party is still sending Binding Requests our way and making sure we
//are still alive.
return;
}
String ufrag = null;
LocalCandidate localCandidate = null;
localCandidate = findLocalCandidate(localAddress);
if (localCandidate == null)
{
logger.info("No localAddress for this incoming checks: " +
localAddress);
return;
}
Component parentComponent = localCandidate.getParentComponent();
RemoteCandidate remoteCandidate = null;
remoteCandidate = new RemoteCandidate(
remoteAddress,
parentComponent,
CandidateType.PEER_REFLEXIVE_CANDIDATE,
foundationsRegistry.obtainFoundationForPeerReflexiveCandidate(),
priority,
// We can not know the related candidate of a remote peer
// reflexive candidate. We must set it to "null".
null,
ufrag);
CandidatePair triggeredPair
= createCandidatePair(localCandidate, remoteCandidate);
logger.fine("set use-candidate " + useCandidate + " for pair " +
triggeredPair.toShortString());
if (useCandidate)
{
triggeredPair.setUseCandidateReceived();
}
synchronized(startLock)
{
if (isStarted())
{
//we are started, which means we have the remote candidates
//so it's now safe to go and see whether this is a new PR cand.
if (triggeredPair.getParentComponent().getSelectedPair() == null)
{
logger.info("Received check from "
+ triggeredPair.toShortString() + " triggered a check. "
+ "Local ufrag " + getLocalUfrag());
}
triggerCheck(triggeredPair);
}
else
{
logger.fine("Receive STUN checks before our ICE has started");
//we are not started yet so we'd better wait until we get the
//remote candidates in case we are holding to a new PR one.
this.preDiscoveredPairsQueue.add(triggeredPair);
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
protected void checkListStatesUpdated()
{
boolean allListsEnded = true;
boolean atLeastOneListSucceeded = false;
if(getState() == IceProcessingState.COMPLETED)
return;
List<IceMediaStream> streams = getStreams();
for(IceMediaStream stream : streams)
{
CheckListState checkListState = stream.getCheckList().getState();
if(checkListState == CheckListState.RUNNING)
{
allListsEnded = false;
break;
}
else if(checkListState == CheckListState.COMPLETED)
{
logger.info("CheckList of stream " + stream.getName() +
" is COMPLETED");
atLeastOneListSucceeded = true;
}
}
if(!allListsEnded)
return;
if(!atLeastOneListSucceeded)
{
//all lists ended but none succeeded. No love today ;(
terminate(IceProcessingState.FAILED);
return;
}
//Once the state of each check list is Completed:
//The agent sets the state of ICE processing overall to Completed.
if(getState() != IceProcessingState.RUNNING)
{
//Oh, seems like we already did this.
return;
}
// The race condition in which another thread enters COMPLETED right
// under our nose here has been observed (and not in a single instance)
// So check that we did indeed just trigger the change.
if (!setState(IceProcessingState.COMPLETED))
return;
// keep ICE running (answer STUN Binding requests, send STUN Binding
// indications or requests)
if (stunKeepAliveThread == null
&& !StackProperties.getBoolean(
StackProperties.NO_KEEP_ALIVES,
false))
{
// schedule STUN checks for selected candidates
scheduleStunKeepAlive();
}
scheduleTermination();
//print logs for the types of addresses we chose.
logCandTypes();
} | #vulnerable code
protected void checkListStatesUpdated()
{
boolean allListsEnded = true;
boolean atLeastOneListSucceeded = false;
if(getState() == IceProcessingState.COMPLETED)
return;
List<IceMediaStream> streams = getStreams();
for(IceMediaStream stream : streams)
{
CheckListState checkListState = stream.getCheckList().getState();
if(checkListState == CheckListState.RUNNING)
{
allListsEnded = false;
break;
}
else if(checkListState == CheckListState.COMPLETED)
{
logger.info("CheckList of stream " + stream.getName() +
" is COMPLETED");
atLeastOneListSucceeded = true;
}
}
if(!allListsEnded)
return;
if(!atLeastOneListSucceeded)
{
//all lists ended but none succeeded. No love today ;(
logger.info("ICE state is FAILED");
terminate(IceProcessingState.FAILED);
return;
}
//Once the state of each check list is Completed:
//The agent sets the state of ICE processing overall to Completed.
if(getState() != IceProcessingState.RUNNING)
{
//Oh, seems like we already did this.
return;
}
logger.info("ICE state is COMPLETED");
setState(IceProcessingState.COMPLETED);
// keep ICE running (answer STUN Binding requests, send STUN Binding
// indications or requests)
if(stunKeepAliveThread == null
&& !StackProperties.getBoolean(
StackProperties.NO_KEEP_ALIVES,
false))
{
// schedule STUN checks for selected candidates
scheduleStunKeepAlive();
}
scheduleTermination();
//print logs for the types of addresses we chose.
logCandTypes();
}
#location 36
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void free()
{
logger.fine("Free ICE agent");
shutdown = true;
//stop sending keep alives (STUN Binding Indications).
if (stunKeepAliveThread != null)
stunKeepAliveThread.interrupt();
// cancel termination timer in case agent is freed
// before termination timer is triggered
synchronized (terminationFutureSyncRoot)
{
if (terminationFuture != null)
{
terminationFuture.cancel(true);
terminationFuture = null;
}
}
//stop responding to STUN Binding Requests.
connCheckServer.stop();
/*
* Set the IceProcessingState#TERMINATED state on this Agent unless it
* is in a termination state already.
*/
IceProcessingState state = getState();
if (!IceProcessingState.FAILED.equals(state)
&& !IceProcessingState.TERMINATED.equals(state))
{
terminate(IceProcessingState.TERMINATED);
}
// Free its IceMediaStreams, Components and Candidates.
boolean interrupted = false;
logger.fine("remove streams");
for (IceMediaStream stream : getStreams())
{
try
{
removeStream(stream);
logger.fine("remove stream " + stream.getName());
}
catch (Throwable t)
{
logger.fine(
"remove stream " + stream.getName() + " failed: " + t);
if (t instanceof InterruptedException)
interrupted = true;
else if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
}
if (interrupted)
Thread.currentThread().interrupt();
getStunStack().shutDown();
logger.fine("ICE agent freed");
} | #vulnerable code
public void free()
{
logger.fine("Free ICE agent");
shutdown = true;
//stop sending keep alives (STUN Binding Indications).
if (stunKeepAliveThread != null)
stunKeepAliveThread.interrupt();
//stop responding to STUN Binding Requests.
connCheckServer.stop();
/*
* Set the IceProcessingState#TERMINATED state on this Agent unless it
* is in a termination state already.
*/
IceProcessingState state = getState();
if (!IceProcessingState.FAILED.equals(state)
&& !IceProcessingState.TERMINATED.equals(state))
{
terminate(IceProcessingState.TERMINATED);
}
// Free its IceMediaStreams, Components and Candidates.
boolean interrupted = false;
logger.fine("remove streams");
for (IceMediaStream stream : getStreams())
{
try
{
removeStream(stream);
logger.fine("remove stream " + stream.getName());
}
catch (Throwable t)
{
logger.fine(
"remove stream " + stream.getName() + " failed: " + t);
if (t instanceof InterruptedException)
interrupted = true;
else if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
}
if (interrupted)
Thread.currentThread().interrupt();
getStunStack().shutDown();
logger.fine("ICE agent freed");
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
protected void free()
{
synchronized (localCandidates)
{
/*
* Since the sockets of the non-HostCandidate LocalCandidates may
* depend on the socket of the HostCandidate for which they have
* been harvested, order the freeing.
*/
CandidateType[] candidateTypes
= new CandidateType[]
{
CandidateType.RELAYED_CANDIDATE,
CandidateType.PEER_REFLEXIVE_CANDIDATE,
CandidateType.SERVER_REFLEXIVE_CANDIDATE
};
for (CandidateType candidateType : candidateTypes)
{
Iterator<LocalCandidate> localCandidateIter
= localCandidates.iterator();
while (localCandidateIter.hasNext())
{
LocalCandidate localCandidate = localCandidateIter.next();
if (candidateType.equals(localCandidate.getType()))
{
free(localCandidate);
localCandidateIter.remove();
}
}
}
// Free whatever's left.
Iterator<LocalCandidate> localCandidateIter
= localCandidates.iterator();
while (localCandidateIter.hasNext())
{
LocalCandidate localCandidate = localCandidateIter.next();
free(localCandidate);
localCandidateIter.remove();
}
}
getComponentSocket().close();
} | #vulnerable code
protected void free()
{
synchronized (localCandidates)
{
/*
* Since the sockets of the non-HostCandidate LocalCandidates may
* depend on the socket of the HostCandidate for which they have
* been harvested, order the freeing.
*/
CandidateType[] candidateTypes
= new CandidateType[]
{
CandidateType.RELAYED_CANDIDATE,
CandidateType.PEER_REFLEXIVE_CANDIDATE,
CandidateType.SERVER_REFLEXIVE_CANDIDATE
};
for (CandidateType candidateType : candidateTypes)
{
Iterator<LocalCandidate> localCandidateIter
= localCandidates.iterator();
while (localCandidateIter.hasNext())
{
LocalCandidate localCandidate = localCandidateIter.next();
if (candidateType.equals(localCandidate.getType()))
{
free(localCandidate);
localCandidateIter.remove();
}
}
}
// Free whatever's left.
Iterator<LocalCandidate> localCandidateIter
= localCandidates.iterator();
while (localCandidateIter.hasNext())
{
LocalCandidate localCandidate = localCandidateIter.next();
free(localCandidate);
localCandidateIter.remove();
}
}
getSocket().close();
}
#location 48
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public boolean equals(Object obj)
throws NullPointerException
{
if (obj == this)
return true;
if (! (obj instanceof Candidate))
return false;
Candidate<?> candidate = (Candidate<?>) obj;
//compare candidate addresses
if (! candidate.getTransportAddress().equals(getTransportAddress()))
return false;
//compare bases
Candidate<?> base = getBase();
Candidate<?> candidateBase = candidate.getBase();
boolean baseEqualsCandidateBase;
if (base == null)
{
if (candidateBase != null)
return false;
else
baseEqualsCandidateBase = true;
}
else
{
baseEqualsCandidateBase = base.equals(candidateBase);
}
//compare other properties
return
(baseEqualsCandidateBase
|| (base == this && candidateBase == candidate))
&& getPriority() == candidate.getPriority()
&& getType() == candidate.getType()
&& getFoundation().equals(candidate.getFoundation());
} | #vulnerable code
@Override
public boolean equals(Object obj)
throws NullPointerException
{
if(obj == this)
return true;
if( ! (obj instanceof Candidate))
return false;
Candidate<?> targetCandidate = (Candidate<?>) obj;
//compare candidate addresses
if( ! targetCandidate.getTransportAddress()
.equals(getTransportAddress()))
return false;
//compare bases
if( getBase() == null )
{
if (targetCandidate.getBase() != null)
return false;
}
//compare other properties
if(((getBase() == this && targetCandidate.getBase() == targetCandidate)
|| getBase().equals(targetCandidate.getBase()))
&& getPriority() == targetCandidate.getPriority()
&& getType() == targetCandidate.getType()
&& getFoundation().equals(targetCandidate.getFoundation()))
{
return true;
}
return false;
}
#location 27
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
void sendRequest()
throws IllegalArgumentException, IOException
{
logger.fine(
"sending STUN " + " tid " + transactionID + " from "
+ localAddress + " to " + requestDestination);
sendRequest0();
this.retransmitter.schedule();
} | #vulnerable code
void sendRequest()
throws IllegalArgumentException, IOException
{
logger.fine(
"sending STUN " + " tid " + transactionID + " from "
+ localAddress + " to " + requestDestination);
sendRequest0();
retransmissionThreadPool.execute(this);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void run()
{
retransmissionsThread.setName("ice4j.ClientTransaction");
nextWaitInterval = originalWaitInterval;
synchronized(this)
{
for (retransmissionCounter = 0;
retransmissionCounter < maxRetransmissions;
retransmissionCounter ++)
{
waitFor(nextWaitInterval);
//did someone tell us to get lost?
if(cancelled)
return;
if(nextWaitInterval < maxWaitInterval)
nextWaitInterval *= 2;
try
{
sendRequest0();
}
catch (Exception ex)
{
//I wonder whether we should notify anyone that a
//retransmission has failed
logger.log(Level.INFO,
"A client tran retransmission failed", ex);
}
}
//before stating that a transaction has timeout-ed we should first
//wait for a reception of the response
if(nextWaitInterval < maxWaitInterval)
nextWaitInterval *= 2;
waitFor(nextWaitInterval);
if(cancelled)
return;
stackCallback.removeClientTransaction(this);
responseCollector.processTimeout( new StunTimeoutEvent(
this.request, getLocalAddress(), transactionID));
}
} | #vulnerable code
public void run()
{
retransmissionsThread.setName("ice4j.ClientTransaction");
nextWaitInterval = originalWaitInterval;
for (retransmissionCounter = 0;
retransmissionCounter < maxRetransmissions;
retransmissionCounter ++)
{
waitFor(nextWaitInterval);
//did someone tell us to get lost?
if(cancelled)
return;
if(nextWaitInterval < maxWaitInterval)
nextWaitInterval *= 2;
try
{
sendRequest0();
}
catch (Exception ex)
{
//I wonder whether we should notify anyone that a retransmission
//has failed
logger.log(Level.WARNING,
"A client tran retransmission failed", ex);
}
}
//before stating that a transaction has timeout-ed we should first wait
//for a reception of the response
if(nextWaitInterval < maxWaitInterval)
nextWaitInterval *= 2;
waitFor(nextWaitInterval);
responseCollector.processTimeout( new StunTimeoutEvent(
this.request, getLocalAddress(), transactionID));
stackCallback.removeClientTransaction(this);
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private static void assertSigned(File outFolder, List<File> uApks) throws Exception {
assertNotNull(outFolder);
File[] outFiles = outFolder.listFiles(pathname -> FileUtil.getFileExtension(pathname).toLowerCase().equals("apk"));
System.out.println("Found " + outFiles.length + " apks in out dir");
assertNotNull(outFiles);
assertEquals("should be same count of apks in out folder", uApks.size(), outFiles.length);
for (File outFile : outFiles) {
AndroidApkSignerVerify.Result verifyResult = new AndroidApkSignerVerify().verify(outFile, null, null, false);
assertTrue(verifyResult.verified);
assertEquals(0, verifyResult.warning);
}
} | #vulnerable code
private static void assertSigned(File outFolder, List<File> uApks) throws Exception {
assertNotNull(outFolder);
File[] outFiles = outFolder.listFiles();
assertNotNull(outFiles);
assertEquals("should be same count of apks in out folder", uApks.size(), outFiles.length);
for (File outFile : outFiles) {
AndroidApkSignerVerify.Result verifyResult = new AndroidApkSignerVerify().verify(outFile, null, null, false);
assertTrue(verifyResult.verified);
assertEquals(0, verifyResult.warning);
}
}
#location 5
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Expression parseVersionExpression() {
int major = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
if (tokens.positiveLookahead(STAR)) {
tokens.consume();
return new And(
new GreaterOrEqual(versionOf(major, 0, 0)),
new Less(versionOf(major + 1, 0, 0))
);
}
int minor = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
consumeNextToken(STAR);
return new And(
new GreaterOrEqual(versionOf(major, minor, 0)),
new Less(versionOf(major, minor + 1, 0))
);
} | #vulnerable code
private Expression parseVersionExpression() {
int major = intOf(tokens.consume(NUMERIC).lexeme);
tokens.consume(DOT);
if (tokens.positiveLookahead(STAR)) {
tokens.consume();
return new And(
new GreaterOrEqual(versionOf(major, 0, 0)),
new Less(versionOf(major + 1, 0, 0))
);
}
int minor = intOf(tokens.consume(NUMERIC).lexeme);
tokens.consume(DOT);
tokens.consume(STAR);
return new And(
new GreaterOrEqual(versionOf(major, minor, 0)),
new Less(versionOf(major, minor + 1, 0))
);
}
#location 2
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void checkForLeadingZeroes() {
Character la1 = chars.lookahead(1);
Character la2 = chars.lookahead(2);
if (la1 != null && la1 == '0' && DIGIT.isMatchedBy(la2)) {
throw new ParseException(
"Numeric identifier MUST NOT contain leading zeroes"
);
}
} | #vulnerable code
private void checkForLeadingZeroes() {
Character la1 = chars.lookahead(1);
Character la2 = chars.lookahead(2);
if (la1 == '0' && DIGIT.isMatchedBy(la2)) {
throw new ParseException(
"Numeric identifier MUST NOT contain leading zeroes"
);
}
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Expression parseTildeExpression() {
consumeNextToken(TILDE);
int major = intOf(consumeNextToken(NUMERIC).lexeme);
if (!tokens.positiveLookahead(DOT)) {
return new GreaterOrEqual(versionOf(major, 0, 0));
}
consumeNextToken(DOT);
int minor = intOf(consumeNextToken(NUMERIC).lexeme);
if (!tokens.positiveLookahead(DOT)) {
return new And(
new GreaterOrEqual(versionOf(major, minor, 0)),
new Less(versionOf(major + 1, 0, 0))
);
}
consumeNextToken(DOT);
int patch = intOf(consumeNextToken(NUMERIC).lexeme);
return new And(
new GreaterOrEqual(versionOf(major, minor, patch)),
new Less(versionOf(major, minor + 1, 0))
);
} | #vulnerable code
private Expression parseTildeExpression() {
tokens.consume(TILDE);
int major = intOf(tokens.consume(NUMERIC).lexeme);
if (!tokens.positiveLookahead(DOT)) {
return new GreaterOrEqual(versionOf(major, 0, 0));
}
tokens.consume(DOT);
int minor = intOf(tokens.consume(NUMERIC).lexeme);
if (!tokens.positiveLookahead(DOT)) {
return new And(
new GreaterOrEqual(versionOf(major, minor, 0)),
new Less(versionOf(major + 1, 0, 0))
);
}
tokens.consume(DOT);
int patch = intOf(tokens.consume(NUMERIC).lexeme);
return new And(
new GreaterOrEqual(versionOf(major, minor, patch)),
new Less(versionOf(major, minor + 1, 0))
);
}
#location 16
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Version parseVersion() {
int major = intOf(consumeNextToken(NUMERIC).lexeme);
int minor = 0;
if (tokens.positiveLookahead(DOT)) {
tokens.consume();
minor = intOf(consumeNextToken(NUMERIC).lexeme);
}
int patch = 0;
if (tokens.positiveLookahead(DOT)) {
tokens.consume();
patch = intOf(consumeNextToken(NUMERIC).lexeme);
}
return versionOf(major, minor, patch);
} | #vulnerable code
private Version parseVersion() {
int major = intOf(tokens.consume(NUMERIC).lexeme);
int minor = 0;
if (tokens.positiveLookahead(DOT)) {
tokens.consume();
minor = intOf(tokens.consume(NUMERIC).lexeme);
}
int patch = 0;
if (tokens.positiveLookahead(DOT)) {
tokens.consume();
patch = intOf(tokens.consume(NUMERIC).lexeme);
}
return versionOf(major, minor, patch);
}
#location 2
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Version parseVersion() {
int major = intOf(consumeNextToken(NUMERIC).lexeme);
int minor = 0;
if (tokens.positiveLookahead(DOT)) {
tokens.consume();
minor = intOf(consumeNextToken(NUMERIC).lexeme);
}
int patch = 0;
if (tokens.positiveLookahead(DOT)) {
tokens.consume();
patch = intOf(consumeNextToken(NUMERIC).lexeme);
}
return versionOf(major, minor, patch);
} | #vulnerable code
private Version parseVersion() {
int major = intOf(tokens.consume(NUMERIC).lexeme);
int minor = 0;
if (tokens.positiveLookahead(DOT)) {
tokens.consume();
minor = intOf(tokens.consume(NUMERIC).lexeme);
}
int patch = 0;
if (tokens.positiveLookahead(DOT)) {
tokens.consume();
patch = intOf(tokens.consume(NUMERIC).lexeme);
}
return versionOf(major, minor, patch);
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
protected void setIV(byte[] iv, boolean isEncrypt) {
if (_ivLength == 0) {
return;
}
CipherParameters cipherParameters = null;
if (isEncrypt) {
cipherParameters = getCipherParameters(iv);
try {
encCipher = getCipher(isEncrypt);
} catch (InvalidAlgorithmParameterException e) {
logger.info(e.toString());
}
encCipher.init(isEncrypt, cipherParameters);
} else {
_decryptIV = new byte[_ivLength];
System.arraycopy(iv, 0, _decryptIV, 0, _ivLength);
cipherParameters = getCipherParameters(iv);
try {
decCipher = getCipher(isEncrypt);
} catch (InvalidAlgorithmParameterException e) {
logger.info(e.toString());
}
decCipher.init(isEncrypt, cipherParameters);
}
} | #vulnerable code
protected void setIV(byte[] iv, boolean isEncrypt) {
if (_ivLength == 0) {
return;
}
if (isEncrypt) {
try {
_encryptIV = new byte[_ivLength];
System.arraycopy(iv, 0, _encryptIV, 0, _ivLength);
encCipher = getCipher(isEncrypt);
ParametersWithIV parameterIV = new ParametersWithIV(
new KeyParameter(_key.getEncoded()), _encryptIV);
encCipher.init(isEncrypt, parameterIV);
} catch (InvalidAlgorithmParameterException e) {
logger.info(e.toString());
}
} else {
try {
_decryptIV = new byte[_ivLength];
System.arraycopy(iv, 0, _decryptIV, 0, _ivLength);
decCipher = getCipher(isEncrypt);
ParametersWithIV parameterIV = new ParametersWithIV(
new KeyParameter(_key.getEncoded()), _decryptIV);
decCipher.init(isEncrypt, parameterIV);
} catch (InvalidAlgorithmParameterException e) {
logger.info(e.toString());
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void testBase64() {
String content = "Hello World";
String encodedContent;
byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content));
encodedContent = StringUtils.newStringUtf8(encodedBytes);
assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ="));
Base64 b64 = new Base64(76, null); // null lineSeparator same as saying no-chunking
encodedBytes = b64.encode(StringUtils.getBytesUtf8(content));
encodedContent = StringUtils.newStringUtf8(encodedBytes);
assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ="));
b64 = new Base64(0, null); // null lineSeparator same as saying no-chunking
encodedBytes = b64.encode(StringUtils.getBytesUtf8(content));
encodedContent = StringUtils.newStringUtf8(encodedBytes);
assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ="));
// bogus characters to decode (to skip actually)
byte[] decode = b64.decode("SGVsbG{}8gV29ybGQ=");
String decodeString = StringUtils.newStringUtf8(decode);
assertTrue("decode hello world", decodeString.equals("Hello World"));
} | #vulnerable code
public void testBase64() {
String content = "Hello World";
String encodedContent;
byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content));
encodedContent = StringUtils.newStringUtf8(encodedBytes);
assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ="));
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
@Ignore
public void testCodec130() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Base64OutputStream base64os = new Base64OutputStream(bos);
base64os.write(StringUtils.getBytesUtf8(STRING_FIXTURE));
base64os.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
Base64InputStream ins = new Base64InputStream(bis);
// we skip the first character read from the reader
ins.skip(1);
byte[] decodedBytes = Base64TestData.streamToBytes(ins, new byte[64]);
String str = StringUtils.newStringUtf8(decodedBytes);
assertEquals(STRING_FIXTURE.substring(1), str);
} | #vulnerable code
@Test
@Ignore
public void testCodec130() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Base64OutputStream base64os = new Base64OutputStream(bos);
base64os.write(STRING_FIXTURE.getBytes());
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
Base64InputStream ins = new Base64InputStream(bis);
// we skip the first character read from the reader
ins.skip(1);
StringBuffer sb = new StringBuffer();
int len = 0;
byte[] bytes = new byte[10];
while ((len = ins.read(bytes)) != -1) {
String s = new String(bytes, 0, len, "iso-8859-1");
sb.append(s);
}
String str = sb.toString();
assertEquals(STRING_FIXTURE.substring(1), str);
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testKnownDecodings() {
assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64
.decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(CHARSET_UTF8))));
assertEquals("It was the best of times, it was the worst of times.", new String(Base64
.decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes(CHARSET_UTF8))));
assertEquals("http://jakarta.apache.org/commmons", new String(Base64
.decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes(CHARSET_UTF8))));
assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64
.decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes(CHARSET_UTF8))));
assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0="
.getBytes(CHARSET_UTF8))));
assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes(CHARSET_UTF8))));
} | #vulnerable code
@Test
public void testKnownDecodings() {
assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64
.decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(Charsets.UTF_8))));
assertEquals("It was the best of times, it was the worst of times.", new String(Base64
.decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes(Charsets.UTF_8))));
assertEquals("http://jakarta.apache.org/commmons", new String(Base64
.decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes(Charsets.UTF_8))));
assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64
.decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes(Charsets.UTF_8))));
assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0="
.getBytes(Charsets.UTF_8))));
assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes(Charsets.UTF_8))));
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testReadNull() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE);
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 });
try {
in.read(null, 0, 0);
fail("Base32InputStream.read(null, 0, 0) to throw a NullPointerException");
} catch (NullPointerException e) {
// Expected
}
in.close();
} | #vulnerable code
@Test
public void testReadNull() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE);
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 });
try {
in.read(null, 0, 0);
fail("Base32InputStream.read(null, 0, 0) to throw a NullPointerException");
} catch (NullPointerException e) {
// Expected
}
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSkipToEnd() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64));
Base64InputStream b64stream = new Base64InputStream(ins);
// due to CODEC-130, skip now skips correctly decoded characters rather than encoded
assertEquals(6, b64stream.skip(6));
// End of stream reached
assertEquals(-1, b64stream.read());
assertEquals(-1, b64stream.read());
b64stream.close();
} | #vulnerable code
@Test
public void testSkipToEnd() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64));
Base64InputStream b64stream = new Base64InputStream(ins);
// due to CODEC-130, skip now skips correctly decoded characters rather than encoded
assertEquals(6, b64stream.skip(6));
// End of stream reached
assertEquals(-1, b64stream.read());
assertEquals(-1, b64stream.read());
}
#location 8
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testEncodeAtzNotEmpty() throws EncoderException {
BeiderMorseEncoder bmpm = new BeiderMorseEncoder();
bmpm.setNameType(NameType.GENERIC);
bmpm.setRuleType(RuleType.APPROX);
String[] names = { "ácz", "átz", "Ignácz", "Ignátz", "Ignác" };
for (String name : names) {
assertNotEmpty(bmpm, name);
}
} | #vulnerable code
@Test
public void testEncodeAtzNotEmpty() throws EncoderException {
BeiderMorseEncoder bmpm = new BeiderMorseEncoder();
bmpm.setNameType(NameType.GENERIC);
bmpm.setRuleType(RuleType.APPROX);
String[] names = { "ácz", "átz", "Ignácz", "Ignátz", "Ignác" };
for (String name : names) {
Assert.assertFalse(bmpm.encode(name).equals(""));
}
}
#location 8
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSkipNone() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO));
Base32InputStream b32stream = new Base32InputStream(ins);
byte[] actualBytes = new byte[6];
assertEquals(0, b32stream.skip(0));
b32stream.read(actualBytes, 0, actualBytes.length);
assertArrayEquals(actualBytes, new byte[] { 102, 111, 111, 0, 0, 0 });
// End of stream reached
assertEquals(-1, b32stream.read());
b32stream.close();
} | #vulnerable code
@Test
public void testSkipNone() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO));
Base32InputStream b32stream = new Base32InputStream(ins);
byte[] actualBytes = new byte[6];
assertEquals(0, b32stream.skip(0));
b32stream.read(actualBytes, 0, actualBytes.length);
assertArrayEquals(actualBytes, new byte[] { 102, 111, 111, 0, 0, 0 });
// End of stream reached
assertEquals(-1, b32stream.read());
}
#location 10
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testDecodePadOnly() {
assertEquals(0, Base64.decodeBase64("====".getBytes(CHARSET_UTF8)).length);
assertEquals("", new String(Base64.decodeBase64("====".getBytes(CHARSET_UTF8))));
// Test truncated padding
assertEquals(0, Base64.decodeBase64("===".getBytes(CHARSET_UTF8)).length);
assertEquals(0, Base64.decodeBase64("==".getBytes(CHARSET_UTF8)).length);
assertEquals(0, Base64.decodeBase64("=".getBytes(CHARSET_UTF8)).length);
assertEquals(0, Base64.decodeBase64("".getBytes(CHARSET_UTF8)).length);
} | #vulnerable code
@Test
public void testDecodePadOnly() {
assertEquals(0, Base64.decodeBase64("====".getBytes(Charsets.UTF_8)).length);
assertEquals("", new String(Base64.decodeBase64("====".getBytes(Charsets.UTF_8))));
// Test truncated padding
assertEquals(0, Base64.decodeBase64("===".getBytes(Charsets.UTF_8)).length);
assertEquals(0, Base64.decodeBase64("==".getBytes(Charsets.UTF_8)).length);
assertEquals(0, Base64.decodeBase64("=".getBytes(Charsets.UTF_8)).length);
assertEquals(0, Base64.decodeBase64("".getBytes(Charsets.UTF_8)).length);
}
#location 3
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testAvailable() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64));
Base64InputStream b64stream = new Base64InputStream(ins);
assertEquals(1, b64stream.available());
assertEquals(6, b64stream.skip(10));
// End of stream reached
assertEquals(0, b64stream.available());
assertEquals(-1, b64stream.read());
assertEquals(-1, b64stream.read());
assertEquals(0, b64stream.available());
b64stream.close();
} | #vulnerable code
@Test
public void testAvailable() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64));
Base64InputStream b64stream = new Base64InputStream(ins);
assertEquals(1, b64stream.available());
assertEquals(6, b64stream.skip(10));
// End of stream reached
assertEquals(0, b64stream.available());
assertEquals(-1, b64stream.read());
assertEquals(-1, b64stream.read());
assertEquals(0, b64stream.available());
}
#location 8
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testDecodePadOnlyChunked() {
assertEquals(0, Base64.decodeBase64("====\n".getBytes(CHARSET_UTF8)).length);
assertEquals("", new String(Base64.decodeBase64("====\n".getBytes(CHARSET_UTF8))));
// Test truncated padding
assertEquals(0, Base64.decodeBase64("===\n".getBytes(CHARSET_UTF8)).length);
assertEquals(0, Base64.decodeBase64("==\n".getBytes(CHARSET_UTF8)).length);
assertEquals(0, Base64.decodeBase64("=\n".getBytes(CHARSET_UTF8)).length);
assertEquals(0, Base64.decodeBase64("\n".getBytes(CHARSET_UTF8)).length);
} | #vulnerable code
@Test
public void testDecodePadOnlyChunked() {
assertEquals(0, Base64.decodeBase64("====\n".getBytes(Charsets.UTF_8)).length);
assertEquals("", new String(Base64.decodeBase64("====\n".getBytes(Charsets.UTF_8))));
// Test truncated padding
assertEquals(0, Base64.decodeBase64("===\n".getBytes(Charsets.UTF_8)).length);
assertEquals(0, Base64.decodeBase64("==\n".getBytes(Charsets.UTF_8)).length);
assertEquals(0, Base64.decodeBase64("=\n".getBytes(Charsets.UTF_8)).length);
assertEquals(0, Base64.decodeBase64("\n".getBytes(Charsets.UTF_8)).length);
}
#location 3
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void testKnownDecodings() throws UnsupportedEncodingException {
assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64
.decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8"))));
assertEquals("It was the best of times, it was the worst of times.", new String(Base64
.decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes("UTF-8"))));
assertEquals("http://jakarta.apache.org/commmons", new String(Base64
.decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes("UTF-8"))));
assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64
.decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes("UTF-8"))));
assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0="
.getBytes("UTF-8"))));
assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes("UTF-8"))));
} | #vulnerable code
public void testKnownDecodings() {
assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64
.decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes())));
assertEquals("It was the best of times, it was the worst of times.", new String(Base64
.decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes())));
assertEquals("http://jakarta.apache.org/commmons", new String(Base64
.decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes())));
assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64
.decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes())));
assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0="
.getBytes())));
assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes())));
}
#location 3
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testRead0() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE);
byte[] buf = new byte[1024];
int bytesRead = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 });
bytesRead = in.read(buf, 0, 0);
assertEquals("Base32InputStream.read(buf, 0, 0) returns 0", 0, bytesRead);
in.close();
} | #vulnerable code
@Test
public void testRead0() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE);
byte[] buf = new byte[1024];
int bytesRead = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 });
bytesRead = in.read(buf, 0, 0);
assertEquals("Base32InputStream.read(buf, 0, 0) returns 0", 0, bytesRead);
}
#location 8
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testWriteToNullCoverage() throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Base32OutputStream out = new Base32OutputStream(bout);
try {
out.write(null, 0, 0);
fail("Expcted Base32OutputStream.write(null) to throw a NullPointerException");
} catch (NullPointerException e) {
// Expected
}
out.close();
} | #vulnerable code
@Test
public void testWriteToNullCoverage() throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Base32OutputStream out = new Base32OutputStream(bout);
try {
out.write(null, 0, 0);
fail("Expcted Base32OutputStream.write(null) to throw a NullPointerException");
} catch (NullPointerException e) {
// Expected
}
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSkipToEnd() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO));
Base32InputStream b32stream = new Base32InputStream(ins);
// due to CODEC-130, skip now skips correctly decoded characters rather than encoded
assertEquals(3, b32stream.skip(3));
// End of stream reached
assertEquals(-1, b32stream.read());
assertEquals(-1, b32stream.read());
b32stream.close();
} | #vulnerable code
@Test
public void testSkipToEnd() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO));
Base32InputStream b32stream = new Base32InputStream(ins);
// due to CODEC-130, skip now skips correctly decoded characters rather than encoded
assertEquals(3, b32stream.skip(3));
// End of stream reached
assertEquals(-1, b32stream.read());
assertEquals(-1, b32stream.read());
}
#location 8
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSkipPastEnd() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64));
Base64InputStream b64stream = new Base64InputStream(ins);
// due to CODEC-130, skip now skips correctly decoded characters rather than encoded
assertEquals(6, b64stream.skip(10));
// End of stream reached
assertEquals(-1, b64stream.read());
assertEquals(-1, b64stream.read());
} | #vulnerable code
@Test
public void testSkipPastEnd() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64));
Base64InputStream b64stream = new Base64InputStream(ins);
assertEquals(8, b64stream.skip(10));
// End of stream reached
assertEquals(-1, b64stream.read());
assertEquals(-1, b64stream.read());
}
#location 9
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testReadNull() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 });
try {
in.read(null, 0, 0);
fail("Base64InputStream.read(null, 0, 0) to throw a NullPointerException");
} catch (NullPointerException e) {
// Expected
}
in.close();
} | #vulnerable code
@Test
public void testReadNull() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 });
try {
in.read(null, 0, 0);
fail("Base64InputStream.read(null, 0, 0) to throw a NullPointerException");
} catch (NullPointerException e) {
// Expected
}
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSkipBig() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64));
Base64InputStream b64stream = new Base64InputStream(ins);
assertEquals(6, b64stream.skip(Integer.MAX_VALUE));
// End of stream reached
assertEquals(-1, b64stream.read());
assertEquals(-1, b64stream.read());
b64stream.close();
} | #vulnerable code
@Test
public void testSkipBig() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64));
Base64InputStream b64stream = new Base64InputStream(ins);
assertEquals(6, b64stream.skip(Integer.MAX_VALUE));
// End of stream reached
assertEquals(-1, b64stream.read());
assertEquals(-1, b64stream.read());
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSkipBig() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO));
Base32InputStream b32stream = new Base32InputStream(ins);
assertEquals(3, b32stream.skip(1024));
// End of stream reached
assertEquals(-1, b32stream.read());
assertEquals(-1, b32stream.read());
b32stream.close();
} | #vulnerable code
@Test
public void testSkipBig() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO));
Base32InputStream b32stream = new Base32InputStream(ins);
assertEquals(3, b32stream.skip(1024));
// End of stream reached
assertEquals(-1, b32stream.read());
assertEquals(-1, b32stream.read());
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSkipPastEnd() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO));
Base32InputStream b32stream = new Base32InputStream(ins);
// due to CODEC-130, skip now skips correctly decoded characters rather than encoded
assertEquals(3, b32stream.skip(10));
// End of stream reached
assertEquals(-1, b32stream.read());
assertEquals(-1, b32stream.read());
b32stream.close();
} | #vulnerable code
@Test
public void testSkipPastEnd() throws Throwable {
InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO));
Base32InputStream b32stream = new Base32InputStream(ins);
// due to CODEC-130, skip now skips correctly decoded characters rather than encoded
assertEquals(3, b32stream.skip(10));
// End of stream reached
assertEquals(-1, b32stream.read());
assertEquals(-1, b32stream.read());
}
#location 8
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void bind() {
bind(false);
} | #vulnerable code
public void bind() {
if (bound) throw new IllegalStateException("Already bound to " + assignedThread);
bound = true;
assignedThread = Thread.currentThread();
AffinitySupport.setAffinity(1L << id);
if (LOGGER.isLoggable(Level.INFO))
LOGGER.info("Assigning cpu " + id + " to " + assignedThread);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void bind() {
bind(false);
} | #vulnerable code
public void bind() {
if (bound) throw new IllegalStateException("Already bound to " + assignedThread);
bound = true;
assignedThread = Thread.currentThread();
AffinitySupport.setAffinity(1L << id);
if (LOGGER.isLoggable(Level.INFO))
LOGGER.info("Assigning cpu " + id + " to " + assignedThread);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void bind() {
bind(false);
} | #vulnerable code
public void bind() {
if (bound) throw new IllegalStateException("Already bound to " + assignedThread);
bound = true;
assignedThread = Thread.currentThread();
AffinitySupport.setAffinity(1L << id);
if (LOGGER.isLoggable(Level.INFO))
LOGGER.info("Assigning cpu " + id + " to " + assignedThread);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void bind() {
bind(false);
} | #vulnerable code
public void bind() {
if (bound) throw new IllegalStateException("Already bound to " + assignedThread);
bound = true;
assignedThread = Thread.currentThread();
AffinitySupport.setAffinity(1L << id);
if (LOGGER.isLoggable(Level.INFO))
LOGGER.info("Assigning cpu " + id + " to " + assignedThread);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
synchronized (Runtime.getRuntime()) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 49
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (CACHE_DISABLE || !cacheAggressively) {
char[] seg = new char[expression.length - 3];
// arraycopy(expression, 2, seg, 0, seg.length);
for (int i = 0; i < seg.length; i++)
seg[i] = expression[i + 2];
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
if (tokens == null) {
tokens = new HashMap();
}
ForeachContext foreachContext;
String[] names;
String[] aliases;
if (!(localStack.peek() instanceof ForeachContext)) {
// create a clone of the context
foreachContext = ((ForeachContext) currNode.getRegister()).clone();
names = foreachContext.getNames();
aliases = foreachContext.getAliases();
try {
Iterator[] iters = new Iterator[names.length];
for (int i = 0; i < names.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(names[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator(); // this throws null pointer exception in thread race
}
// set the newly created iterators into the context
foreachContext.setIterators(iters);
// push the context onto the local stack.
localStack.push(foreachContext);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)), e);
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)), e);
}
}
else {
foreachContext = (ForeachContext) localStack.peek();
// names = foreachContext.getNames();
aliases = foreachContext.getAliases();
}
Iterator[] iters = foreachContext.getItererators();
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(aliases[i], iters[i].next());
}
int c;
tokens.put("i0", c = foreachContext.getCount());
if (c != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
foreachContext.incrementCount();
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(aliases[i]);
}
// foreachContext.setIterators(null);
// foreachContext.setCount(0);
localStack.pop();
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (CACHE_DISABLE || !cacheAggressively) {
char[] seg = new char[expression.length - 3];
// arraycopy(expression, 2, seg, 0, seg.length);
for (int i = 0; i < seg.length; i++)
seg[i] = expression[i + 2];
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
if (tokens == null) {
tokens = new HashMap();
}
ForeachContext foreachContext;
if (!(localStack.peek() instanceof ForeachContext)) {
foreachContext = ((ForeachContext) currNode.getRegister()).clone();
// if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
localStack.push(foreachContext);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
foreachContext = (ForeachContext) localStack.peek();
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
localStack.pop();
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 119
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
// return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens);
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, MVEL.compileExpression(s));
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
ExpressionParser oParser = new ExpressionParser(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = ( ForeachContext ) currNode.getRegister();
if ( foreachContext.getItererators() == null ) {
try {
String[] lists = getForEachSegment(currNode).split( "," );
Iterator[] iters = new Iterator[lists.length];
for( int i = 0; i < lists.length; i++ ) {
Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse();
if ( listObject instanceof Object[]) {
listObject = Arrays.asList( (Object[]) listObject );
}
iters[i] = ((Collection)listObject).iterator() ;
}
foreachContext.setIterators( iters );
} catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split( "," );
// must trim vars
for ( int i = 0; i < alias.length; i++ ) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for ( int i = 0; i < iters.length; i++ ) {
tokens.put(alias[i], iters[i].next());
}
if ( foreachContext.getCount() != 0 ) {
sbuf.append( foreachContext.getSeperator() );
}
foreachContext.setCount( foreachContext.getCount( ) + 1 );
}
else {
for ( int i = 0; i < iters.length; i++ ) {
tokens.remove(alias[i]);
}
foreachContext.setIterators( null );
foreachContext.setCount( 0 );
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length == 2) {
return register;
}
else {
return sbuf.toString();
}
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}", e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
// return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens);
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, MVEL.compileExpression(s));
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
ExpressionParser oParser = new ExpressionParser(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
String seperator = "";
if (currNode.getRegister() == null || currNode.getRegister() instanceof String) {
try {
String props = ( String) currNode.getRegister();
if ( props != null && props.length() > 0 ) {
seperator = props;
}
String[] lists = getForEachSegment(currNode).split( "," );
Iterator[] iters = new Iterator[lists.length];
for( int i = 0; i < lists.length; i++ ) {
Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse();
if ( listObject instanceof Object[]) {
listObject = Arrays.asList( (Object[]) listObject );
}
iters[i] = ((Collection)listObject).iterator() ;
}
currNode.setRegister( iters );
} catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = (Iterator[]) currNode.getRegister();
String[] alias = currNode.getAlias().split( "," );
// must trim vars
for ( int i = 0; i < alias.length; i++ ) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for ( int i = 0; i < iters.length; i++ ) {
tokens.put(alias[i], iters[i].next());
}
sbuf.append( seperator );
}
else {
for ( int i = 0; i < iters.length; i++ ) {
tokens.remove(alias[i]);
}
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length == 2) {
return register;
}
else {
return sbuf.toString();
}
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}", e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 93
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
synchronized (Runtime.getRuntime()) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 122
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@SuppressWarnings({"unchecked"})
private Object getMethod(Object ctx, String name) throws Exception {
int st = cursor;
String tk = cursor != length
&& expr[cursor] == '(' && ((cursor = balancedCapture(expr, cursor, '(')) - st) > 1 ?
new String(expr, st + 1, cursor - st - 1) : "";
cursor++;
Object[] args;
Accessor[] es;
if (tk.length() == 0) {
args = ParseTools.EMPTY_OBJ_ARR;
es = null;
}
else {
String[] subtokens = parseParameterList(tk.toCharArray(), 0, -1);
es = new ExecutableStatement[subtokens.length];
args = new Object[subtokens.length];
for (int i = 0; i < subtokens.length; i++) {
args[i] = (es[i] = (ExecutableStatement) subCompileExpression(subtokens[i].toCharArray()))
.getValue(this.ctx, thisRef, variableFactory);
}
}
if (first && variableFactory != null && variableFactory.isResolveable(name)) {
Object ptr = variableFactory.getVariableResolver(name).getValue();
if (ptr instanceof Method) {
ctx = ((Method) ptr).getDeclaringClass();
name = ((Method) ptr).getName();
}
else if (ptr instanceof MethodStub) {
ctx = ((MethodStub) ptr).getClassReference();
name = ((MethodStub) ptr).getMethodName();
}
else if (ptr instanceof Function) {
addAccessorNode(new FunctionAccessor((Function) ptr, es));
Object[] parm = null;
if (es != null) {
parm = new Object[es.length];
for (int i = 0; i < es.length; i++) {
parm[i] = es[i].getValue(ctx, thisRef, variableFactory);
}
}
return ((Function) ptr).call(ctx, thisRef, variableFactory, parm);
}
else {
throw new OptimizationFailure("attempt to optimize a method call for a reference that does not point to a method: "
+ name + " (reference is type: " + (ctx != null ? ctx.getClass().getName() : null) + ")");
}
first = false;
}
if (ctx == null) throw new PropertyAccessException("unable to access property (null parent): " + name);
/**
* If the target object is an instance of java.lang.Class itself then do not
* adjust the Class scope target.
*/
Class<?> cls = ctx instanceof Class ? (Class<?>) ctx : ctx.getClass();
Method m;
Class[] parameterTypes = null;
/**
* If we have not cached the method then we need to go ahead and try to resolve it.
*/
/**
* Try to find an instance method from the class target.
*/
if ((m = getBestCandidate(args, name, cls, cls.getMethods(), false)) != null) {
parameterTypes = m.getParameterTypes();
}
if (m == null) {
/**
* If we didn't find anything, maybe we're looking for the actual java.lang.Class methods.
*/
if ((m = getBestCandidate(args, name, cls, cls.getClass().getDeclaredMethods(), false)) != null) {
parameterTypes = m.getParameterTypes();
}
}
if (m == null) {
StringAppender errorBuild = new StringAppender();
for (int i = 0; i < args.length; i++) {
errorBuild.append(args[i] != null ? args[i].getClass().getName() : null);
if (i < args.length - 1) errorBuild.append(", ");
}
if ("size".equals(name) && args.length == 0 && cls.isArray()) {
addAccessorNode(new ArrayLength());
return getLength(ctx);
}
throw new PropertyAccessException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]");
}
else {
if (es != null) {
ExecutableStatement cExpr;
for (int i = 0; i < es.length; i++) {
cExpr = (ExecutableStatement) es[i];
if (cExpr.getKnownIngressType() == null) {
cExpr.setKnownIngressType(parameterTypes[i]);
cExpr.computeTypeConversionRule();
}
if (!cExpr.isConvertableIngressEgress()) {
args[i] = convert(args[i], parameterTypes[i]);
}
}
}
else {
/**
* Coerce any types if required.
*/
for (int i = 0; i < args.length; i++)
args[i] = convert(args[i], parameterTypes[i]);
}
addAccessorNode(new MethodAccessor(getWidenedTarget(m), (ExecutableStatement[]) es));
/**
* Invoke the target method and return the response.
*/
return m.invoke(ctx, args);
}
} | #vulnerable code
@SuppressWarnings({"unchecked"})
private Object getMethod(Object ctx, String name) throws Exception {
int st = cursor;
String tk = cursor != length
&& expr[cursor] == '(' && ((cursor = balancedCapture(expr, cursor, '(')) - st) > 1 ?
new String(expr, st + 1, cursor - st - 1) : "";
cursor++;
Object[] args;
Accessor[] es;
if (tk.length() == 0) {
args = ParseTools.EMPTY_OBJ_ARR;
es = null;
}
else {
String[] subtokens = parseParameterList(tk.toCharArray(), 0, -1);
es = new ExecutableStatement[subtokens.length];
args = new Object[subtokens.length];
for (int i = 0; i < subtokens.length; i++) {
args[i] = (es[i] = (ExecutableStatement) subCompileExpression(subtokens[i].toCharArray()))
.getValue(this.ctx, thisRef, variableFactory);
}
}
if (first && variableFactory != null && variableFactory.isResolveable(name)) {
Object ptr = variableFactory.getVariableResolver(name).getValue();
if (ptr instanceof Method) {
ctx = ((Method) ptr).getDeclaringClass();
name = ((Method) ptr).getName();
}
else if (ptr instanceof MethodStub) {
ctx = ((MethodStub) ptr).getClassReference();
name = ((MethodStub) ptr).getMethodName();
}
else if (ptr instanceof Function) {
addAccessorNode(new FunctionAccessor((Function) ptr, es));
Object[] parm = null;
if (es != null) {
parm = new Object[es.length];
for (int i = 0; i < es.length; i++) {
parm[i] = es[i].getValue(ctx, thisRef, variableFactory);
}
}
return ((Function) ptr).call(ctx, thisRef, variableFactory, parm);
}
else {
throw new OptimizationFailure("attempt to optimize a method call for a reference that does not point to a method: "
+ name + " (reference is type: " + (ctx != null ? ctx.getClass().getName() : null) + ")");
}
first = false;
}
/**
* If the target object is an instance of java.lang.Class itself then do not
* adjust the Class scope target.
*/
Class<?> cls = ctx == null || ctx instanceof Class ? (Class<?>) ctx : ctx.getClass();
Method m;
Class[] parameterTypes = null;
/**
* If we have not cached the method then we need to go ahead and try to resolve it.
*/
/**
* Try to find an instance method from the class target.
*/
if ((m = getBestCandidate(args, name, cls, cls.getMethods(), false)) != null) {
parameterTypes = m.getParameterTypes();
}
if (m == null) {
/**
* If we didn't find anything, maybe we're looking for the actual java.lang.Class methods.
*/
if ((m = getBestCandidate(args, name, cls, cls.getClass().getDeclaredMethods(), false)) != null) {
parameterTypes = m.getParameterTypes();
}
}
if (m == null) {
StringAppender errorBuild = new StringAppender();
for (int i = 0; i < args.length; i++) {
errorBuild.append(args[i] != null ? args[i].getClass().getName() : null);
if (i < args.length - 1) errorBuild.append(", ");
}
if ("size".equals(name) && args.length == 0 && cls.isArray()) {
addAccessorNode(new ArrayLength());
return getLength(ctx);
}
throw new PropertyAccessException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]");
}
else {
if (es != null) {
ExecutableStatement cExpr;
for (int i = 0; i < es.length; i++) {
cExpr = (ExecutableStatement) es[i];
if (cExpr.getKnownIngressType() == null) {
cExpr.setKnownIngressType(parameterTypes[i]);
cExpr.computeTypeConversionRule();
}
if (!cExpr.isConvertableIngressEgress()) {
args[i] = convert(args[i], parameterTypes[i]);
}
}
}
else {
/**
* Coerce any types if required.
*/
for (int i = 0; i < args.length; i++)
args[i] = convert(args[i], parameterTypes[i]);
}
addAccessorNode(new MethodAccessor(getWidenedTarget(m), (ExecutableStatement[]) es));
/**
* Invoke the target method and return the response.
*/
return m.invoke(ctx, args);
}
}
#location 72
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (CACHE_DISABLE || !cacheAggressively) {
char[] seg = new char[expression.length - 3];
// arraycopy(expression, 2, seg, 0, seg.length);
for (int i = 0; i < seg.length; i++)
seg[i] = expression[i + 2];
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
if (tokens == null) {
tokens = new HashMap();
}
ForeachContext foreachContext;
String[] names;
String[] aliases;
if (!(localStack.peek() instanceof ForeachContext)) {
// create a clone of the context
foreachContext = ((ForeachContext) currNode.getRegister()).clone();
names = foreachContext.getNames();
aliases = foreachContext.getAliases();
try {
Iterator[] iters = new Iterator[names.length];
for (int i = 0; i < names.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(names[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator(); // this throws null pointer exception in thread race
}
// set the newly created iterators into the context
foreachContext.setIterators(iters);
// push the context onto the local stack.
localStack.push(foreachContext);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)), e);
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)), e);
}
}
else {
foreachContext = (ForeachContext) localStack.peek();
// names = foreachContext.getNames();
aliases = foreachContext.getAliases();
}
Iterator[] iters = foreachContext.getItererators();
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(aliases[i], iters[i].next());
}
int c;
tokens.put("i0", c = foreachContext.getCount());
if (c != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
foreachContext.incrementCount();
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(aliases[i]);
}
// foreachContext.setIterators(null);
// foreachContext.setCount(0);
localStack.pop();
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (CACHE_DISABLE || !cacheAggressively) {
char[] seg = new char[expression.length - 3];
// arraycopy(expression, 2, seg, 0, seg.length);
for (int i = 0; i < seg.length; i++)
seg[i] = expression[i + 2];
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
if (tokens == null) {
tokens = new HashMap();
}
ForeachContext foreachContext;
if (!(localStack.peek() instanceof ForeachContext)) {
foreachContext = ((ForeachContext) currNode.getRegister()).clone();
// if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
localStack.push(foreachContext);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
foreachContext = (ForeachContext) localStack.peek();
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
localStack.pop();
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 118
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
synchronized (Runtime.getRuntime()) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 139
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (CACHE_DISABLE || !cacheAggressively) {
char[] seg = new char[expression.length - 3];
// arraycopy(expression, 2, seg, 0, seg.length);
for (int i = 0; i < seg.length; i++)
seg[i] = expression[i + 2];
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
if (tokens == null) {
tokens = new HashMap();
}
ForeachContext foreachContext;
String[] names;
String[] aliases;
if (!(localStack.peek() instanceof ForeachContext)) {
// create a clone of the context
foreachContext = ((ForeachContext) currNode.getRegister()).clone();
names = foreachContext.getNames();
aliases = foreachContext.getAliases();
try {
Iterator[] iters = new Iterator[names.length];
for (int i = 0; i < names.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(names[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator(); // this throws null pointer exception in thread race
}
// set the newly created iterators into the context
foreachContext.setIterators(iters);
// push the context onto the local stack.
localStack.push(foreachContext);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)), e);
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)), e);
}
}
else {
foreachContext = (ForeachContext) localStack.peek();
// names = foreachContext.getNames();
aliases = foreachContext.getAliases();
}
Iterator[] iters = foreachContext.getItererators();
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(aliases[i], iters[i].next());
}
int c;
tokens.put("i0", c = foreachContext.getCount());
if (c != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
foreachContext.incrementCount();
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(aliases[i]);
}
// foreachContext.setIterators(null);
// foreachContext.setCount(0);
localStack.pop();
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (CACHE_DISABLE || !cacheAggressively) {
char[] seg = new char[expression.length - 3];
// arraycopy(expression, 2, seg, 0, seg.length);
for (int i = 0; i < seg.length; i++)
seg[i] = expression[i + 2];
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
if (tokens == null) {
tokens = new HashMap();
}
ForeachContext foreachContext;
if (!(localStack.peek() instanceof ForeachContext)) {
foreachContext = ((ForeachContext) currNode.getRegister()).clone();
// if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
localStack.push(foreachContext);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
foreachContext = (ForeachContext) localStack.peek();
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
localStack.pop();
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 122
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
if (prop.length() != 0) {
ctx = getBeanProperty(ctx, prop);
}
int start = ++cursor;
whiteSpaceSkip();
if (cursor == length || scanTo(']'))
throw new PropertyAccessException("unterminated '['");
prop = new String(property, start, cursor++ - start);
if (ctx instanceof Map) {
return ((Map) ctx).get(eval(prop, ctx, variableFactory));
}
else if (ctx instanceof List) {
return ((List) ctx).get((Integer) eval(prop, ctx, variableFactory));
}
else if (ctx instanceof Collection) {
int count = (Integer) eval(prop, ctx, variableFactory);
if (count > ((Collection) ctx).size())
throw new PropertyAccessException("index [" + count + "] out of bounds on collections");
Iterator iter = ((Collection) ctx).iterator();
for (int i = 0; i < count; i++) iter.next();
return iter.next();
}
else if (ctx.getClass().isArray()) {
return Array.get(ctx, (Integer) eval(prop, ctx, variableFactory));
}
else if (ctx instanceof CharSequence) {
return ((CharSequence) ctx).charAt((Integer) eval(prop, ctx, variableFactory));
}
else {
throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()));
}
} | #vulnerable code
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
if (prop.length() != 0) {
ctx = getBeanProperty(ctx, prop);
}
int start = ++cursor;
whiteSpaceSkip();
if (cursor == length)
throw new PropertyAccessException("unterminated '['");
Object item;
if (scanTo(']'))
throw new PropertyAccessException("unterminated '['");
// String ex = new String(property, start, cursor++ - start);
item = eval(new String(property, start, cursor++ - start), ctx, variableFactory);
if (ctx instanceof Map) {
return ((Map) ctx).get(item);
}
else if (ctx instanceof List) {
return ((List) ctx).get((Integer) item);
}
else if (ctx instanceof Collection) {
int count = (Integer) item;
if (count > ((Collection) ctx).size())
throw new PropertyAccessException("index [" + count + "] out of bounds on collections");
Iterator iter = ((Collection) ctx).iterator();
for (int i = 0; i < count; i++) iter.next();
return iter.next();
}
else if (ctx.getClass().isArray()) {
return Array.get(ctx, (Integer) item);
}
else if (ctx instanceof CharSequence) {
return ((CharSequence) ctx).charAt((Integer) item);
}
else {
throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()));
}
}
#location 40
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
protected ASTNode nextToken() {
/**
* If the cursor is at the end of the expression, we have nothing more to do:
* return null.
*/
if (cursor >= length) {
return null;
}
else if (!splitAccumulator.isEmpty()) {
return lastNode = (ASTNode) splitAccumulator.pop();
}
int brace, start = cursor;
/**
* Because of parser recursion for sub-expression parsing, we sometimes need to remain
* certain field states. We do not reset for assignments, boolean mode, list creation or
* a capture only mode.
*/
fields = fields & (ASTNode.INLINE_COLLECTION | ASTNode.COMPILE_IMMEDIATE);
boolean capture = false, union = false;
if (debugSymbols) {
if (!lastWasLineLabel) {
if (getParserContext().getSourceFile() == null) {
throw new CompileException("unable to produce debugging symbols: source name must be provided.");
}
ParserContext pCtx = getParserContext();
line = pCtx.getLineCount();
if (expr[cursor] == '\n' || expr[cursor] == '\r') {
skipWhitespaceWithLineAccounting();
}
if (lastWasComment) {
line++;
lastWasComment = false;
}
pCtx.setLineCount(line);
if (!pCtx.isKnownLine(pCtx.getSourceFile(), line)) {
lastWasLineLabel = true;
pCtx.setLineAndOffset(line, cursor);
pCtx.addKnownLine(pCtx.getSourceFile(), line);
LineLabel ll = new LineLabel(pCtx.getSourceFile(), line);
if (pCtx.getFirstLineLabel() == null) pCtx.setFirstLineLabel(ll);
return lastNode = ll;
}
}
else {
lastWasComment = lastWasLineLabel = false;
}
}
/**
* Skip any whitespace currently under the starting point.
*/
while (start < length && isWhitespace(expr[start])) start++;
/**
* From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for
* trouble unless you really know what you're doing.
*/
for (cursor = start; cursor < length;) {
if (isIdentifierPart(expr[cursor])) {
/**
* If the current character under the cursor is a valid
* part of an identifier, we keep capturing.
*/
capture = true;
cursor++;
}
else if (capture) {
String t;
if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) {
switch (OPERATORS.get(t)) {
case NEW:
start = cursor + 1;
captureToEOT();
return new NewObjectNode(subArray(start, cursor), fields);
case ASSERT:
start = cursor + 1;
captureToEOS();
return new AssertNode(subArray(start, cursor--), fields);
case RETURN:
start = cursor + 1;
captureToEOS();
return new ReturnNode(subArray(start, cursor), fields);
case IF:
fields |= ASTNode.BLOCK_IF;
return captureCodeBlock();
case FOREACH:
fields |= ASTNode.BLOCK_FOREACH;
return captureCodeBlock();
case WITH:
fields |= ASTNode.BLOCK_WITH;
return captureCodeBlock();
case IMPORT:
start = cursor + 1;
captureToEOS();
ImportNode importNode = new ImportNode(subArray(start, cursor--), fields);
getParserContext().addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass());
return importNode;
case IMPORT_STATIC:
start = cursor + 1;
captureToEOS();
return new StaticImportNode(subArray(start, cursor--), fields);
}
}
/**
* If we *were* capturing a token, and we just hit a non-identifier
* character, we stop and figure out what to do.
*/
skipWhitespace();
if (expr[cursor] == '(') {
fields |= ASTNode.METHOD;
/**
* If the current token is a method call or a constructor, we
* simply capture the entire parenthesized range and allow
* reduction to be dealt with through sub-parsing the property.
*/
cursor++;
for (brace = 1; cursor < length && brace > 0;) {
switch (expr[cursor++]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length) + 1;
break;
case'"':
cursor = captureStringLiteral('"', expr, cursor, length) + 1;
break;
}
}
/**
* If the brace counter is greater than 0, we know we have
* unbalanced braces in the expression. So we throw a
* optimize error now.
*/
if (brace > 0)
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
/**
* If we encounter any of the following cases, we are still dealing with
* a contiguous token.
*/
String name;
if (cursor < length) {
switch (expr[cursor]) {
case'+':
switch (lookAhead(1)) {
case'+':
ASTNode n = new PostFixIncNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields, Operator.ADD, t);
}
else {
return new AssignmentNode(subArray(start, cursor), fields, Operator.ADD, name);
}
}
break;
case'-':
switch (lookAhead(1)) {
case'-':
ASTNode n = new PostFixDecNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignSub(subArray(start, cursor), fields, name);
}
break;
case'*':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignMult(subArray(start, cursor), fields, name);
}
break;
case'/':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignDiv(subArray(start, cursor), fields, name);
}
break;
case']':
case'[':
balancedCapture('[');
cursor++;
continue;
case'.':
union = true;
cursor++;
continue;
case'~':
if (isAt('=', 1)) {
char[] stmt = subArray(start, trimLeft(cursor));
start = cursor += 2;
captureToEOT();
return new RegExMatch(stmt, fields, subArray(start, cursor));
}
break;
case'=':
if (isAt('+', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignAdd(subArray(start, cursor), fields, name);
}
if (greedy && !isAt('=', 1)) {
cursor++;
fields |= ASTNode.ASSIGN;
skipWhitespace();
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields);
}
else if (lastWasIdentifier) {
/**
* Check for typing information.
*/
if (lastNode.getLiteralValue() instanceof String) {
if (getParserContext().hasImport((String) lastNode.getLiteralValue())) {
lastNode.setLiteralValue(getParserContext().getImport((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
else {
try {
/**
* take a stab in the dark and try and load the class
*/
lastNode.setLiteralValue(createClass((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) {
lastNode.setDiscard(true);
captureToEOS();
return new TypedVarNode(subArray(start, cursor), fields, (Class)
lastNode.getLiteralValue());
}
throw new ParseException("unknown class: " + lastNode.getLiteralValue());
}
else {
return new AssignmentNode(subArray(start, cursor), fields);
}
}
}
}
/**
* Produce the token.
*/
trimWhitespace();
return createPropertyToken(start, cursor);
}
else
switch (expr[cursor]) {
case'@': {
start++;
captureToEOT();
String interceptorName = new String(expr, start, cursor - start);
if (getParserContext().getInterceptors() == null || !getParserContext().getInterceptors().
containsKey(interceptorName)) {
throw new CompileException("reference to undefined interceptor: " + interceptorName, expr, cursor);
}
return new InterceptorWrapper(getParserContext().getInterceptors().get(interceptorName), nextToken());
}
case'=':
return createToken(expr, start, (cursor += 2), fields);
case'-':
if (isAt('-', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixDecNode(subArray(start, cursor), fields);
}
else if ((cursor > 0 && !isWhitespace(lookBehind(1))) || !isDigit(lookAhead(1))) {
return createToken(expr, start, cursor++ + 1, fields);
}
else if ((cursor - 1) < 0 || (!isDigit(lookBehind(1))) && isDigit(lookAhead(1))) {
cursor++;
break;
}
case'+':
if (isAt('+', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixIncNode(subArray(start, cursor), fields);
}
return createToken(expr, start, cursor++ + 1, fields);
case'*':
if (isAt('*', 1)) {
cursor++;
}
return createToken(expr, start, cursor++ + 1, fields);
case';':
cursor++;
lastWasIdentifier = false;
return lastNode = new EndOfStatement();
case'#':
case'/':
if (isAt(expr[cursor], 1)) {
/**
* Handle single line comments.
*/
while (cursor < length && expr[cursor] != '\n') cursor++;
if (debugSymbols) {
line = getParserContext().getLineCount();
skipWhitespaceWithLineAccounting();
if (lastNode instanceof LineLabel) {
getParserContext().getFirstLineLabel().setLineNumber(line);
}
lastWasComment = true;
getParserContext().setLineCount(line);
}
else if (cursor < length) {
skipWhitespace();
}
if ((start = cursor) >= length) return null;
continue;
}
else if (expr[cursor] == '/' && isAt('*', 1)) {
/**
* Handle multi-line comments.
*/
int len = length - 1;
/**
* This probably seems highly redundant, but sub-compilations within the same
* source will spawn a new compiler, and we need to sync this with the
* parser context;
*/
if (debugSymbols) {
line = getParserContext().getLineCount();
}
while (true) {
cursor++;
/**
* Since multi-line comments may cross lines, we must keep track of any line-break
* we encounter.
*/
// if (debugSymbols && expr[cursor] == '\n') {
// line++;
// }
if (debugSymbols && (expr[cursor] == '\n' || expr[cursor] == '\r')) {
skipWhitespaceWithLineAccounting();
}
if (cursor == len) {
throw new CompileException("unterminated block comment", expr, cursor);
}
if (expr[cursor] == '*' && isAt('/', 1)) {
if ((cursor += 2) >= length) return null;
skipWhitespace();
start = cursor;
break;
}
}
if (debugSymbols) {
getParserContext().setLineCount(line);
if (lastNode instanceof LineLabel) {
getParserContext().getFirstLineLabel().setLineNumber(line);
}
lastWasComment = true;
}
continue;
}
case'?':
case':':
case'^':
case'%': {
return createToken(expr, start, cursor++ + 1, fields);
}
case'(': {
cursor++;
boolean singleToken = true;
boolean lastWS = false;
skipWhitespace();
for (brace = 1; cursor < length && brace > 0; cursor++) {
switch (expr[cursor]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'"':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'i':
if (isAt('n', 1) && isWhitespace(lookAhead(2))) {
fields |= ASTNode.FOLD;
for (int level = brace; cursor < length; cursor++) {
switch (expr[cursor]) {
case'(':
brace++;
break;
case')':
if (--brace < level) {
if (lookAhead(1) == '.') {
ASTNode node = createToken(expr, trimRight(start), (start = cursor++), ASTNode.FOLD);
captureToEOT();
return new Union(expr, trimRight(start + 2), cursor, fields, node);
}
else {
return createToken(expr, trimRight(start), cursor++, ASTNode.FOLD);
}
}
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'"':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
}
}
}
break;
default:
/**
* Check to see if we should disqualify this current token as a potential
* type-cast candidate.
*/
if (lastWS || !isIdentifierPart(expr[cursor])) {
singleToken = false;
}
else if (isWhitespace(expr[cursor])) {
lastWS = true;
skipWhitespace();
cursor--;
}
}
}
if (brace > 0) {
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
char[] _subset = null;
if (singleToken) {
String tokenStr = new String(_subset = subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)));
if (getParserContext().hasImport(tokenStr)) {
start = cursor;
captureToEOS();
return new TypeCast(expr, start, cursor, fields, getParserContext().getImport(tokenStr));
}
else {
try {
/**
*
* take a stab in the dark and try and load the class
*/
int _start = cursor;
captureToEOS();
return new TypeCast(expr, _start, cursor, fields, createClass(tokenStr));
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if (_subset != null) {
return handleUnion(new Substatement(_subset, fields));
}
else {
return handleUnion(new Substatement(subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)), fields));
}
}
case'}':
case']':
case')': {
throw new ParseException("unbalanced braces", expr, cursor);
}
case'>': {
if (expr[cursor + 1] == '>') {
if (expr[cursor += 2] == '>') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor + 1] == '=') {
return createToken(expr, start, cursor += 2, fields);
}
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'<': {
if (expr[++cursor] == '<') {
if (expr[++cursor] == '<') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor] == '=') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'"':
cursor = captureStringLiteral('"', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'&': {
if (expr[cursor++ + 1] == '&') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'|': {
if (expr[cursor++ + 1] == '|') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'~':
if ((cursor - 1 < 0 || !isIdentifierPart(lookBehind(1)))
&& isDigit(expr[cursor + 1])) {
fields |= ASTNode.INVERT;
start++;
cursor++;
break;
}
else if (expr[cursor + 1] == '(') {
fields |= ASTNode.INVERT;
start = ++cursor;
continue;
}
else {
if (expr[cursor + 1] == '=') cursor++;
return createToken(expr, start, ++cursor, fields);
}
case'!': {
if (isIdentifierPart(expr[++cursor]) || expr[cursor] == '(') {
start = cursor;
fields |= ASTNode.NEGATION;
continue;
}
else if (expr[cursor] != '=')
throw new CompileException("unexpected operator '!'", expr, cursor, null);
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'[':
case'{':
if (balancedCapture(expr[cursor]) == -1) {
if (cursor >= length) cursor--;
throw new CompileException("unbalanced brace: in inline map/list/array creation", expr, cursor);
}
if (lookAhead(1) == '.') {
InlineCollectionNode n = new InlineCollectionNode(expr, start, start = ++cursor, fields);
captureToEOT();
return new Union(expr, start + 1, cursor, fields, n);
}
else {
return new InlineCollectionNode(expr, start, ++cursor, fields);
}
default:
cursor++;
}
}
return createPropertyToken(start, cursor);
} | #vulnerable code
protected ASTNode nextToken() {
/**
* If the cursor is at the end of the expression, we have nothing more to do:
* return null.
*/
if (cursor >= length) {
return null;
}
else if (!splitAccumulator.isEmpty()) {
return lastNode = (ASTNode) splitAccumulator.pop();
}
int brace, start = cursor;
/**
* Because of parser recursion for sub-expression parsing, we sometimes need to remain
* certain field states. We do not reset for assignments, boolean mode, list creation or
* a capture only mode.
*/
fields = fields & (ASTNode.INLINE_COLLECTION | ASTNode.COMPILE_IMMEDIATE);
boolean capture = false, union = false;
if (debugSymbols) {
if (!lastWasLineLabel) {
if (getParserContext().getSourceFile() == null) {
throw new CompileException("unable to produce debugging symbols: source name must be provided.");
}
ParserContext pCtx = getParserContext();
line = pCtx.getLineCount();
if (expr[cursor] == '\n' || expr[cursor] == '\r') {
skipWhitespaceWithLineAccounting();
}
if (lastWasComment) {
line++;
lastWasComment = false;
}
pCtx.setLineCount(line);
if (!pCtx.isKnownLine(pCtx.getSourceFile(), line)) {
lastWasLineLabel = true;
pCtx.setLineAndOffset(line, cursor);
pCtx.addKnownLine(pCtx.getSourceFile(), line);
LineLabel ll = new LineLabel(pCtx.getSourceFile(), line);
if (pCtx.getFirstLineLabel() == null) pCtx.setFirstLineLabel(ll);
return lastNode = ll;
}
}
else {
lastWasComment = lastWasLineLabel = false;
}
}
/**
* Skip any whitespace currently under the starting point.
*/
while (start < length && isWhitespace(expr[start])) start++;
/**
* From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for
* trouble unless you really know what you're doing.
*/
for (cursor = start; cursor < length;) {
if (isIdentifierPart(expr[cursor])) {
/**
* If the current character under the cursor is a valid
* part of an identifier, we keep capturing.
*/
capture = true;
cursor++;
}
else if (capture) {
String t;
if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) {
switch (OPERATORS.get(t)) {
case NEW:
start = cursor + 1;
captureToEOT();
return new NewObjectNode(subArray(start, cursor), fields);
case ASSERT:
start = cursor + 1;
captureToEOS();
return new AssertNode(subArray(start, cursor--), fields);
case RETURN:
start = cursor + 1;
captureToEOS();
return new ReturnNode(subArray(start, cursor), fields);
case IF:
fields |= ASTNode.BLOCK_IF;
return captureCodeBlock();
case FOREACH:
fields |= ASTNode.BLOCK_FOREACH;
return captureCodeBlock();
case WITH:
fields |= ASTNode.BLOCK_WITH;
return captureCodeBlock();
case IMPORT:
start = cursor + 1;
captureToEOS();
ImportNode importNode = new ImportNode(subArray(start, cursor--), fields);
getParserContext().addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass());
return importNode;
case IMPORT_STATIC:
start = cursor + 1;
captureToEOS();
return new StaticImportNode(subArray(start, cursor--), fields);
}
}
/**
* If we *were* capturing a token, and we just hit a non-identifier
* character, we stop and figure out what to do.
*/
skipWhitespace();
if (expr[cursor] == '(') {
fields |= ASTNode.METHOD;
/**
* If the current token is a method call or a constructor, we
* simply capture the entire parenthesized range and allow
* reduction to be dealt with through sub-parsing the property.
*/
cursor++;
for (brace = 1; cursor < length && brace > 0;) {
switch (expr[cursor++]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length) + 1;
break;
case'"':
cursor = captureStringLiteral('"', expr, cursor, length) + 1;
break;
}
}
/**
* If the brace counter is greater than 0, we know we have
* unbalanced braces in the expression. So we throw a
* optimize error now.
*/
if (brace > 0)
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
/**
* If we encounter any of the following cases, we are still dealing with
* a contiguous token.
*/
String name;
if (cursor < length) {
switch (expr[cursor]) {
case'+':
switch (lookAhead(1)) {
case'+':
ASTNode n = new PostFixIncNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields, Operator.ADD, t);
}
else {
return new AssignmentNode(subArray(start, cursor), fields, Operator.ADD, name);
}
}
break;
case'-':
switch (lookAhead(1)) {
case'-':
ASTNode n = new PostFixDecNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignSub(subArray(start, cursor), fields, name);
}
break;
case'*':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignMult(subArray(start, cursor), fields, name);
}
break;
case'/':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignDiv(subArray(start, cursor), fields, name);
}
break;
case']':
case'[':
balancedCapture('[');
cursor++;
continue;
case'.':
union = true;
cursor++;
continue;
case'~':
if (isAt('=', 1)) {
char[] stmt = subArray(start, trimLeft(cursor));
start = cursor += 2;
captureToEOT();
return new RegExMatch(stmt, fields, subArray(start, cursor));
}
break;
case'=':
if (isAt('+', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignAdd(subArray(start, cursor), fields, name);
}
if (greedy && !isAt('=', 1)) {
cursor++;
fields |= ASTNode.ASSIGN;
skipWhitespace();
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields);
}
else if (lastWasIdentifier) {
/**
* Check for typing information.
*/
if (lastNode.getLiteralValue() instanceof String) {
if (getParserContext().hasImport((String) lastNode.getLiteralValue())) {
lastNode.setLiteralValue(getParserContext().getImport((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
else {
try {
/**
* take a stab in the dark and try and load the class
*/
lastNode.setLiteralValue(createClass((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) {
lastNode.setDiscard(true);
captureToEOS();
return new TypedVarNode(subArray(start, cursor), fields, (Class)
lastNode.getLiteralValue());
}
throw new ParseException("unknown class: " + lastNode.getLiteralValue());
}
else {
return new AssignmentNode(subArray(start, cursor), fields);
}
}
}
}
/**
* Produce the token.
*/
trimWhitespace();
if (parserContext != null && parserContext.get() != null && parserContext.get().hasImports()) {
char[] _subset = subset(expr, start, cursor - start);
int offset;
if ((offset = findFirst('.', _subset)) != -1) {
String iStr = new String(_subset, 0, offset);
if ("this".equals(iStr)) {
lastWasIdentifier = true;
return lastNode = new ThisValDeepPropertyNode(subset(_subset, offset + 1, _subset.length - offset - 1), fields);
}
else if (getParserContext().hasImport(iStr)) {
lastWasIdentifier = true;
return lastNode = new LiteralDeepPropertyNode(subset(_subset, offset + 1, _subset.length - offset - 1), fields, getParserContext().getImport(iStr));
}
}
else {
ASTNode node = new ASTNode(_subset, 0, _subset.length, fields);
lastWasIdentifier = node.isIdentifier();
return lastNode = node;
}
}
// return createPropertyToken(expr, start, cursor, fields);
lastWasIdentifier = true;
lastNode = createPropertyToken(start, cursor);
return lastNode;
}
else
switch (expr[cursor]) {
case'@': {
start++;
captureToEOT();
String interceptorName = new String(expr, start, cursor - start);
if (getParserContext().getInterceptors() == null || !getParserContext().getInterceptors().
containsKey(interceptorName)) {
throw new CompileException("reference to undefined interceptor: " + interceptorName, expr, cursor);
}
return new InterceptorWrapper(getParserContext().getInterceptors().get(interceptorName), nextToken());
}
case'=':
return createToken(expr, start, (cursor += 2), fields);
case'-':
if (isAt('-', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixDecNode(subArray(start, cursor), fields);
}
else if ((cursor > 0 && !isWhitespace(lookBehind(1))) || !isDigit(lookAhead(1))) {
return createToken(expr, start, cursor++ + 1, fields);
}
else if ((cursor - 1) < 0 || (!isDigit(lookBehind(1))) && isDigit(lookAhead(1))) {
cursor++;
break;
}
case'+':
if (isAt('+', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixIncNode(subArray(start, cursor), fields);
}
return createToken(expr, start, cursor++ + 1, fields);
case'*':
if (isAt('*', 1)) {
cursor++;
}
return createToken(expr, start, cursor++ + 1, fields);
case';':
cursor++;
lastWasIdentifier = false;
return lastNode = new EndOfStatement();
case'#':
case'/':
if (isAt(expr[cursor], 1)) {
/**
* Handle single line comments.
*/
while (cursor < length && expr[cursor] != '\n') cursor++;
if (debugSymbols) {
line = getParserContext().getLineCount();
skipWhitespaceWithLineAccounting();
if (lastNode instanceof LineLabel) {
getParserContext().getFirstLineLabel().setLineNumber(line);
}
lastWasComment = true;
getParserContext().setLineCount(line);
}
else if (cursor < length) {
skipWhitespace();
}
if ((start = cursor) >= length) return null;
continue;
}
else if (expr[cursor] == '/' && isAt('*', 1)) {
/**
* Handle multi-line comments.
*/
int len = length - 1;
/**
* This probably seems highly redundant, but sub-compilations within the same
* source will spawn a new compiler, and we need to sync this with the
* parser context;
*/
if (debugSymbols) {
line = getParserContext().getLineCount();
}
while (true) {
cursor++;
/**
* Since multi-line comments may cross lines, we must keep track of any line-break
* we encounter.
*/
// if (debugSymbols && expr[cursor] == '\n') {
// line++;
// }
if (debugSymbols && (expr[cursor] == '\n' || expr[cursor] == '\r')) {
skipWhitespaceWithLineAccounting();
}
if (cursor == len) {
throw new CompileException("unterminated block comment", expr, cursor);
}
if (expr[cursor] == '*' && isAt('/', 1)) {
if ((cursor += 2) >= length) return null;
skipWhitespace();
start = cursor;
break;
}
}
if (debugSymbols) {
getParserContext().setLineCount(line);
if (lastNode instanceof LineLabel) {
getParserContext().getFirstLineLabel().setLineNumber(line);
}
lastWasComment = true;
}
continue;
}
case'?':
case':':
case'^':
case'%': {
return createToken(expr, start, cursor++ + 1, fields);
}
case'(': {
cursor++;
boolean singleToken = true;
boolean lastWS = false;
skipWhitespace();
for (brace = 1; cursor < length && brace > 0; cursor++) {
switch (expr[cursor]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'"':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'i':
if (isAt('n', 1) && isWhitespace(lookAhead(2))) {
fields |= ASTNode.FOLD;
for (int level = brace; cursor < length; cursor++) {
switch (expr[cursor]) {
case'(':
brace++;
break;
case')':
if (--brace < level) {
if (lookAhead(1) == '.') {
ASTNode node = createToken(expr, trimRight(start), (start = cursor++), ASTNode.FOLD);
captureToEOT();
return new Union(expr, trimRight(start + 2), cursor, fields, node);
}
else {
return createToken(expr, trimRight(start), cursor++, ASTNode.FOLD);
}
}
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'"':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
}
}
}
break;
default:
/**
* Check to see if we should disqualify this current token as a potential
* type-cast candidate.
*/
if (lastWS || !isIdentifierPart(expr[cursor])) {
singleToken = false;
}
else if (isWhitespace(expr[cursor])) {
lastWS = true;
skipWhitespace();
cursor--;
}
}
}
if (brace > 0) {
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
char[] _subset = null;
if (singleToken) {
String tokenStr = new String(_subset = subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)));
if (getParserContext().hasImport(tokenStr)) {
start = cursor;
captureToEOS();
return new TypeCast(expr, start, cursor, fields, getParserContext().getImport(tokenStr));
}
// else if (LITERALS.containsKey(tokenStr)) {
// start = cursor;
// captureToEOS();
// return new TypeCast(expr, start, cursor, fields, (Class) LITERALS.get(tokenStr));
// }
else {
try {
/**
*
* take a stab in the dark and try and load the class
*/
int _start = cursor;
captureToEOS();
return new TypeCast(expr, _start, cursor, fields, createClass(tokenStr));
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if (_subset != null) {
return handleUnion(new Substatement(_subset, fields));
}
else {
return handleUnion(new Substatement(subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)), fields));
}
}
case'}':
case']':
case')': {
throw new ParseException("unbalanced braces", expr, cursor);
}
case'>': {
if (expr[cursor + 1] == '>') {
if (expr[cursor += 2] == '>') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor + 1] == '=') {
return createToken(expr, start, cursor += 2, fields);
}
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'<': {
if (expr[++cursor] == '<') {
if (expr[++cursor] == '<') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor] == '=') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'"':
cursor = captureStringLiteral('"', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'&': {
if (expr[cursor++ + 1] == '&') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'|': {
if (expr[cursor++ + 1] == '|') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'~':
if ((cursor - 1 < 0 || !isIdentifierPart(lookBehind(1)))
&& isDigit(expr[cursor + 1])) {
fields |= ASTNode.INVERT;
start++;
cursor++;
break;
}
else if (expr[cursor + 1] == '(') {
fields |= ASTNode.INVERT;
start = ++cursor;
continue;
}
else {
if (expr[cursor + 1] == '=') cursor++;
return createToken(expr, start, ++cursor, fields);
}
case'!': {
if (isIdentifierPart(expr[++cursor]) || expr[cursor] == '(') {
start = cursor;
fields |= ASTNode.NEGATION;
continue;
}
else if (expr[cursor] != '=')
throw new CompileException("unexpected operator '!'", expr, cursor, null);
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'[':
case'{':
if (balancedCapture(expr[cursor]) == -1) {
if (cursor >= length) cursor--;
throw new CompileException("unbalanced brace: in inline map/list/array creation", expr, cursor);
}
if (lookAhead(1) == '.') {
InlineCollectionNode n = new InlineCollectionNode(expr, start, start = ++cursor, fields);
captureToEOT();
return new Union(expr, start + 1, cursor, fields, n);
}
else {
return new InlineCollectionNode(expr, start, ++cursor, fields);
}
default:
cursor++;
}
}
return createPropertyToken(start, cursor);
}
#location 318
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) {
// return Math.sqrt(DataConversion.convert(p0.getValue(ctx, variableFactory), Double.class).doubleValue());
for (Method m : Math.class.getMethods()) {
if ("sqrt".equals(m.getName())) {
return m;
}
}
return null;
} | #vulnerable code
public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) {
return Math.sqrt(DataConversion.convert(p0.getValue(ctx, variableFactory), Double.class).doubleValue());
}
#location 2
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
protected void setExpression(String expression) {
if (expression != null && !"".equals(expression)) {
synchronized (EX_PRECACHE) {
if ((this.expr = EX_PRECACHE.get(expression)) == null) {
length = (this.expr = expression.toCharArray()).length;
// trim any whitespace.
while (length != 0 && isWhitespace(this.expr[length - 1])) length--;
char[] e = new char[length];
for (int i = 0; i != e.length; i++)
e[i] = expr[i];
EX_PRECACHE.put(expression, e);
}
else {
length = this.expr.length;
}
}
}
} | #vulnerable code
protected void setExpression(String expression) {
if (expression != null && !"".equals(expression)) {
if ((this.expr = EX_PRECACHE.get(expression)) == null) {
synchronized (EX_PRECACHE) {
length = (this.expr = expression.toCharArray()).length;
// trim any whitespace.
while (length != 0 && isWhitespace(this.expr[length - 1])) length--;
char[] e = new char[length];
for (int i = 0; i != e.length; i++)
e[i] = expr[i];
EX_PRECACHE.put(expression, e);
}
}
else {
length = this.expr.length;
}
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void runTest(PerfTest test, int count) throws Exception {
int exFlags = test.getRunFlags();
String expression = test.getExpression();
String name = test.getName();
if (!silent) {
System.out.println("Test Name : " + test.getName());
System.out.println("Expression : " + test.getExpression());
System.out.println("Iterations : " + count);
}
long time;
long mem;
long total = 0;
long[] res = new long[TESTITER];
if ((testFlags & INTERPRETED) != 0) {
if (!silent) System.out.println("Interpreted Results :");
if ((testFlags & RUN_OGNL) != 0 && ((exFlags & RUN_OGNL)) != 0) {
try {
// unbenched warm-up
for (int i = 0; i < count; i++) {
// Ognl.getValue(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
// Ognl.getValue(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(OGNL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(OGNL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
ognlTotal += total;
}
total = 0;
if ((testFlags & RUN_MVEL) != 0 && ((exFlags & RUN_MVEL) != 0)) {
try {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(MVEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
e.printStackTrace();
if (!silent)
System.out.println("(MVEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
mvelTotal += total;
}
//
// total = 0;
//
// if ((testFlags & RUN_GROOVY) != 0 && ((exFlags & RUN_GROOVY) != 0)) {
// try {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
//
// time = currentTimeMillis();
// mem = Runtime.getRuntime().freeMemory();
// for (int reps = 0; reps < TESTITER; reps++) {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
// if (reps == 0) res[0] = total += currentTimeMillis() - time;
// else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
// }
//
// if (!silent)
// System.out.println("(Groovy) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
// + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
//
// }
// catch (Exception e) {
// e.printStackTrace();
//
// if (!silent)
// System.out.println("(Groovy) : <<COULD NOT EXECUTE>>");
// }
// }
//
// synchronized (this) {
// groovyTotal += total;
// }
//
total = 0;
if ((testFlags & RUN_COMMONS_EL) != 0 && ((exFlags & RUN_COMMONS_EL) != 0)) {
VariableResolver vars = new JSPMapVariableResolver(variables);
String commonsEx = "${" + expression + "}";
try {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(CommonsEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(CommonsEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
commonElTotal += total;
}
}
if ((testFlags & COMPILED) != 0) {
runTestCompiled(name, test.getOgnlCompiled(), test.getMvelCompiled(), test.getGroovyCompiled(), test.getElCompiled(), count, exFlags);
}
total = 0;
if ((testFlags & RUN_JAVA_NATIVE) != 0 && ((exFlags & RUN_JAVA_NATIVE) != 0)) {
NativeTest nt = test.getJavaNative();
try {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(JavaNative) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(JavaNative) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
javaNativeTotal += total;
}
if (!silent)
System.out.println("------------------------------------------------");
} | #vulnerable code
public void runTest(PerfTest test, int count) throws Exception {
int exFlags = test.getRunFlags();
String expression = test.getExpression();
String name = test.getName();
if (!silent) {
System.out.println("Test Name : " + test.getName());
System.out.println("Expression : " + test.getExpression());
System.out.println("Iterations : " + count);
}
long time;
long mem;
long total = 0;
long[] res = new long[TESTITER];
if ((testFlags & INTERPRETED) != 0) {
if (!silent) System.out.println("Interpreted Results :");
if ((testFlags & RUN_OGNL) != 0 && ((exFlags & RUN_OGNL)) != 0) {
try {
// unbenched warm-up
for (int i = 0; i < count; i++) {
Ognl.getValue(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
Ognl.getValue(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(OGNL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(OGNL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
ognlTotal += total;
}
total = 0;
if ((testFlags & RUN_MVEL) != 0 && ((exFlags & RUN_MVEL) != 0)) {
try {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(MVEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
e.printStackTrace();
if (!silent)
System.out.println("(MVEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
mvelTotal += total;
}
//
// total = 0;
//
// if ((testFlags & RUN_GROOVY) != 0 && ((exFlags & RUN_GROOVY) != 0)) {
// try {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
//
// time = currentTimeMillis();
// mem = Runtime.getRuntime().freeMemory();
// for (int reps = 0; reps < TESTITER; reps++) {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
// if (reps == 0) res[0] = total += currentTimeMillis() - time;
// else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
// }
//
// if (!silent)
// System.out.println("(Groovy) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
// + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
//
// }
// catch (Exception e) {
// e.printStackTrace();
//
// if (!silent)
// System.out.println("(Groovy) : <<COULD NOT EXECUTE>>");
// }
// }
//
// synchronized (this) {
// groovyTotal += total;
// }
//
total = 0;
if ((testFlags & RUN_COMMONS_EL) != 0 && ((exFlags & RUN_COMMONS_EL) != 0)) {
VariableResolver vars = new JSPMapVariableResolver(variables);
String commonsEx = "${" + expression + "}";
try {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(CommonsEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(CommonsEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
commonElTotal += total;
}
}
if ((testFlags & COMPILED) != 0) {
runTestCompiled(name, test.getOgnlCompiled(), test.getMvelCompiled(), test.getGroovyCompiled(), test.getElCompiled(), count, exFlags);
}
total = 0;
if ((testFlags & RUN_JAVA_NATIVE) != 0 && ((exFlags & RUN_JAVA_NATIVE) != 0)) {
NativeTest nt = test.getJavaNative();
try {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(JavaNative) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(JavaNative) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
javaNativeTotal += total;
}
if (!silent)
System.out.println("------------------------------------------------");
}
#location 65
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
if (prop.length() != 0) {
ctx = getBeanProperty(ctx, prop);
}
int start = ++cursor;
whiteSpaceSkip();
if (cursor == length || scanTo(']'))
throw new PropertyAccessException("unterminated '['");
prop = new String(property, start, cursor++ - start);
if (ctx instanceof Map) {
return ((Map) ctx).get(eval(prop, ctx, variableFactory));
}
else if (ctx instanceof List) {
return ((List) ctx).get((Integer) eval(prop, ctx, variableFactory));
}
else if (ctx instanceof Collection) {
int count = (Integer) eval(prop, ctx, variableFactory);
if (count > ((Collection) ctx).size())
throw new PropertyAccessException("index [" + count + "] out of bounds on collections");
Iterator iter = ((Collection) ctx).iterator();
for (int i = 0; i < count; i++) iter.next();
return iter.next();
}
else if (ctx.getClass().isArray()) {
return Array.get(ctx, (Integer) eval(prop, ctx, variableFactory));
}
else if (ctx instanceof CharSequence) {
return ((CharSequence) ctx).charAt((Integer) eval(prop, ctx, variableFactory));
}
else {
throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()));
}
} | #vulnerable code
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
if (prop.length() != 0) {
ctx = getBeanProperty(ctx, prop);
}
int start = ++cursor;
whiteSpaceSkip();
if (cursor == length)
throw new PropertyAccessException("unterminated '['");
Object item;
if (scanTo(']'))
throw new PropertyAccessException("unterminated '['");
// String ex = new String(property, start, cursor++ - start);
item = eval(new String(property, start, cursor++ - start), ctx, variableFactory);
if (ctx instanceof Map) {
return ((Map) ctx).get(item);
}
else if (ctx instanceof List) {
return ((List) ctx).get((Integer) item);
}
else if (ctx instanceof Collection) {
int count = (Integer) item;
if (count > ((Collection) ctx).size())
throw new PropertyAccessException("index [" + count + "] out of bounds on collections");
Iterator iter = ((Collection) ctx).iterator();
for (int i = 0; i < count; i++) iter.next();
return iter.next();
}
else if (ctx.getClass().isArray()) {
return Array.get(ctx, (Integer) item);
}
else if (ctx instanceof CharSequence) {
return ((CharSequence) ctx).charAt((Integer) item);
}
else {
throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()));
}
}
#location 25
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
synchronized (Runtime.getRuntime()) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 102
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
try {
if (!((Boolean) MVEL.eval(this.name, ctx, factory))) {
throw new AssertionError("assertion failed in expression: " + new String(this.name));
}
else {
return true;
}
}
catch (ClassCastException e) {
throw new CompileException("assertion does not contain a boolean statement");
}
} | #vulnerable code
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
try {
Boolean bool = (Boolean) MVEL.eval(this.name, ctx, factory);
if (!bool) throw new AssertionError("assertion failed in expression: " + new String(this.name));
return bool;
}
catch (ClassCastException e) {
throw new CompileException("assertion does not contain a boolean statement");
}
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Object getWithProperty(Object ctx) {
String root = new String(expr, 0, cursor - 1).trim();
int start = cursor + 1;
cursor = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx);
WithAccessor wa = new WithAccessor(root, subset(expr, start, cursor++ - start), ingressType, false);
addAccessorNode(wa);
return wa.getValue(ctx, thisRef, variableFactory);
} | #vulnerable code
private Object getWithProperty(Object ctx) {
String root = new String(expr, 0, cursor - 1).trim();
int start = cursor + 1;
int[] res = balancedCaptureWithLineAccounting(expr, cursor, '{');
cursor = res[0];
getParserContext().incrementLineCount(res[1]);
WithAccessor wa = new WithAccessor(root, subset(expr, start, cursor++ - start), ingressType, false);
addAccessorNode(wa);
return wa.getValue(ctx, thisRef, variableFactory);
}
#location 7
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Object getWithProperty(Object ctx) {
assert debug("\n ** ENTER -> {with}");
if (first) {
assert debug("ALOAD 1");
mv.visitVarInsn(ALOAD, 1);
first = false;
}
String root = new String(expr, 0, cursor - 1).trim();
int start = cursor + 1;
// int[] res = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx);
cursor = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx);
// (pCtx = getParserContext()).incrementLineCount(res[1]);
this.returnType = ctx != null ? ctx.getClass() : null;
for (WithStatementPair aPvp : parseWithExpressions(root, subset(expr, start, cursor++ - start))) {
assert debug("DUP");
mv.visitInsn(DUP);
if (aPvp.getParm() == null) {
// Execute this interpretively now.
MVEL.eval(aPvp.getValue(), ctx, variableFactory);
addSubstatement((ExecutableStatement) subCompileExpression(aPvp.getValue().toCharArray()));
}
else {
// Execute interpretively.
MVEL.setProperty(ctx, aPvp.getParm(), MVEL.eval(aPvp.getValue(), ctx, variableFactory));
compiledInputs.add(((ExecutableStatement) MVEL.compileSetExpression(aPvp.getParm(),
getReturnType(ingressType, aPvp.getParm(), pCtx), pCtx)));
assert debug("ALOAD 0");
mv.visitVarInsn(ALOAD, 0);
assert debug("GETFIELD p" + (compiledInputs.size() - 1));
mv.visitFieldInsn(GETFIELD, className, "p" + (compiledInputs.size() - 1), "L" + NAMESPACE + "compiler/ExecutableStatement;");
assert debug("ALOAD 1");
mv.visitVarInsn(ALOAD, 1);
assert debug("ALOAD 2");
mv.visitVarInsn(ALOAD, 2);
assert debug("ALOAD 3");
mv.visitVarInsn(ALOAD, 3);
addSubstatement((ExecutableStatement) subCompileExpression(aPvp.getValue().toCharArray()));
assert debug("INVOKEINTERFACE Accessor.setValue");
mv.visitMethodInsn(INVOKEINTERFACE, NAMESPACE + "compiler/ExecutableStatement",
"setValue",
"(Ljava/lang/Object;Ljava/lang/Object;L"
+ NAMESPACE + "integration/VariableResolverFactory;Ljava/lang/Object;)Ljava/lang/Object;");
assert debug("POP");
mv.visitInsn(POP);
}
}
return ctx;
} | #vulnerable code
private Object getWithProperty(Object ctx) {
assert debug("\n ** ENTER -> {with}");
if (first) {
assert debug("ALOAD 1");
mv.visitVarInsn(ALOAD, 1);
first = false;
}
String root = new String(expr, 0, cursor - 1).trim();
int start = cursor + 1;
int[] res = balancedCaptureWithLineAccounting(expr, cursor, '{');
cursor = res[0];
(pCtx = getParserContext()).incrementLineCount(res[1]);
this.returnType = ctx != null ? ctx.getClass() : null;
for (WithStatementPair aPvp : parseWithExpressions(root, subset(expr, start, cursor++ - start))) {
assert debug("DUP");
mv.visitInsn(DUP);
if (aPvp.getParm() == null) {
// Execute this interpretively now.
MVEL.eval(aPvp.getValue(), ctx, variableFactory);
addSubstatement((ExecutableStatement) subCompileExpression(aPvp.getValue().toCharArray()));
}
else {
// Execute interpretively.
MVEL.setProperty(ctx, aPvp.getParm(), MVEL.eval(aPvp.getValue(), ctx, variableFactory));
compiledInputs.add(((ExecutableStatement) MVEL.compileSetExpression(aPvp.getParm(),
getReturnType(ingressType, aPvp.getParm(), pCtx), pCtx)));
assert debug("ALOAD 0");
mv.visitVarInsn(ALOAD, 0);
assert debug("GETFIELD p" + (compiledInputs.size() - 1));
mv.visitFieldInsn(GETFIELD, className, "p" + (compiledInputs.size() - 1), "L" + NAMESPACE + "compiler/ExecutableStatement;");
assert debug("ALOAD 1");
mv.visitVarInsn(ALOAD, 1);
assert debug("ALOAD 2");
mv.visitVarInsn(ALOAD, 2);
assert debug("ALOAD 3");
mv.visitVarInsn(ALOAD, 3);
addSubstatement((ExecutableStatement) subCompileExpression(aPvp.getValue().toCharArray()));
assert debug("INVOKEINTERFACE Accessor.setValue");
mv.visitMethodInsn(INVOKEINTERFACE, NAMESPACE + "compiler/ExecutableStatement",
"setValue",
"(Ljava/lang/Object;Ljava/lang/Object;L"
+ NAMESPACE + "integration/VariableResolverFactory;Ljava/lang/Object;)Ljava/lang/Object;");
assert debug("POP");
mv.visitInsn(POP);
}
}
return ctx;
}
#location 15
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static Object parse(File file, Object ctx, Map tokens, TemplateRegistry registry) throws IOException {
if (!file.exists())
throw new CompileException("cannot find file: " + file.getName());
FileInputStream inStream = null;
ReadableByteChannel fc = null;
try {
inStream = new FileInputStream(file);
fc = inStream.getChannel();
ByteBuffer buf = allocateDirect(10);
StringAppender sb = new StringAppender((int) file.length());
int read = 0;
while (read >= 0) {
buf.rewind();
read = fc.read(buf);
buf.rewind();
for (; read > 0; read--) {
sb.append((char) buf.get());
}
}
//noinspection unchecked
return parse(sb, ctx, tokens, registry);
}
catch (FileNotFoundException e) {
// this can't be thrown, we check for this explicitly.
}
finally {
if (inStream != null) inStream.close();
if (fc != null) fc.close();
}
return null;
} | #vulnerable code
public static Object parse(File file, Object ctx, Map tokens, TemplateRegistry registry) throws IOException {
if (!file.exists())
throw new CompileException("cannot find file: " + file.getName());
FileInputStream inStream = null;
ReadableByteChannel fc = null;
try {
inStream = new FileInputStream(file);
fc = inStream.getChannel();
ByteBuffer buf = allocateDirect(10);
StringAppender sb = new StringAppender((int) file.length());
int read = 0;
while (read >= 0) {
buf.rewind();
read = fc.read(buf);
buf.rewind();
for (; read > 0; read--) {
sb.append((char) buf.get());
}
}
//noinspection unchecked
return parse(sb, ctx, tokens, registry);
}
catch (FileNotFoundException e) {
// this can't be thrown, we check for this explicitly.
}
finally {
if (inStream != null) inStream.close();
if (fc != null) fc.close();
}
return null;
}
#location 26
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public CompiledExpression compile() {
ASTNode tk;
ASTNode tkOp;
ASTNode tkOp2;
ASTNode tkLA;
ASTNode tkLA2;
ASTLinkedList astLinkedList = new ASTLinkedList();
boolean firstLA;
ParserContext pCtx = getParserContext();
if (verifying) {
inputs = new LinkedHashSet<String>();
locals = new LinkedHashSet<String>();
getParserContext().setVariableTable(new HashMap<String, Class>());
}
fields |= ASTNode.COMPILE_IMMEDIATE;
while ((tk = nextToken()) != null) {
if (tk.fields == -1) {
astLinkedList.addTokenNode(tk);
continue;
}
returnType = tk.getEgressType();
if (tk instanceof TypedVarNode) {
TypedVarNode tv = (TypedVarNode) tk;
pCtx.getVariableTable().put(tv.getName(), tv.getEgressType());
}
else if (pCtx.isStrictTypeEnforcement() && tk instanceof AssignmentNode
&& (pCtx.getInputTable() == null
|| !pCtx.getInputTable().containsKey(tk.getName()))) {
addFatalError("untyped var not permitted in strict-mode: " + tk.getName());
}
if (tk instanceof Substatement) {
ExpressionCompiler subCompiler = new ExpressionCompiler(tk.getNameAsArray());
tk.setAccessor(subCompiler.compile());
if (verifying)
inputs.addAll(subCompiler.getInputs());
}
/**
* This kludge of code is to handle compile-time literal reduction. We need to avoid
* reducing for certain literals like, 'this', ternary and ternary else.
*/
if (tk.isLiteral() && tk.getLiteralValue() != LITERALS.get("this")) {
if ((tkOp = nextToken()) != null && tkOp.isOperator()
&& !tkOp.isOperator(Operator.TERNARY) && !tkOp.isOperator(Operator.TERNARY_ELSE)) {
/**
* If the next token is ALSO a literal, then we have a candidate for a compile-time
* reduction.
*/
if ((tkLA = nextToken()) != null && tkLA.isLiteral()) {
stk.push(tk.getLiteralValue(), tkLA.getLiteralValue(), tkOp.getLiteralValue());
/**
* Reduce the token now.
*/
reduceTrinary();
firstLA = true;
/**
* Now we need to check to see if this is actually a continuing reduction.
*/
while ((tkOp2 = nextToken()) != null) {
if (!tkOp2.isOperator(tkOp.getOperator())) {
/**
* We can't continue any further because we are dealing with
* different operators.
*/
astLinkedList.addTokenNode(new LiteralNode(stk.pop()));
astLinkedList.addTokenNode(tkOp2);
break;
}
else if ((tkLA2 = nextToken()) != null
&& tkLA2.isLiteral()) {
stk.push(tkLA2.getLiteralValue(), tkOp2.getLiteralValue());
reduceTrinary();
firstLA = false;
}
else {
if (firstLA) {
/**
* There are more tokens, but we can't reduce anymore. So
* we create a reduced token for what we've got.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
}
else {
/**
* We have reduced additional tokens, but we can't reduce
* anymore.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()), tkOp);
if (tkLA2 != null) astLinkedList.addTokenNode(tkLA2);
}
break;
}
}
/**
* If there are no more tokens left to parse, we check to see if
* we've been doing any reducing, and if so we create the token
* now.
*/
if (!stk.isEmpty())
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
continue;
}
else {
astLinkedList.addTokenNode(verify(tk), verify(tkOp));
if (tkLA != null) astLinkedList.addTokenNode(verify(tkLA));
continue;
}
}
else {
astLinkedList.addTokenNode(verify(tk));
if (tkOp != null) astLinkedList.addTokenNode(verify(tkOp));
continue;
}
}
astLinkedList.addTokenNode(verify(tk));
}
if (verifying) {
for (String s : locals) {
inputs.remove(s);
}
}
if (pCtx.isFatalError()) {
parserContext.set(null);
throw new CompileException("Failed to compile: " + pCtx.getErrorList().size() + " compilation error(s)", pCtx.getErrorList());
}
else if (pCtx.isFatalError()) {
throw new CompileException("Failed to compile: " + pCtx.getErrorList().size() + " compilation error(s)", pCtx.getErrorList());
}
return new CompiledExpression(new ASTArrayList(astLinkedList), getCurrentSourceFileName());
} | #vulnerable code
public CompiledExpression compile() {
ASTNode tk;
ASTNode tkOp;
ASTNode tkOp2;
ASTNode tkLA;
ASTNode tkLA2;
ASTLinkedList astLinkedList = new ASTLinkedList();
boolean firstLA;
ParserContext pCtx = getParserContext();
if (verifying) {
inputs = new LinkedHashSet<String>();
locals = new LinkedHashSet<String>();
getParserContext().setVariableTable(new HashMap<String, Class>());
}
fields |= ASTNode.COMPILE_IMMEDIATE;
while ((tk = nextToken()) != null) {
if (tk.fields == -1) {
astLinkedList.addTokenNode(tk);
continue;
}
returnType = tk.getEgressType();
if (tk instanceof TypedVarNode) {
TypedVarNode tv = (TypedVarNode) tk;
pCtx.getVariableTable().put(tv.getName(), tv.getEgressType());
}
else if (pCtx.isStrictTypeEnforcement() && tk instanceof AssignmentNode
&& (pCtx.getInputTable() == null
|| !pCtx.getInputTable().containsKey(tk.getName()))) {
pCtx.addError(new ErrorDetail("untyped var not permitted in strict-mode: " + tk.getName(), true));
}
if (tk instanceof Substatement) {
ExpressionCompiler subCompiler = new ExpressionCompiler(tk.getNameAsArray());
tk.setAccessor(subCompiler.compile());
if (verifying)
inputs.addAll(subCompiler.getInputs());
}
/**
* This kludge of code is to handle compile-time literal reduction. We need to avoid
* reducing for certain literals like, 'this', ternary and ternary else.
*/
if (tk.isLiteral() && tk.getLiteralValue() != LITERALS.get("this")) {
if ((tkOp = nextToken()) != null && tkOp.isOperator()
&& !tkOp.isOperator(Operator.TERNARY) && !tkOp.isOperator(Operator.TERNARY_ELSE)) {
/**
* If the next token is ALSO a literal, then we have a candidate for a compile-time
* reduction.
*/
if ((tkLA = nextToken()) != null && tkLA.isLiteral()) {
stk.push(tk.getLiteralValue(), tkLA.getLiteralValue(), tkOp.getLiteralValue());
/**
* Reduce the token now.
*/
reduceTrinary();
firstLA = true;
/**
* Now we need to check to see if this is actually a continuing reduction.
*/
while ((tkOp2 = nextToken()) != null) {
if (!tkOp2.isOperator(tkOp.getOperator())) {
/**
* We can't continue any further because we are dealing with
* different operators.
*/
astLinkedList.addTokenNode(new LiteralNode(stk.pop()));
astLinkedList.addTokenNode(tkOp2);
break;
}
else if ((tkLA2 = nextToken()) != null
&& tkLA2.isLiteral()) {
stk.push(tkLA2.getLiteralValue(), tkOp2.getLiteralValue());
reduceTrinary();
firstLA = false;
}
else {
if (firstLA) {
/**
* There are more tokens, but we can't reduce anymore. So
* we create a reduced token for what we've got.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
}
else {
/**
* We have reduced additional tokens, but we can't reduce
* anymore.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()), tkOp);
if (tkLA2 != null) astLinkedList.addTokenNode(tkLA2);
}
break;
}
}
/**
* If there are no more tokens left to parse, we check to see if
* we've been doing any reducing, and if so we create the token
* now.
*/
if (!stk.isEmpty())
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
continue;
}
else {
astLinkedList.addTokenNode(verify(tk), verify(tkOp));
if (tkLA != null) astLinkedList.addTokenNode(verify(tkLA));
continue;
}
}
else {
astLinkedList.addTokenNode(verify(tk));
if (tkOp != null) astLinkedList.addTokenNode(verify(tkOp));
continue;
}
}
astLinkedList.addTokenNode(verify(tk));
}
if (verifying) {
for (String s : locals) {
inputs.remove(s);
}
}
if (compileFail) {
throw new CompileException("Failed to compile: " + getParserContext().getErrorList().size() + " compilation error(s)", getParserContext().getErrorList());
}
if (pCtx.getRootParser() == this) {
parserContext.set(null);
}
return new CompiledExpression(new ASTArrayList(astLinkedList), getCurrentSourceFileName());
}
#location 150
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
ItemResolverFactory.ItemResolver itemR = new ItemResolverFactory.ItemResolver(item);
ItemResolverFactory itemFactory = new ItemResolverFactory(itemR, new DefaultLocalVariableResolverFactory(factory));
Object iterCond = MVEL.eval(cond, thisValue, factory);
if (itemType != null && itemType.isArray())
enforceTypeSafety(itemType, ParseTools.getBaseComponentType(iterCond.getClass()));
this.compiledBlock = (ExecutableStatement) subCompileExpression(block);
if (iterCond instanceof Iterable) {
for (Object o : (Iterable) iterCond) {
itemR.setValue(o);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond != null && iterCond.getClass().isArray()) {
int len = Array.getLength(iterCond);
for (int i = 0; i < len; i++) {
itemR.setValue(Array.get(iterCond, i));
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond instanceof CharSequence) {
for (Object o : iterCond.toString().toCharArray()) {
itemR.setValue(o);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond instanceof Integer) {
int max = (Integer) iterCond + 1;
for (int i = 1; i != max; i++) {
itemR.setValue(i);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else {
throw new CompileException("non-iterable type: " + (iterCond != null ? iterCond.getClass().getName() : "null"));
}
return null;
} | #vulnerable code
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
ItemResolverFactory.ItemResolver itemR = new ItemResolverFactory.ItemResolver(item);
ItemResolverFactory itemFactory = new ItemResolverFactory(itemR, new DefaultLocalVariableResolverFactory(factory));
Object iterCond = MVEL.eval(cond, thisValue, factory);
if (itemType != null && itemType.isArray())
enforceTypeSafety(itemType, ParseTools.getBaseComponentType(iterCond.getClass()));
this.compiledBlock = (ExecutableStatement) subCompileExpression(block);
if (iterCond instanceof Iterable) {
for (Object o : (Iterable) iterCond) {
itemR.setValue(o);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond != null && iterCond.getClass().isArray()) {
int len = Array.getLength(iterCond);
for (int i = 0; i < len; i++) {
itemR.setValue(Array.get(iterCond, i));
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond instanceof CharSequence) {
for (Object o : iterCond.toString().toCharArray()) {
itemR.setValue(o);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond instanceof Integer) {
int max = (Integer) iterCond + 1;
for (int i = 1; i != max; i++) {
itemR.setValue(i);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else {
throw new CompileException("non-iterable type: " + iterCond.getClass().getName());
}
return null;
}
#location 39
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (CACHE_DISABLE || !cacheAggressively) {
char[] seg = new char[expression.length - 3];
// arraycopy(expression, 2, seg, 0, seg.length);
for (int i = 0; i < seg.length; i++)
seg[i] = expression[i + 2];
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
if (tokens == null) {
tokens = new HashMap();
}
ForeachContext foreachContext;
String[] names;
String[] aliases;
if (!(localStack.peek() instanceof ForeachContext)) {
// create a clone of the context
foreachContext = ((ForeachContext) currNode.getRegister()).clone();
names = foreachContext.getNames();
aliases = foreachContext.getAliases();
try {
Iterator[] iters = new Iterator[names.length];
for (int i = 0; i < names.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(names[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator(); // this throws null pointer exception in thread race
}
// set the newly created iterators into the context
foreachContext.setIterators(iters);
// push the context onto the local stack.
localStack.push(foreachContext);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)), e);
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)), e);
}
}
else {
foreachContext = (ForeachContext) localStack.peek();
// names = foreachContext.getNames();
aliases = foreachContext.getAliases();
}
Iterator[] iters = foreachContext.getItererators();
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(aliases[i], iters[i].next());
}
int c;
tokens.put("i0", c = foreachContext.getCount());
if (c != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
foreachContext.incrementCount();
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(aliases[i]);
}
// foreachContext.setIterators(null);
// foreachContext.setCount(0);
localStack.pop();
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (CACHE_DISABLE || !cacheAggressively) {
char[] seg = new char[expression.length - 3];
// arraycopy(expression, 2, seg, 0, seg.length);
for (int i = 0; i < seg.length; i++)
seg[i] = expression[i + 2];
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
if (tokens == null) {
tokens = new HashMap();
}
ForeachContext foreachContext;
if (!(localStack.peek() instanceof ForeachContext)) {
foreachContext = ((ForeachContext) currNode.getRegister()).clone();
// if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
localStack.push(foreachContext);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
foreachContext = (ForeachContext) localStack.peek();
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
localStack.pop();
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 145
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
synchronized (Runtime.getRuntime()) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 136
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
protected ASTNode nextToken() {
/**
* If the cursor is at the end of the expression, we have nothing more to do:
* return null.
*/
if (cursor >= length) {
return null;
}
else if (!splitAccumulator.isEmpty()) {
return lastNode = (ASTNode) splitAccumulator.pop();
}
int brace, start = cursor;
/**
* Because of parser recursion for sub-expression parsing, we sometimes need to remain
* certain field states. We do not reset for assignments, boolean mode, list creation or
* a capture only mode.
*/
fields = fields & (ASTNode.INLINE_COLLECTION | ASTNode.COMPILE_IMMEDIATE);
boolean capture = false;
boolean union = false;
if (debugSymbols) {
if (!lastWasLineLabel) {
if (getParserContext().getSourceFile() == null) {
throw new CompileException("unable to produce debugging symbols: source name must be provided.");
}
ParserContext pCtx = getParserContext();
line = pCtx.getLineCount();
int scan = cursor;
while (expr[scan] == '\n') {
scan++;
line++;
}
if (lastWasComment) {
line++;
lastWasComment = false;
}
pCtx.setLineCount(line);
if (!pCtx.isKnownLine(pCtx.getSourceFile(), line)) {
lastWasLineLabel = true;
pCtx.setLineAndOffset(line, cursor);
pCtx.addKnownLine(pCtx.getSourceFile(), line);
LineLabel ll = new LineLabel(pCtx.getSourceFile(), line);
if (pCtx.getFirstLineLabel() == null) pCtx.setFirstLineLabel(ll);
return lastNode = ll;
}
}
else {
lastWasComment = lastWasLineLabel = false;
}
}
/**
* Skip any whitespace currently under the starting point.
*/
while (start < length && isWhitespace(expr[start])) start++;
/**
* From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for
* trouble unless you really know what you're doing.
*/
for (cursor = start; cursor < length;) {
if (isIdentifierPart(expr[cursor])) {
/**
* If the current character under the cursor is a valid
* part of an identifier, we keep capturing.
*/
capture = true;
cursor++;
}
else if (capture) {
String t;
if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) {
switch (OPERATORS.get(t)) {
case NEW:
start = cursor + 1;
captureToEOT();
return new NewObjectNode(subArray(start, cursor), fields);
case ASSERT:
start = cursor + 1;
captureToEOS();
return new AssertNode(subArray(start, cursor--), fields);
case RETURN:
start = cursor + 1;
captureToEOS();
return new ReturnNode(subArray(start, cursor), fields);
case IF:
fields |= ASTNode.BLOCK_IF;
return captureCodeBlock();
case FOREACH:
fields |= ASTNode.BLOCK_FOREACH;
return captureCodeBlock();
case WITH:
fields |= ASTNode.BLOCK_WITH;
return captureCodeBlock();
case IMPORT:
start = cursor + 1;
captureToEOS();
ImportNode importNode = new ImportNode(subArray(start, cursor--), fields);
getParserContext().addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass());
return importNode;
case IMPORT_STATIC:
start = cursor + 1;
captureToEOS();
return new StaticImportNode(subArray(start, cursor--), fields);
}
}
/**
* If we *were* capturing a token, and we just hit a non-identifier
* character, we stop and figure out what to do.
*/
skipWhitespace();
if (expr[cursor] == '(') {
fields |= ASTNode.METHOD;
/**
* If the current token is a method call or a constructor, we
* simply capture the entire parenthesized range and allow
* reduction to be dealt with through sub-parsing the property.
*/
cursor++;
for (brace = 1; cursor < length && brace > 0;) {
switch (expr[cursor++]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length) + 1;
break;
case'"':
cursor = captureStringLiteral('"', expr, cursor, length) + 1;
break;
}
}
/**
* If the brace counter is greater than 0, we know we have
* unbalanced braces in the expression. So we throw a
* optimize error now.
*/
if (brace > 0)
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
/**
* If we encounter any of the following cases, we are still dealing with
* a contiguous token.
*/
String name;
if (cursor < length) {
switch (expr[cursor]) {
case'+':
switch (lookAhead(1)) {
case'+':
ASTNode n = new PostFixIncNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields, Operator.ADD, t);
}
else {
return new AssignmentNode(subArray(start, cursor), fields, Operator.ADD, name);
}
}
break;
case'-':
switch (lookAhead(1)) {
case'-':
ASTNode n = new PostFixDecNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignSub(subArray(start, cursor), fields, name);
}
break;
case'*':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignMult(subArray(start, cursor), fields, name);
}
break;
case'/':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignDiv(subArray(start, cursor), fields, name);
}
break;
case']':
case'[':
balancedCapture('[');
cursor++;
continue;
case'.':
union = true;
cursor++;
continue;
case'~':
if (isAt('=', 1)) {
char[] stmt = subArray(start, trimLeft(cursor));
start = cursor += 2;
captureToEOT();
return new RegExMatch(stmt, fields, subArray(start, cursor));
}
break;
case'=':
if (isAt('+', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignAdd(subArray(start, cursor), fields, name);
}
if (greedy && !isAt('=', 1)) {
cursor++;
fields |= ASTNode.ASSIGN;
skipWhitespace();
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields);
}
else if (lastWasIdentifier) {
/**
* Check for typing information.
*/
if (lastNode.getLiteralValue() instanceof String) {
if (getParserContext().hasImport((String) lastNode.getLiteralValue())) {
lastNode.setLiteralValue(getParserContext().getImport((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
else {
try {
/**
* take a stab in the dark and try and load the class
*/
lastNode.setLiteralValue(createClass((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) {
lastNode.setDiscard(true);
captureToEOS();
return new TypedVarNode(subArray(start, cursor), fields, (Class)
lastNode.getLiteralValue());
}
throw new ParseException("unknown class: " + lastNode.getLiteralValue());
}
else {
return new AssignmentNode(subArray(start, cursor), fields);
}
}
}
}
/**
* Produce the token.
*/
trimWhitespace();
if (parserContext != null) {
char[] _subset = subset(expr, start, cursor - start);
int offset;
Class cls;
if ((offset = ArrayTools.findFirst('.', _subset)) != -1) {
String iStr;
if (getParserContext().hasImport(iStr = new String(_subset, 0, offset))) {
lastWasIdentifier = true;
return lastNode = new LiteralDeepPropertyNode(subset(_subset, offset + 1, _subset.length - offset - 1), fields, getParserContext().getImport(iStr));
// / return lastNode = new Union(_subset, offset + 1, _subset.length, fields, new LiteralNode(getParserContext().getImport(iStr)));
}
// else if ((cls = createClassSafe(iStr = new String(_subset, offset = ArrayTools.findLast('.', _subset), _subset.length - offset))) != null) {
//
// }
}
else {
ASTNode node = new ASTNode(_subset, 0, _subset.length, fields);
lastWasIdentifier = node.isIdentifier();
return lastNode = node;
}
}
return createToken(expr, start, cursor, fields);
}
else
switch (expr[cursor]) {
case'@': {
start++;
captureToEOT();
String interceptorName = new String(expr, start, cursor - start);
if (getParserContext().getInterceptors() == null || !getParserContext().getInterceptors().
containsKey(interceptorName)) {
throw new CompileException("reference to undefined interceptor: " + interceptorName, expr, cursor);
}
return new InterceptorWrapper(getParserContext().getInterceptors().get(interceptorName), nextToken());
}
case'=':
return createToken(expr, start, (cursor += 2), fields);
case'-':
if (isAt('-', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixDecNode(subArray(start, cursor), fields);
}
else if ((cursor > 0 && !isWhitespace(lookBehind(1))) || !isDigit(lookAhead(1))) {
return createToken(expr, start, cursor++ + 1, fields);
}
else if ((cursor - 1) < 0 || (!isDigit(lookBehind(1))) && isDigit(lookAhead(1))) {
cursor++;
break;
}
case'+':
if (isAt('+', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixIncNode(subArray(start, cursor), fields);
}
return createToken(expr, start, cursor++ + 1, fields);
case'*':
if (isAt('*', 1)) {
cursor++;
}
return createToken(expr, start, cursor++ + 1, fields);
case';':
cursor++;
lastWasIdentifier = false;
return lastNode = new EndOfStatement();
case'#':
case'/':
if (isAt(expr[cursor], 1)) {
/**
* Handle single line comments.
*/
while (cursor < length && expr[cursor] != '\n') cursor++;
if (debugSymbols) {
line = getParserContext().getLineCount();
skipWhitespaceWithLineAccounting();
if (lastNode instanceof LineLabel) {
getParserContext().getFirstLineLabel().setLineNumber(line);
}
lastWasComment = true;
getParserContext().setLineCount(line);
}
else if (cursor < length) {
skipWhitespace();
}
if ((start = cursor) >= length) return null;
continue;
}
else if (expr[cursor] == '/' && isAt('*', 1)) {
/**
* Handle multi-line comments.
*/
int len = length - 1;
/**
* This probably seems highly redundant, but sub-compilations within the same
* source will spawn a new compiler, and we need to sync this with the
* parser context;
*/
if (debugSymbols) {
line = getParserContext().getLineCount();
}
while (true) {
cursor++;
/**
* Since multi-line comments may cross lines, we must keep track of any line-break
* we encounter.
*/
if (debugSymbols && expr[cursor] == '\n') {
line++;
}
if (cursor == len) {
throw new CompileException("unterminated block comment", expr, cursor);
}
if (expr[cursor] == '*' && isAt('/', 1)) {
if ((cursor += 2) >= length) return null;
skipWhitespace();
start = cursor;
break;
}
}
if (debugSymbols) {
getParserContext().setLineCount(line);
}
continue;
}
case'?':
case':':
case'^':
case'%': {
return createToken(expr, start, cursor++ + 1, fields);
}
case'(': {
cursor++;
boolean singleToken = true;
boolean lastWS = false;
skipWhitespace();
for (brace = 1; cursor < length && brace > 0; cursor++) {
switch (expr[cursor]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'"':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'i':
if (isAt('n', 1) && isWhitespace(lookAhead(2))) {
fields |= ASTNode.FOLD;
}
break;
default:
/**
* Check to see if we should disqualify this current token as a potential
* type-cast candidate.
*/
if (lastWS || !isIdentifierPart(expr[cursor])) {
singleToken = false;
}
else if (isWhitespace(expr[cursor])) {
lastWS = true;
skipWhitespace();
cursor--;
}
}
}
if (brace > 0) {
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
char[] _subset = null;
if (singleToken) {
String tokenStr = new String(_subset = subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)));
if (getParserContext().hasImport(tokenStr)) {
start = cursor;
captureToEOS();
return new TypeCast(expr, start, cursor, fields, getParserContext().getImport(tokenStr));
}
else if (LITERALS.containsKey(tokenStr)) {
start = cursor;
captureToEOS();
return new TypeCast(expr, start, cursor, fields, (Class) LITERALS.get(tokenStr));
}
else {
try {
/**
*
* take a stab in the dark and try and load the class
*/
int _start = cursor;
captureToEOS();
return new TypeCast(expr, _start, cursor, fields, createClass(tokenStr));
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if ((fields & ASTNode.FOLD) != 0) {
if (cursor < length && expr[cursor] == '.') {
cursor += 1;
continue;
}
return createToken(expr, trimRight(start), cursor, ASTNode.FOLD);
}
if (_subset != null) {
return handleUnion(new Substatement(_subset, fields));
}
else {
return handleUnion(new Substatement(subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)), fields));
}
}
case'}':
case']':
case')': {
throw new ParseException("unbalanced braces", expr, cursor);
}
case'>': {
if (expr[cursor + 1] == '>') {
if (expr[cursor += 2] == '>') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor + 1] == '=') {
return createToken(expr, start, cursor += 2, fields);
}
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'<': {
if (expr[++cursor] == '<') {
if (expr[++cursor] == '<') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor] == '=') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'"':
cursor = captureStringLiteral('"', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'&': {
if (expr[cursor++ + 1] == '&') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'|': {
if (expr[cursor++ + 1] == '|') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'~':
if ((cursor - 1 < 0 || !isIdentifierPart(lookBehind(1)))
&& isDigit(expr[cursor + 1])) {
fields |= ASTNode.INVERT;
start++;
cursor++;
break;
}
else if (expr[cursor + 1] == '(') {
fields |= ASTNode.INVERT;
start = ++cursor;
continue;
}
else {
if (expr[cursor + 1] == '=') cursor++;
return createToken(expr, start, ++cursor, fields);
}
case'!': {
if (isIdentifierPart(expr[++cursor]) || expr[cursor] == '(') {
start = cursor;
fields |= ASTNode.NEGATION;
continue;
}
else if (expr[cursor] != '=')
throw new CompileException("unexpected operator '!'", expr, cursor, null);
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'[':
case'{':
if (balancedCapture(expr[cursor]) == -1) {
if (cursor >= length) cursor--;
throw new CompileException("unbalanced brace: in inline map/list/array creation", expr, cursor);
}
if (cursor < (length - 1) && expr[cursor + 1] == '.') {
fields |= ASTNode.INLINE_COLLECTION;
cursor++;
continue;
}
return new InlineCollectionNode(expr, start, ++cursor, fields);
default:
cursor++;
}
}
return createPropertyToken(start, cursor);
} | #vulnerable code
protected ASTNode nextToken() {
/**
* If the cursor is at the end of the expression, we have nothing more to do:
* return null.
*/
if (cursor >= length) {
return null;
}
else if (!splitAccumulator.isEmpty()) {
return lastNode = (ASTNode) splitAccumulator.pop();
}
int brace, start = cursor;
/**
* Because of parser recursion for sub-expression parsing, we sometimes need to remain
* certain field states. We do not reset for assignments, boolean mode, list creation or
* a capture only mode.
*/
fields = fields & (ASTNode.INLINE_COLLECTION | ASTNode.COMPILE_IMMEDIATE);
boolean capture = false;
boolean union = false;
if (debugSymbols) {
if (!lastWasLineLabel) {
if (getParserContext().getSourceFile() == null) {
throw new CompileException("unable to produce debugging symbols: source name must be provided.");
}
ParserContext pCtx = getParserContext();
line = pCtx.getLineCount();
int scan = cursor;
while (expr[scan] == '\n') {
scan++;
line++;
}
if (lastWasComment) {
line++;
lastWasComment = false;
}
pCtx.setLineCount(line);
if (!pCtx.isKnownLine(pCtx.getSourceFile(), line)) {
lastWasLineLabel = true;
pCtx.setLineAndOffset(line, cursor);
pCtx.addKnownLine(pCtx.getSourceFile(), line);
LineLabel ll = new LineLabel(pCtx.getSourceFile(), line);
if (pCtx.getFirstLineLabel() == null) pCtx.setFirstLineLabel(ll);
return lastNode = ll;
}
}
else {
lastWasComment = lastWasLineLabel = false;
}
}
/**
* Skip any whitespace currently under the starting point.
*/
while (start < length && isWhitespace(expr[start])) start++;
/**
* From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for
* trouble unless you really know what you're doing.
*/
for (cursor = start; cursor < length;) {
if (isIdentifierPart(expr[cursor])) {
/**
* If the current character under the cursor is a valid
* part of an identifier, we keep capturing.
*/
capture = true;
cursor++;
}
else if (capture) {
String t;
if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) {
switch (OPERATORS.get(t)) {
case NEW:
start = cursor + 1;
captureToEOT();
return new NewObjectNode(subArray(start, cursor), fields);
case ASSERT:
start = cursor + 1;
captureToEOS();
return new AssertNode(subArray(start, cursor--), fields);
case RETURN:
start = cursor + 1;
captureToEOS();
return new ReturnNode(subArray(start, cursor), fields);
case IF:
fields |= ASTNode.BLOCK_IF;
return captureCodeBlock();
case FOREACH:
fields |= ASTNode.BLOCK_FOREACH;
return captureCodeBlock();
case WITH:
fields |= ASTNode.BLOCK_WITH;
return captureCodeBlock();
case IMPORT:
start = cursor + 1;
captureToEOS();
ImportNode importNode = new ImportNode(subArray(start, cursor--), fields);
getParserContext().addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass());
return importNode;
case IMPORT_STATIC:
start = cursor + 1;
captureToEOS();
return new StaticImportNode(subArray(start, cursor--), fields);
}
}
/**
* If we *were* capturing a token, and we just hit a non-identifier
* character, we stop and figure out what to do.
*/
skipWhitespace();
if (expr[cursor] == '(') {
fields |= ASTNode.METHOD;
/**
* If the current token is a method call or a constructor, we
* simply capture the entire parenthesized range and allow
* reduction to be dealt with through sub-parsing the property.
*/
cursor++;
for (brace = 1; cursor < length && brace > 0;) {
switch (expr[cursor++]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length) + 1;
break;
case'"':
cursor = captureStringLiteral('"', expr, cursor, length) + 1;
break;
}
}
/**
* If the brace counter is greater than 0, we know we have
* unbalanced braces in the expression. So we throw a
* optimize error now.
*/
if (brace > 0)
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
/**
* If we encounter any of the following cases, we are still dealing with
* a contiguous token.
*/
String name;
if (cursor < length) {
switch (expr[cursor]) {
case'+':
switch (lookAhead(1)) {
case'+':
ASTNode n = new PostFixIncNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields, Operator.ADD, t);
}
else {
return new AssignmentNode(subArray(start, cursor), fields, Operator.ADD, name);
}
}
break;
case'-':
switch (lookAhead(1)) {
case'-':
ASTNode n = new PostFixDecNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignSub(subArray(start, cursor), fields, name);
}
break;
case'*':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignMult(subArray(start, cursor), fields, name);
}
break;
case'/':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignDiv(subArray(start, cursor), fields, name);
}
break;
case']':
case'[':
balancedCapture('[');
cursor++;
continue;
case'.':
union = true;
cursor++;
continue;
case'~':
if (isAt('=', 1)) {
char[] stmt = subArray(start, trimLeft(cursor));
start = cursor += 2;
captureToEOT();
return new RegExMatch(stmt, fields, subArray(start, cursor));
}
break;
case'=':
if (isAt('+', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignAdd(subArray(start, cursor), fields, name);
}
if (greedy && !isAt('=', 1)) {
cursor++;
fields |= ASTNode.ASSIGN;
skipWhitespace();
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields);
}
else if (lastWasIdentifier) {
/**
* Check for typing information.
*/
if (lastNode.getLiteralValue() instanceof String) {
if (getParserContext().hasImport((String) lastNode.getLiteralValue())) {
lastNode.setLiteralValue(getParserContext().getImport((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
else {
try {
/**
* take a stab in the dark and try and load the class
*/
lastNode.setLiteralValue(createClass((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) {
lastNode.setDiscard(true);
captureToEOS();
return new TypedVarNode(subArray(start, cursor), fields, (Class)
lastNode.getLiteralValue());
}
throw new ParseException("unknown class: " + lastNode.getLiteralValue());
}
else {
return new AssignmentNode(subArray(start, cursor), fields);
}
}
}
}
/**
* Produce the token.
*/
trimWhitespace();
return createToken(expr, start, cursor, fields);
}
else
switch (expr[cursor]) {
case'@': {
start++;
captureToEOT();
String interceptorName = new String(expr, start, cursor - start);
if (getParserContext().getInterceptors() == null || !getParserContext().getInterceptors().
containsKey(interceptorName)) {
throw new CompileException("reference to undefined interceptor: " + interceptorName, expr, cursor);
}
return new InterceptorWrapper(getParserContext().getInterceptors().get(interceptorName), nextToken());
}
case'=':
return createToken(expr, start, (cursor += 2), fields);
case'-':
if (isAt('-', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixDecNode(subArray(start, cursor), fields);
}
else if ((cursor > 0 && !isWhitespace(lookBehind(1))) || !isDigit(lookAhead(1))) {
return createToken(expr, start, cursor++ + 1, fields);
}
else if ((cursor - 1) < 0 || (!isDigit(lookBehind(1))) && isDigit(lookAhead(1))) {
cursor++;
break;
}
case'+':
if (isAt('+', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixIncNode(subArray(start, cursor), fields);
}
return createToken(expr, start, cursor++ + 1, fields);
case'*':
if (isAt('*', 1)) {
cursor++;
}
return createToken(expr, start, cursor++ + 1, fields);
case';':
cursor++;
lastWasIdentifier = false;
return lastNode = new EndOfStatement();
case'#':
case'/':
if (isAt(expr[cursor], 1)) {
/**
* Handle single line comments.
*/
while (cursor < length && expr[cursor] != '\n') cursor++;
if (debugSymbols) {
line = getParserContext().getLineCount();
skipWhitespaceWithLineAccounting();
if (lastNode instanceof LineLabel) {
getParserContext().getFirstLineLabel().setLineNumber(line);
}
lastWasComment = true;
getParserContext().setLineCount(line);
}
else if (cursor < length) {
skipWhitespace();
}
if ((start = cursor) >= length) return null;
continue;
}
else if (expr[cursor] == '/' && isAt('*', 1)) {
/**
* Handle multi-line comments.
*/
int len = length - 1;
/**
* This probably seems highly redundant, but sub-compilations within the same
* source will spawn a new compiler, and we need to sync this with the
* parser context;
*/
if (debugSymbols) {
line = getParserContext().getLineCount();
}
while (true) {
cursor++;
/**
* Since multi-line comments may cross lines, we must keep track of any line-break
* we encounter.
*/
if (debugSymbols && expr[cursor] == '\n') {
line++;
}
if (cursor == len) {
throw new CompileException("unterminated block comment", expr, cursor);
}
if (expr[cursor] == '*' && isAt('/', 1)) {
if ((cursor += 2) >= length) return null;
skipWhitespace();
start = cursor;
break;
}
}
if (debugSymbols) {
getParserContext().setLineCount(line);
}
continue;
}
case'?':
case':':
case'^':
case'%': {
return createToken(expr, start, cursor++ + 1, fields);
}
case'(': {
cursor++;
boolean singleToken = true;
boolean lastWS = false;
skipWhitespace();
for (brace = 1; cursor < length && brace > 0; cursor++) {
switch (expr[cursor]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'"':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'i':
if (isAt('n', 1) && isWhitespace(lookAhead(2))) {
fields |= ASTNode.FOLD;
}
break;
default:
/**
* Check to see if we should disqualify this current token as a potential
* type-cast candidate.
*/
if (lastWS || isIdentifierPart(expr[cursor])) {
singleToken = false;
}
else if (isWhitespace(expr[cursor])) {
lastWS = true;
skipWhitespace();
cursor--;
}
}
}
if (brace > 0) {
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
char[] _subset = null;
if (singleToken) {
String tokenStr = new String(_subset = subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)));
if (getParserContext().hasImport(tokenStr)) {
start = cursor;
captureToEOS();
return new TypeCast(expr, start, cursor, fields, getParserContext().getImport(tokenStr));
}
else if (LITERALS.containsKey(tokenStr)) {
start = cursor;
captureToEOS();
return new TypeCast(expr, start, cursor, fields, (Class) LITERALS.get(tokenStr));
}
else {
try {
/**
*
* take a stab in the dark and try and load the class
*/
int _start = cursor;
captureToEOS();
return new TypeCast(expr, _start, cursor, fields, createClass(tokenStr));
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if ((fields & ASTNode.FOLD) != 0) {
if (cursor < length && expr[cursor] == '.') {
cursor += 1;
continue;
}
return createToken(expr, trimRight(start), cursor, ASTNode.FOLD);
}
if (_subset != null) {
return handleUnion(new Substatement(_subset, fields));
}
else {
return handleUnion(new Substatement(subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)), fields));
}
}
case'}':
case']':
case')': {
throw new ParseException("unbalanced braces", expr, cursor);
}
case'>': {
if (expr[cursor + 1] == '>') {
if (expr[cursor += 2] == '>') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor + 1] == '=') {
return createToken(expr, start, cursor += 2, fields);
}
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'<': {
if (expr[++cursor] == '<') {
if (expr[++cursor] == '<') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor] == '=') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'"':
cursor = captureStringLiteral('"', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'&': {
if (expr[cursor++ + 1] == '&') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'|': {
if (expr[cursor++ + 1] == '|') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'~':
if ((cursor - 1 < 0 || !isIdentifierPart(lookBehind(1)))
&& isDigit(expr[cursor + 1])) {
fields |= ASTNode.INVERT;
start++;
cursor++;
break;
}
else if (expr[cursor + 1] == '(') {
fields |= ASTNode.INVERT;
start = ++cursor;
continue;
}
else {
if (expr[cursor + 1] == '=') cursor++;
return createToken(expr, start, ++cursor, fields);
}
case'!': {
if (isIdentifierPart(expr[++cursor]) || expr[cursor] == '(') {
start = cursor;
fields |= ASTNode.NEGATION;
continue;
}
else if (expr[cursor] != '=')
throw new CompileException("unexpected operator '!'", expr, cursor, null);
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'[':
case'{':
if (balancedCapture(expr[cursor]) == -1) {
if (cursor >= length) cursor--;
throw new CompileException("unbalanced brace: in inline map/list/array creation", expr, cursor);
}
if (cursor < (length - 1) && expr[cursor + 1] == '.') {
fields |= ASTNode.INLINE_COLLECTION;
cursor++;
continue;
}
return new InlineCollectionNode(expr, start, ++cursor, fields);
default:
cursor++;
}
}
return createPropertyToken(start, cursor);
}
#location 508
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static Class findClass(VariableResolverFactory factory, String name, ParserContext ctx) throws ClassNotFoundException {
try {
if (LITERALS.containsKey(name)) {
return (Class) LITERALS.get(name);
}
else if (factory != null && factory.isResolveable(name)) {
return (Class) factory.getVariableResolver(name).getValue();
}
else {
return createClass(name, ctx);
}
}
catch (ClassNotFoundException e) {
throw e;
}
catch (Exception e) {
throw new CompileException("class not found: " + name, e);
}
} | #vulnerable code
public static Class findClass(VariableResolverFactory factory, String name, ParserContext ctx) throws ClassNotFoundException {
try {
if (LITERALS.containsKey(name)) {
return (Class) LITERALS.get(name);
}
else if (factory != null && factory.isResolveable(name)) {
return (Class) factory.getVariableResolver(name).getValue();
}
else if (ctx != null && ctx.hasImport(name)) {
return getCurrentThreadParserContext().getImport(name);
}
else {
return createClass(name);
}
}
catch (ClassNotFoundException e) {
throw e;
}
catch (Exception e) {
throw new CompileException("class not found: " + name, e);
}
}
#location 10
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
synchronized (Runtime.getRuntime()) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 128
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void runTest(PerfTest test, int count) throws Exception {
int exFlags = test.getRunFlags();
String expression = test.getExpression();
String name = test.getName();
if (!silent) {
System.out.println("Test Name : " + test.getName());
System.out.println("Expression : " + test.getExpression());
System.out.println("Iterations : " + count);
}
long time;
long mem;
long total = 0;
long[] res = new long[TESTITER];
if ((testFlags & INTERPRETED) != 0) {
if (!silent) System.out.println("Interpreted Results :");
if ((testFlags & RUN_OGNL) != 0 && ((exFlags & RUN_OGNL)) != 0) {
try {
// unbenched warm-up
for (int i = 0; i < count; i++) {
// Ognl.getValue(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
// Ognl.getValue(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(OGNL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(OGNL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
ognlTotal += total;
}
total = 0;
if ((testFlags & RUN_MVEL) != 0 && ((exFlags & RUN_MVEL) != 0)) {
try {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(MVEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
e.printStackTrace();
if (!silent)
System.out.println("(MVEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
mvelTotal += total;
}
//
// total = 0;
//
// if ((testFlags & RUN_GROOVY) != 0 && ((exFlags & RUN_GROOVY) != 0)) {
// try {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
//
// time = currentTimeMillis();
// mem = Runtime.getRuntime().freeMemory();
// for (int reps = 0; reps < TESTITER; reps++) {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
// if (reps == 0) res[0] = total += currentTimeMillis() - time;
// else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
// }
//
// if (!silent)
// System.out.println("(Groovy) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
// + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
//
// }
// catch (Exception e) {
// e.printStackTrace();
//
// if (!silent)
// System.out.println("(Groovy) : <<COULD NOT EXECUTE>>");
// }
// }
//
// synchronized (this) {
// groovyTotal += total;
// }
//
total = 0;
if ((testFlags & RUN_COMMONS_EL) != 0 && ((exFlags & RUN_COMMONS_EL) != 0)) {
VariableResolver vars = new JSPMapVariableResolver(variables);
String commonsEx = "${" + expression + "}";
try {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(CommonsEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(CommonsEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
commonElTotal += total;
}
}
if ((testFlags & COMPILED) != 0) {
runTestCompiled(name, test.getOgnlCompiled(), test.getMvelCompiled(), test.getGroovyCompiled(), test.getElCompiled(), count, exFlags);
}
total = 0;
if ((testFlags & RUN_JAVA_NATIVE) != 0 && ((exFlags & RUN_JAVA_NATIVE) != 0)) {
NativeTest nt = test.getJavaNative();
try {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(JavaNative) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(JavaNative) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
javaNativeTotal += total;
}
if (!silent)
System.out.println("------------------------------------------------");
} | #vulnerable code
public void runTest(PerfTest test, int count) throws Exception {
int exFlags = test.getRunFlags();
String expression = test.getExpression();
String name = test.getName();
if (!silent) {
System.out.println("Test Name : " + test.getName());
System.out.println("Expression : " + test.getExpression());
System.out.println("Iterations : " + count);
}
long time;
long mem;
long total = 0;
long[] res = new long[TESTITER];
if ((testFlags & INTERPRETED) != 0) {
if (!silent) System.out.println("Interpreted Results :");
if ((testFlags & RUN_OGNL) != 0 && ((exFlags & RUN_OGNL)) != 0) {
try {
// unbenched warm-up
for (int i = 0; i < count; i++) {
Ognl.getValue(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
Ognl.getValue(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(OGNL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(OGNL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
ognlTotal += total;
}
total = 0;
if ((testFlags & RUN_MVEL) != 0 && ((exFlags & RUN_MVEL) != 0)) {
try {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(MVEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
e.printStackTrace();
if (!silent)
System.out.println("(MVEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
mvelTotal += total;
}
//
// total = 0;
//
// if ((testFlags & RUN_GROOVY) != 0 && ((exFlags & RUN_GROOVY) != 0)) {
// try {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
//
// time = currentTimeMillis();
// mem = Runtime.getRuntime().freeMemory();
// for (int reps = 0; reps < TESTITER; reps++) {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
// if (reps == 0) res[0] = total += currentTimeMillis() - time;
// else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
// }
//
// if (!silent)
// System.out.println("(Groovy) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
// + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
//
// }
// catch (Exception e) {
// e.printStackTrace();
//
// if (!silent)
// System.out.println("(Groovy) : <<COULD NOT EXECUTE>>");
// }
// }
//
// synchronized (this) {
// groovyTotal += total;
// }
//
total = 0;
if ((testFlags & RUN_COMMONS_EL) != 0 && ((exFlags & RUN_COMMONS_EL) != 0)) {
VariableResolver vars = new JSPMapVariableResolver(variables);
String commonsEx = "${" + expression + "}";
try {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(CommonsEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(CommonsEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
commonElTotal += total;
}
}
if ((testFlags & COMPILED) != 0) {
runTestCompiled(name, test.getOgnlCompiled(), test.getMvelCompiled(), test.getGroovyCompiled(), test.getElCompiled(), count, exFlags);
}
total = 0;
if ((testFlags & RUN_JAVA_NATIVE) != 0 && ((exFlags & RUN_JAVA_NATIVE) != 0)) {
NativeTest nt = test.getJavaNative();
try {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(JavaNative) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(JavaNative) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
javaNativeTotal += total;
}
if (!silent)
System.out.println("------------------------------------------------");
}
#location 65
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object execute(Object ctx, Map tokens) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
// return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens);
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, MVEL.compileExpression(s));
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
ExpressionParser oParser = new ExpressionParser(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = ( ForeachContext ) currNode.getRegister();
if ( foreachContext.getItererators() == null ) {
try {
String[] lists = getForEachSegment(currNode).split( "," );
Iterator[] iters = new Iterator[lists.length];
for( int i = 0; i < lists.length; i++ ) {
Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse();
if ( listObject instanceof Object[]) {
listObject = Arrays.asList( (Object[]) listObject );
}
iters[i] = ((Collection)listObject).iterator() ;
}
foreachContext.setIterators( iters );
} catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split( "," );
// must trim vars
for ( int i = 0; i < alias.length; i++ ) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for ( int i = 0; i < iters.length; i++ ) {
tokens.put(alias[i], iters[i].next());
}
if ( foreachContext.getCount() != 0 ) {
sbuf.append( foreachContext.getSeperator() );
}
foreachContext.setCount( foreachContext.getCount( ) + 1 );
}
else {
for ( int i = 0; i < iters.length; i++ ) {
tokens.remove(alias[i]);
}
foreachContext.setIterators( null );
foreachContext.setCount( 0 );
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length == 2) {
return register;
}
else {
return sbuf.toString();
}
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}", e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
// return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens);
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, MVEL.compileExpression(s));
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
ExpressionParser oParser = new ExpressionParser(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
String seperator = "";
if (currNode.getRegister() == null || currNode.getRegister() instanceof String) {
try {
String props = ( String) currNode.getRegister();
if ( props != null && props.length() > 0 ) {
seperator = props;
}
String[] lists = getForEachSegment(currNode).split( "," );
Iterator[] iters = new Iterator[lists.length];
for( int i = 0; i < lists.length; i++ ) {
Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse();
if ( listObject instanceof Object[]) {
listObject = Arrays.asList( (Object[]) listObject );
}
iters[i] = ((Collection)listObject).iterator() ;
}
currNode.setRegister( iters );
} catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = (Iterator[]) currNode.getRegister();
String[] alias = currNode.getAlias().split( "," );
// must trim vars
for ( int i = 0; i < alias.length; i++ ) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for ( int i = 0; i < iters.length; i++ ) {
tokens.put(alias[i], iters[i].next());
}
sbuf.append( seperator );
}
else {
for ( int i = 0; i < iters.length; i++ ) {
tokens.remove(alias[i]);
}
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length == 2) {
return register;
}
else {
return sbuf.toString();
}
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}", e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 102
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public HmilyParticipant preTryParticipant(final HmilyTransactionContext context, final ProceedingJoinPoint point) {
LogUtil.debug(LOGGER, "participant hmily tcc transaction start..:{}", context::toString);
final HmilyParticipant hmilyParticipant = buildHmilyParticipant(point, context.getParticipantId(), context.getParticipantRefId(), HmilyRoleEnum.PARTICIPANT.getCode(), context.getTransId());
HmilyTransactionHolder.getInstance().cacheHmilyParticipant(hmilyParticipant);
HmilyRepositoryStorage.createHmilyParticipant(hmilyParticipant);
//publishEvent
//Nested transaction support
context.setRole(HmilyRoleEnum.PARTICIPANT.getCode());
HmilyContextHolder.set(context);
return hmilyParticipant;
} | #vulnerable code
public HmilyParticipant preTryParticipant(final HmilyTransactionContext context, final ProceedingJoinPoint point) {
LogUtil.debug(LOGGER, "participant hmily tcc transaction start..:{}", context::toString);
final HmilyParticipant hmilyParticipant = buildHmilyParticipant(point, context.getParticipantId(), context.getParticipantRefId(), HmilyRoleEnum.PARTICIPANT.getCode(), context.getTransId());
//cache by guava
if (Objects.nonNull(hmilyParticipant)) {
HmilyParticipantCacheManager.getInstance().cacheHmilyParticipant(hmilyParticipant);
PUBLISHER.publishEvent(hmilyParticipant, EventTypeEnum.CREATE_HMILY_PARTICIPANT.getCode());
}
//publishEvent
//Nested transaction support
context.setRole(HmilyRoleEnum.PARTICIPANT.getCode());
HmilyContextHolder.set(context);
return hmilyParticipant;
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@SafeVarargs
public static Type wrapInArrayTypes(Type type, List<ArrayBracketPair>... arrayBracketPairLists) {
for (int i = arrayBracketPairLists.length - 1; i >= 0; i--) {
final List<ArrayBracketPair> arrayBracketPairList = arrayBracketPairLists[i];
if (arrayBracketPairList != null) {
for (int j = arrayBracketPairList.size() - 1; j >= 0; j--) {
ArrayBracketPair pair = arrayBracketPairList.get(j);
TokenRange tokenRange = null;
if (type.getTokenRange().isPresent() && pair.getTokenRange().isPresent()) {
tokenRange = new TokenRange(type.getTokenRange().get().getBegin(), pair.getTokenRange().get().getEnd());
}
type = new ArrayType(tokenRange, type, pair.getAnnotations());
if (tokenRange != null) {
type.setRange(tokenRange.toRange().get());
}
}
}
}
return type;
} | #vulnerable code
@SafeVarargs
public static Type wrapInArrayTypes(Type type, List<ArrayBracketPair>... arrayBracketPairLists) {
for (int i = arrayBracketPairLists.length - 1; i >= 0; i--) {
final List<ArrayBracketPair> arrayBracketPairList = arrayBracketPairLists[i];
if (arrayBracketPairList != null) {
for (int j = arrayBracketPairList.size() - 1; j >= 0; j--) {
ArrayBracketPair pair = arrayBracketPairList.get(j);
TokenRange tokenRange = null;
if (type.getTokenRange().isPresent() && pair.getTokenRange().isPresent()) {
tokenRange = new TokenRange(type.getTokenRange().get().getBegin(), pair.getTokenRange().get().getEnd());
}
type = new ArrayType(tokenRange, type, pair.getAnnotations());
if (tokenRange != null) {
type.setRange(tokenRange.toRange());
}
}
}
}
return type;
}
#location 12
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Optional<MethodUsage> solveMethodAsUsage(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver) {
// TODO consider call of static methods
if (wrappedNode.getScope() != null) {
try {
TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getType(wrappedNode.getScope());
return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
} catch (UnsolvedSymbolException e){
// ok, maybe it was instead a static access, so let's look for a type
if (wrappedNode.getScope() instanceof NameExpr){
String className = ((NameExpr)wrappedNode.getScope()).getName();
SymbolReference<TypeDeclaration> ref = solveType(className, typeSolver);
if (ref.isSolved()) {
SymbolReference<MethodDeclaration> m = ref.getCorrespondingDeclaration().solveMethod(name, parameterTypes, typeSolver);
if (m.isSolved()) {
return Optional.of(new MethodUsage(m.getCorrespondingDeclaration(), typeSolver));
}
}
}
throw e;
}
} else {
if (wrappedNode.getParentNode() instanceof MethodCallExpr) {
MethodCallExpr parent = (MethodCallExpr)wrappedNode.getParentNode();
if (parent.getScope() == wrappedNode) {
return getParent().getParent().solveMethodAsUsage(name, parameterTypes, typeSolver);
}
}
//TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode);
//return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
Context parentContext = getParent();
//System.out.println("NAME "+name);
return parentContext.solveMethodAsUsage(name, parameterTypes, typeSolver);
}
} | #vulnerable code
@Override
public Optional<MethodUsage> solveMethodAsUsage(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver) {
// TODO consider call of static methods
if (wrappedNode.getScope() != null) {
try {
TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getType(wrappedNode.getScope());
return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
} catch (UnsolvedSymbolException e){
// ok, maybe it was instead a static access, so let's look for a type
if (wrappedNode.getScope() instanceof NameExpr){
String className = ((NameExpr)wrappedNode.getScope()).getName();
SymbolReference<TypeDeclaration> ref = solveType(className, typeSolver);
if (ref.isSolved()) {
SymbolReference<MethodDeclaration> m = ref.getCorrespondingDeclaration().solveMethod(name, parameterTypes, typeSolver);
if (m.isSolved()) {
return Optional.of(new MethodUsage(m.getCorrespondingDeclaration(), typeSolver));
}
}
}
throw e;
}
} else {
//TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode);
//return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
return getParent().solveMethodAsUsage(name, parameterTypes, typeSolver);
}
}
#location 25
#vulnerability type NULL_DEREFERENCE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.