input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
private PhotometricInterpreter getPhotometricInterpreter(
final TiffDirectory directory, final int photometricInterpretation,
final int bitsPerPixel, final int bitsPerSample[], final int predictor,
final int samplesPerPixel, final int width, final int height)
throws ImageReadException {
switch (photometricInterpretation) {
case 0:
case 1:
final boolean invert = photometricInterpretation == 0;
return new PhotometricInterpreterBiLevel(bitsPerPixel,
samplesPerPixel, bitsPerSample, predictor, width, height,
invert);
case 3: // Palette
{
final int colorMap[] = directory.findField(
TiffTagConstants.TIFF_TAG_COLOR_MAP, true)
.getIntArrayValue();
final int expected_colormap_size = 3 * (1 << bitsPerPixel);
if (colorMap.length != expected_colormap_size) {
throw new ImageReadException("Tiff: fColorMap.length ("
+ colorMap.length + ")!=expected_colormap_size ("
+ expected_colormap_size + ")");
}
return new PhotometricInterpreterPalette(samplesPerPixel,
bitsPerSample, predictor, width, height, colorMap);
}
case 2: // RGB
return new PhotometricInterpreterRgb(samplesPerPixel,
bitsPerSample, predictor, width, height);
case 5: // CMYK
return new PhotometricInterpreterCmyk(samplesPerPixel,
bitsPerSample, predictor, width, height);
case 6: //
{
final double yCbCrCoefficients[] = directory.findField(
TiffTagConstants.TIFF_TAG_YCBCR_COEFFICIENTS, true)
.getDoubleArrayValue();
final int yCbCrPositioning[] = directory.findField(
TiffTagConstants.TIFF_TAG_YCBCR_POSITIONING, true)
.getIntArrayValue();
final int yCbCrSubSampling[] = directory.findField(
TiffTagConstants.TIFF_TAG_YCBCR_SUB_SAMPLING, true)
.getIntArrayValue();
final double referenceBlackWhite[] = directory.findField(
TiffTagConstants.TIFF_TAG_REFERENCE_BLACK_WHITE, true)
.getDoubleArrayValue();
return new PhotometricInterpreterYCbCr(yCbCrCoefficients,
yCbCrPositioning, yCbCrSubSampling, referenceBlackWhite,
samplesPerPixel, bitsPerSample, predictor, width, height);
}
case 8:
return new PhotometricInterpreterCieLab(samplesPerPixel,
bitsPerSample, predictor, width, height);
case 32844:
case 32845: {
final boolean yonly = (photometricInterpretation == 32844);
return new PhotometricInterpreterLogLuv(samplesPerPixel,
bitsPerSample, predictor, width, height, yonly);
}
default:
throw new ImageReadException(
"TIFF: Unknown fPhotometricInterpretation: "
+ photometricInterpretation);
}
}
#location 41
#vulnerability type NULL_DEREFERENCE | #fixed code
private PhotometricInterpreter getPhotometricInterpreter(
final TiffDirectory directory, final int photometricInterpretation,
final int bitsPerPixel, final int bitsPerSample[], final int predictor,
final int samplesPerPixel, final int width, final int height)
throws ImageReadException {
switch (photometricInterpretation) {
case 0:
case 1:
final boolean invert = photometricInterpretation == 0;
return new PhotometricInterpreterBiLevel(samplesPerPixel,
bitsPerSample, predictor, width, height, invert);
case 3: // Palette
{
final int colorMap[] = directory.findField(
TiffTagConstants.TIFF_TAG_COLOR_MAP, true)
.getIntArrayValue();
final int expected_colormap_size = 3 * (1 << bitsPerPixel);
if (colorMap.length != expected_colormap_size) {
throw new ImageReadException("Tiff: fColorMap.length ("
+ colorMap.length + ")!=expected_colormap_size ("
+ expected_colormap_size + ")");
}
return new PhotometricInterpreterPalette(samplesPerPixel,
bitsPerSample, predictor, width, height, colorMap);
}
case 2: // RGB
return new PhotometricInterpreterRgb(samplesPerPixel,
bitsPerSample, predictor, width, height);
case 5: // CMYK
return new PhotometricInterpreterCmyk(samplesPerPixel,
bitsPerSample, predictor, width, height);
case 6: //
{
// final double yCbCrCoefficients[] = directory.findField(
// TiffTagConstants.TIFF_TAG_YCBCR_COEFFICIENTS, true)
// .getDoubleArrayValue();
//
// final int yCbCrPositioning[] = directory.findField(
// TiffTagConstants.TIFF_TAG_YCBCR_POSITIONING, true)
// .getIntArrayValue();
// final int yCbCrSubSampling[] = directory.findField(
// TiffTagConstants.TIFF_TAG_YCBCR_SUB_SAMPLING, true)
// .getIntArrayValue();
//
// final double referenceBlackWhite[] = directory.findField(
// TiffTagConstants.TIFF_TAG_REFERENCE_BLACK_WHITE, true)
// .getDoubleArrayValue();
return new PhotometricInterpreterYCbCr(samplesPerPixel,
bitsPerSample, predictor, width,
height);
}
case 8:
return new PhotometricInterpreterCieLab(samplesPerPixel,
bitsPerSample, predictor, width, height);
case 32844:
case 32845: {
// final boolean yonly = (photometricInterpretation == 32844);
return new PhotometricInterpreterLogLuv(samplesPerPixel,
bitsPerSample, predictor, width, height);
}
default:
throw new ImageReadException(
"TIFF: Unknown fPhotometricInterpretation: "
+ photometricInterpretation);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static byte[] decompressModifiedHuffman(final byte[] compressed,
final int width, final int height) throws ImageReadException {
final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(
new ByteArrayInputStream(compressed));
BitArrayOutputStream outputStream = null;
boolean canThrow = false;
try {
outputStream = new BitArrayOutputStream();
for (int y = 0; y < height; y++) {
int color = WHITE;
int rowLength;
for (rowLength = 0; rowLength < width;) {
final int runLength = readTotalRunLength(inputStream, color);
for (int i = 0; i < runLength; i++) {
outputStream.writeBit(color);
}
color = 1 - color;
rowLength += runLength;
}
if (rowLength == width) {
inputStream.flushCache();
outputStream.flush();
} else if (rowLength > width) {
throw new ImageReadException("Unrecoverable row length error in image row " + y);
}
}
final byte[] ret = outputStream.toByteArray();
canThrow = true;
return ret;
} finally {
try {
IoUtils.closeQuietly(canThrow, outputStream);
} catch (final IOException ioException) {
throw new ImageReadException("I/O error", ioException);
}
}
}
#location 28
#vulnerability type RESOURCE_LEAK | #fixed code
public static byte[] decompressModifiedHuffman(final byte[] compressed,
final int width, final int height) throws ImageReadException {
try (ByteArrayInputStream baos = new ByteArrayInputStream(compressed);
BitInputStreamFlexible inputStream = new BitInputStreamFlexible(baos);
BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
for (int y = 0; y < height; y++) {
int color = WHITE;
int rowLength;
for (rowLength = 0; rowLength < width;) {
final int runLength = readTotalRunLength(inputStream, color);
for (int i = 0; i < runLength; i++) {
outputStream.writeBit(color);
}
color = 1 - color;
rowLength += runLength;
}
if (rowLength == width) {
inputStream.flushCache();
outputStream.flush();
} else if (rowLength > width) {
throw new ImageReadException("Unrecoverable row length error in image row " + y);
}
}
final byte[] ret = outputStream.toByteArray();
return ret;
} catch (final IOException ioException) {
throw new ImageReadException("Error reading image to decompress", ioException);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected List<IptcBlock> parseAllBlocks(byte bytes[], boolean verbose,
boolean strict) throws ImageReadException, IOException {
List<IptcBlock> blocks = new ArrayList<IptcBlock>();
BinaryInputStream bis = new BinaryInputStream(bytes, APP13_BYTE_ORDER);
// Note that these are unsigned quantities. Name is always an even
// number of bytes (including the 1st byte, which is the size.)
byte[] idString = bis.readByteArray(
PHOTOSHOP_IDENTIFICATION_STRING.size(),
"App13 Segment missing identification string");
if (!PHOTOSHOP_IDENTIFICATION_STRING.equals(idString))
throw new ImageReadException("Not a Photoshop App13 Segment");
// int index = PHOTOSHOP_IDENTIFICATION_STRING.length;
while (true) {
byte[] imageResourceBlockSignature = bis
.readByteArray(CONST_8BIM.size(),
"App13 Segment missing identification string",
false, false);
if (null == imageResourceBlockSignature)
break;
if (!CONST_8BIM.equals(imageResourceBlockSignature))
throw new ImageReadException(
"Invalid Image Resource Block Signature");
int blockType = bis
.read2ByteInteger("Image Resource Block missing type");
if (verbose)
Debug.debug("blockType",
blockType + " (0x" + Integer.toHexString(blockType)
+ ")");
int blockNameLength = bis
.read1ByteInteger("Image Resource Block missing name length");
if (verbose && blockNameLength > 0)
Debug.debug("blockNameLength", blockNameLength + " (0x"
+ Integer.toHexString(blockNameLength) + ")");
byte[] blockNameBytes;
if (blockNameLength == 0) {
bis.read1ByteInteger("Image Resource Block has invalid name");
blockNameBytes = new byte[0];
} else {
blockNameBytes = bis.readByteArray(blockNameLength,
"Invalid Image Resource Block name", verbose, strict);
if (null == blockNameBytes)
break;
if (blockNameLength % 2 == 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
int blockSize = bis
.read4ByteInteger("Image Resource Block missing size");
if (verbose)
Debug.debug("blockSize",
blockSize + " (0x" + Integer.toHexString(blockSize)
+ ")");
/*
* doesn't catch cases where blocksize is invalid but is still less
* than bytes.length but will at least prevent OutOfMemory errors
*/
if (blockSize > bytes.length) {
throw new ImageReadException("Invalid Block Size : "
+ blockSize + " > " + bytes.length);
}
byte[] blockData = bis.readByteArray(blockSize,
"Invalid Image Resource Block data", verbose, strict);
if (null == blockData)
break;
blocks.add(new IptcBlock(blockType, blockNameBytes, blockData));
if ((blockSize % 2) != 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
return blocks;
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
protected List<IptcBlock> parseAllBlocks(byte bytes[], boolean verbose,
boolean strict) throws ImageReadException, IOException {
List<IptcBlock> blocks = new ArrayList<IptcBlock>();
BinaryInputStream bis = null;
try {
bis = new BinaryInputStream(bytes, APP13_BYTE_ORDER);
// Note that these are unsigned quantities. Name is always an even
// number of bytes (including the 1st byte, which is the size.)
byte[] idString = bis.readByteArray(
PHOTOSHOP_IDENTIFICATION_STRING.size(),
"App13 Segment missing identification string");
if (!PHOTOSHOP_IDENTIFICATION_STRING.equals(idString))
throw new ImageReadException("Not a Photoshop App13 Segment");
// int index = PHOTOSHOP_IDENTIFICATION_STRING.length;
while (true) {
byte[] imageResourceBlockSignature = bis
.readByteArray(CONST_8BIM.size(),
"App13 Segment missing identification string",
false, false);
if (null == imageResourceBlockSignature)
break;
if (!CONST_8BIM.equals(imageResourceBlockSignature))
throw new ImageReadException(
"Invalid Image Resource Block Signature");
int blockType = bis
.read2ByteInteger("Image Resource Block missing type");
if (verbose)
Debug.debug("blockType",
blockType + " (0x" + Integer.toHexString(blockType)
+ ")");
int blockNameLength = bis
.read1ByteInteger("Image Resource Block missing name length");
if (verbose && blockNameLength > 0)
Debug.debug("blockNameLength", blockNameLength + " (0x"
+ Integer.toHexString(blockNameLength) + ")");
byte[] blockNameBytes;
if (blockNameLength == 0) {
bis.read1ByteInteger("Image Resource Block has invalid name");
blockNameBytes = new byte[0];
} else {
blockNameBytes = bis.readByteArray(blockNameLength,
"Invalid Image Resource Block name", verbose, strict);
if (null == blockNameBytes)
break;
if (blockNameLength % 2 == 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
int blockSize = bis
.read4ByteInteger("Image Resource Block missing size");
if (verbose)
Debug.debug("blockSize",
blockSize + " (0x" + Integer.toHexString(blockSize)
+ ")");
/*
* doesn't catch cases where blocksize is invalid but is still less
* than bytes.length but will at least prevent OutOfMemory errors
*/
if (blockSize > bytes.length) {
throw new ImageReadException("Invalid Block Size : "
+ blockSize + " > " + bytes.length);
}
byte[] blockData = bis.readByteArray(blockSize,
"Invalid Image Resource Block data", verbose, strict);
if (null == blockData)
break;
blocks.add(new IptcBlock(blockType, blockNameBytes, blockData));
if ((blockSize % 2) != 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
return blocks;
} finally {
if (bis != null) {
bis.close();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void changeExifMetadata(final File jpegImageFile, final File dst)
throws IOException, ImageReadException, ImageWriteException {
OutputStream os = null;
boolean canThrow = false;
try {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
// if file does not contain any exif metadata, we create an empty
// set of exif metadata. Otherwise, we keep all of the other
// existing tags.
if (null == outputSet) {
outputSet = new TiffOutputSet();
}
{
// Example of how to add a field/tag to the output set.
//
// Note that you should first remove the field/tag if it already
// exists in this directory, or you may end up with duplicate
// tags. See above.
//
// Certain fields/tags are expected in certain Exif directories;
// Others can occur in more than one directory (and often have a
// different meaning in different directories).
//
// TagInfo constants often contain a description of what
// directories are associated with a given tag.
//
final TiffOutputDirectory exifDirectory = outputSet
.getOrCreateExifDirectory();
// make sure to remove old value if present (this method will
// not fail if the tag does not exist).
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
exifDirectory.add(ExifTagConstants.EXIF_TAG_APERTURE_VALUE,
new RationalNumber(3, 10));
}
{
// Example of how to add/update GPS info to output set.
// New York City
final double longitude = -74.0; // 74 degrees W (in Degrees East)
final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
// North)
outputSet.setGPSInDegrees(longitude, latitude);
}
// printTagValue(jpegMetadata, TiffConstants.TIFF_TAG_DATE_TIME);
os = new FileOutputStream(dst);
os = new BufferedOutputStream(os);
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
}
#location 80
#vulnerability type RESOURCE_LEAK | #fixed code
public void changeExifMetadata(final File jpegImageFile, final File dst)
throws IOException, ImageReadException, ImageWriteException {
try (FileOutputStream fos = new FileOutputStream(dst);
OutputStream os = new BufferedOutputStream(fos);) {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
// if file does not contain any exif metadata, we create an empty
// set of exif metadata. Otherwise, we keep all of the other
// existing tags.
if (null == outputSet) {
outputSet = new TiffOutputSet();
}
{
// Example of how to add a field/tag to the output set.
//
// Note that you should first remove the field/tag if it already
// exists in this directory, or you may end up with duplicate
// tags. See above.
//
// Certain fields/tags are expected in certain Exif directories;
// Others can occur in more than one directory (and often have a
// different meaning in different directories).
//
// TagInfo constants often contain a description of what
// directories are associated with a given tag.
//
final TiffOutputDirectory exifDirectory = outputSet
.getOrCreateExifDirectory();
// make sure to remove old value if present (this method will
// not fail if the tag does not exist).
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
exifDirectory.add(ExifTagConstants.EXIF_TAG_APERTURE_VALUE,
new RationalNumber(3, 10));
}
{
// Example of how to add/update GPS info to output set.
// New York City
final double longitude = -74.0; // 74 degrees W (in Degrees East)
final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
// North)
outputSet.setGPSInDegrees(longitude, latitude);
}
// printTagValue(jpegMetadata, TiffConstants.TIFF_TAG_DATE_TIME);
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testRemove() throws Exception {
final ByteSource byteSource = new ByteSourceFile(imageFile);
final Map<String, Object> params = new HashMap<String, Object>();
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
params.put(PARAM_KEY_READ_THUMBNAILS, new Boolean(!ignoreImageData));
final JpegPhotoshopMetadata metadata = new JpegImageParser()
.getPhotoshopMetadata(byteSource, params);
assertNotNull(metadata);
// metadata.dump();
final File noIptcFile = createTempFile(imageFile.getName()
+ ".iptc.remove.", ".jpg");
{
// test remove
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(noIptcFile);
os = new BufferedOutputStream(os);
new JpegIptcRewriter().removeIPTC(byteSource, os);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
final JpegPhotoshopMetadata outMetadata = new JpegImageParser()
.getPhotoshopMetadata(new ByteSourceFile(noIptcFile),
params);
assertTrue(outMetadata == null
|| outMetadata.getItems().size() == 0);
}
}
#location 27
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testRemove() throws Exception {
final ByteSource byteSource = new ByteSourceFile(imageFile);
final Map<String, Object> params = new HashMap<String, Object>();
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
params.put(PARAM_KEY_READ_THUMBNAILS, Boolean.valueOf(!ignoreImageData));
final JpegPhotoshopMetadata metadata = new JpegImageParser()
.getPhotoshopMetadata(byteSource, params);
assertNotNull(metadata);
final File noIptcFile = removeIptc(byteSource);
final JpegPhotoshopMetadata outMetadata = new JpegImageParser()
.getPhotoshopMetadata(new ByteSourceFile(noIptcFile),
params);
// FIXME should either be null or empty
assertTrue(outMetadata == null
|| outMetadata.getItems().size() == 0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testImaging144() throws Exception {
tiffOutputSet.setGPSInDegrees(1.0, 1.0);
TiffOutputDirectory gpsDirectory = tiffOutputSet.getGPSDirectory();
TiffOutputField gpsVersionId = gpsDirectory.findField(GpsTagConstants.GPS_TAG_GPS_VERSION_ID);
assertNotNull(gpsVersionId);
assertTrue(gpsVersionId.bytesEqual(GpsTagConstants.GPS_VERSION));
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testImaging144() throws Exception {
tiffOutputSet.setGPSInDegrees(1.0, 1.0);
TiffOutputField gpsVersionId = tiffOutputSet.findField(GpsTagConstants.GPS_TAG_GPS_VERSION_ID);
assertNotNull(gpsVersionId);
assertTrue(gpsVersionId.bytesEqual(GpsTagConstants.GPS_VERSION));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void test() throws Exception {
String imagesFolderPath = FilenameUtils
.separatorsToSystem("src\\test\\data\\images\\png\\3");
File imagesFolder = new File(imagesFolderPath);
assertTrue(imagesFolder.exists() && imagesFolder.isDirectory());
File files[] = imagesFolder.listFiles();
for (int i = 0; i < files.length; i++) {
File imageFile = files[i];
if (!imageFile.isFile())
continue;
if (!imageFile.getName().toLowerCase().endsWith(".png"))
continue;
Debug.debug();
Debug.debug("imageFile", imageFile);
File lastFile = imageFile;
for (int j = 0; j < 10; j++) {
Map<String,Object> readParams = new HashMap<String,Object>();
// readParams.put(SanselanConstants.BUFFERED_IMAGE_FACTORY,
// new RgbBufferedImageFactory());
BufferedImage image = Imaging.getBufferedImage(lastFile,
readParams);
assertNotNull(image);
File tempFile = createTempFile(imageFile.getName() + "." + j
+ ".", ".png");
Debug.debug("tempFile", tempFile);
Map<String,Object> writeParams = new HashMap<String,Object>();
Imaging.writeImage(image, tempFile,
ImageFormat.IMAGE_FORMAT_PNG, writeParams);
lastFile = tempFile;
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public void test() throws Exception {
String imagesFolderPath = FilenameUtils
.separatorsToSystem("src\\test\\data\\images\\png\\3");
File imagesFolder = new File(imagesFolderPath);
assertTrue(imagesFolder.exists() && imagesFolder.isDirectory());
File files[] = imagesFolder.listFiles();
for (File file : files) {
File imageFile = file;
if (!imageFile.isFile())
continue;
if (!imageFile.getName().toLowerCase().endsWith(".png"))
continue;
Debug.debug();
Debug.debug("imageFile", imageFile);
File lastFile = imageFile;
for (int j = 0; j < 10; j++) {
Map<String,Object> readParams = new HashMap<String,Object>();
// readParams.put(SanselanConstants.BUFFERED_IMAGE_FACTORY,
// new RgbBufferedImageFactory());
BufferedImage image = Imaging.getBufferedImage(lastFile,
readParams);
assertNotNull(image);
File tempFile = createTempFile(imageFile.getName() + "." + j
+ ".", ".png");
Debug.debug("tempFile", tempFile);
Map<String,Object> writeParams = new HashMap<String,Object>();
Imaging.writeImage(image, tempFile,
ImageFormat.IMAGE_FORMAT_PNG, writeParams);
lastFile = tempFile;
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testAll5x2Images() {
int[] combinations = new int[10];
BufferedImage image = new BufferedImage(5, 2, BufferedImage.TYPE_INT_RGB);
do {
for (int x = 0; x < 5; x++) {
if (combinations[x] == 0) {
image.setRGB(x, 0, 0xFFFFFF);
} else {
image.setRGB(x, 0, 0);
}
}
for (int x = 0; x < 5; x++) {
if (combinations[5 + x] == 0) {
image.setRGB(x, 1, 0xFFFFFF);
} else {
image.setRGB(x, 1, 0);
}
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_1D);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 0);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 4);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
FileOutputStream fos = new FileOutputStream("/tmp/test.tiff");
fos.write(compressed);
fos.close();
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 1);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 5);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_4);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
} while (nextCombination(combinations, 1));
}
#location 26
#vulnerability type RESOURCE_LEAK | #fixed code
public void testAll5x2Images() {
int[] combinations = new int[10];
BufferedImage image = new BufferedImage(5, 2, BufferedImage.TYPE_INT_RGB);
do {
for (int x = 0; x < 5; x++) {
if (combinations[x] == 0) {
image.setRGB(x, 0, 0xFFFFFF);
} else {
image.setRGB(x, 0, 0);
}
}
for (int x = 0; x < 5; x++) {
if (combinations[5 + x] == 0) {
image.setRGB(x, 1, 0xFFFFFF);
} else {
image.setRGB(x, 1, 0);
}
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_1D);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 0);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 4);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 1);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 5);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_4);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
} while (nextCombination(combinations, 1));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAddIptcData() throws Exception {
final ByteSource byteSource = new ByteSourceFile(imageFile);
final Map<String, Object> params = new HashMap<String, Object>();
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
params.put(PARAM_KEY_READ_THUMBNAILS, Boolean.valueOf(!ignoreImageData));
final JpegPhotoshopMetadata metadata = new JpegImageParser().getPhotoshopMetadata(byteSource, params);
{
final List<IptcBlock> newBlocks = new ArrayList<IptcBlock>();
List<IptcRecord> newRecords = new ArrayList<IptcRecord>();
if (null != metadata) {
final boolean keepOldIptcNonTextValues = true;
if (keepOldIptcNonTextValues) {
newBlocks.addAll(metadata.photoshopApp13Data
.getNonIptcBlocks());
}
final boolean keepOldIptcTextValues = true;
if (keepOldIptcTextValues) {
final List<IptcRecord> oldRecords = metadata.photoshopApp13Data
.getRecords();
newRecords = new ArrayList<IptcRecord>();
for (int j = 0; j < oldRecords.size(); j++) {
final IptcRecord record = oldRecords.get(j);
if (record.iptcType != IptcTypes.CITY
&& record.iptcType != IptcTypes.CREDIT) {
newRecords.add(record);
}
}
}
}
newRecords.add(new IptcRecord(IptcTypes.CITY, "Albany, NY"));
newRecords.add(new IptcRecord(IptcTypes.CREDIT,
"William Sorensen"));
final PhotoshopApp13Data newData = new PhotoshopApp13Data(newRecords,
newBlocks);
final File updated = createTempFile(imageFile.getName()
+ ".iptc.add.", ".jpg");
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(updated);
os = new BufferedOutputStream(os);
new JpegIptcRewriter().writeIPTC(byteSource, os, newData);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
// Debug.debug("Destination Segments:");
// new JpegUtils().dumpJFIF(new ByteSourceFile(updated));
final ByteSource updateByteSource = new ByteSourceFile(updated);
final JpegPhotoshopMetadata outMetadata = new JpegImageParser()
.getPhotoshopMetadata(updateByteSource, params);
// Debug.debug("outMetadata", outMetadata.toString());
// Debug.debug("hasIptcSegment", new JpegImageParser()
// .hasIptcSegment(updateByteSource));
assertNotNull(outMetadata);
assertTrue(outMetadata.getItems().size() == newRecords.size());
// assertEquals(metadata.toString(), outMetadata.toString());
}
}
#location 54
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAddIptcData() throws Exception {
final ByteSource byteSource = new ByteSourceFile(imageFile);
final Map<String, Object> params = new HashMap<String, Object>();
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
params.put(PARAM_KEY_READ_THUMBNAILS, Boolean.valueOf(!ignoreImageData));
final JpegPhotoshopMetadata metadata = new JpegImageParser().getPhotoshopMetadata(byteSource, params);
if (metadata == null) {
// FIXME select only files with meta for this test
return;
}
final List<IptcBlock> newBlocks = new ArrayList<IptcBlock>();
newBlocks.addAll(metadata.photoshopApp13Data.getNonIptcBlocks());
final List<IptcRecord> oldRecords = metadata.photoshopApp13Data.getRecords();
List<IptcRecord> newRecords = new ArrayList<IptcRecord>();
for (final IptcRecord record : oldRecords) {
if (record.iptcType != IptcTypes.CITY
&& record.iptcType != IptcTypes.CREDIT) {
newRecords.add(record);
}
}
newRecords.add(new IptcRecord(IptcTypes.CITY, "Albany, NY"));
newRecords.add(new IptcRecord(IptcTypes.CREDIT, "William Sorensen"));
final PhotoshopApp13Data newData = new PhotoshopApp13Data(newRecords, newBlocks);
final File updated = createTempFile(imageFile.getName() + ".iptc.add.", ".jpg");
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(updated);
os = new BufferedOutputStream(os);
new JpegIptcRewriter().writeIPTC(byteSource, os, newData);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
final ByteSource updateByteSource = new ByteSourceFile(updated);
final JpegPhotoshopMetadata outMetadata = new JpegImageParser()
.getPhotoshopMetadata(updateByteSource, params);
assertNotNull(outMetadata);
assertTrue(outMetadata.getItems().size() == newRecords.size());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void interpretStrip(
final ImageBuilder imageBuilder,
final byte[] bytes,
final int pixelsPerStrip,
final int yLimit) throws ImageReadException, IOException {
if (y >= yLimit) {
return;
}
// changes added May 2012
// In the original implementation, a general-case bit reader called
// getSamplesAsBytes is used to retrieve the samples (raw data values)
// for each pixel in the strip. These samples are then passed into a
// photogrammetric interpreter that converts them to ARGB pixel values
// and stores them in the image. Because the bit-reader must handle
// a large number of formats, it involves several conditional
// branches that must be executed each time a pixel is read.
// Depending on the size of an image, the same evaluations must be
// executed redundantly thousands and perhaps millions of times
// in order to process the complete collection of pixels.
// This code attempts to remove that redundancy by
// evaluating the format up-front and bypassing the general-format
// code for two commonly used data formats: the 8 bits-per-pixel
// and 24 bits-per-pixel cases. For these formats, the
// special case code achieves substantial reductions in image-loading
// time. In other cases, it simply falls through to the original code
// and continues to read the data correctly as it did in previous
// versions of this class.
// In addition to bypassing the getBytesForSample() method,
// the 24-bit case also implements a special block for RGB
// formatted images. To get a sense of the contributions of each
// optimization (removing getSamplesAsBytes and removing the
// photometric interpreter), consider the following results from tests
// conducted with large TIFF images using the 24-bit RGB format
// bypass getSamplesAsBytes: 67.5 % reduction
// bypass both optimizations: 77.2 % reduction
//
//
// Future Changes
// Both of the 8-bit and 24-bit blocks make the assumption that a strip
// always begins on x = 0 and that each strip exactly fills out the rows
// it contains (no half rows). The original code did not make this
// assumption, but the approach is consistent with the TIFF 6.0 spec
// (1992),
// and should probably be considered as an enhancement to the
// original general-case code block that remains from the original
// implementation. Taking this approach saves one conditional
// operation per pixel or about 5 percent of the total run time
// in the 8 bits/pixel case.
// verify that all samples are one byte in size
final boolean allSamplesAreOneByte = isHomogenous(8);
if (predictor != 2 && bitsPerPixel == 8 && allSamplesAreOneByte) {
int k = 0;
int nRows = pixelsPerStrip / width;
if (y + nRows > yLimit) {
nRows = yLimit - y;
}
final int i0 = y;
final int i1 = y + nRows;
x = 0;
y += nRows;
final int[] samples = new int[1];
for (int i = i0; i < i1; i++) {
for (int j = 0; j < width; j++) {
samples[0] = bytes[k++] & 0xff;
photometricInterpreter.interpretPixel(imageBuilder,
samples, j, i);
}
}
return;
} else if (predictor != 2 && bitsPerPixel == 24 && allSamplesAreOneByte) {
int k = 0;
int nRows = pixelsPerStrip / width;
if (y + nRows > yLimit) {
nRows = yLimit - y;
}
final int i0 = y;
final int i1 = y + nRows;
x = 0;
y += nRows;
if (photometricInterpreter instanceof PhotometricInterpreterRgb) {
for (int i = i0; i < i1; i++) {
for (int j = 0; j < width; j++, k += 3) {
final int rgb = 0xff000000
| (((bytes[k] << 8) | (bytes[k + 1] & 0xff)) << 8)
| (bytes[k + 2] & 0xff);
imageBuilder.setRGB(j, i, rgb);
}
}
} else {
final int[] samples = new int[3];
for (int i = i0; i < i1; i++) {
for (int j = 0; j < width; j++) {
samples[0] = bytes[k++] & 0xff;
samples[1] = bytes[k++] & 0xff;
samples[2] = bytes[k++] & 0xff;
photometricInterpreter.interpretPixel(imageBuilder,
samples, j, i);
}
}
}
return;
}
// ------------------------------------------------------------
// original code before May 2012 modification
// this logic will handle all cases not conforming to the
// special case handled above
final BitInputStream bis = new BitInputStream(new ByteArrayInputStream(bytes), byteOrder);
int[] samples = new int[bitsPerSampleLength];
resetPredictor();
for (int i = 0; i < pixelsPerStrip; i++) {
getSamplesAsBytes(bis, samples);
if (x < width) {
samples = applyPredictor(samples);
photometricInterpreter.interpretPixel(
imageBuilder, samples, x, y);
}
x++;
if (x >= width) {
x = 0;
resetPredictor();
y++;
bis.flushCache();
if (y >= yLimit) {
break;
}
}
}
}
#location 117
#vulnerability type RESOURCE_LEAK | #fixed code
private void interpretStrip(
final ImageBuilder imageBuilder,
final byte[] bytes,
final int pixelsPerStrip,
final int yLimit) throws ImageReadException, IOException {
if (y >= yLimit) {
return;
}
// changes added May 2012
// In the original implementation, a general-case bit reader called
// getSamplesAsBytes is used to retrieve the samples (raw data values)
// for each pixel in the strip. These samples are then passed into a
// photogrammetric interpreter that converts them to ARGB pixel values
// and stores them in the image. Because the bit-reader must handle
// a large number of formats, it involves several conditional
// branches that must be executed each time a pixel is read.
// Depending on the size of an image, the same evaluations must be
// executed redundantly thousands and perhaps millions of times
// in order to process the complete collection of pixels.
// This code attempts to remove that redundancy by
// evaluating the format up-front and bypassing the general-format
// code for two commonly used data formats: the 8 bits-per-pixel
// and 24 bits-per-pixel cases. For these formats, the
// special case code achieves substantial reductions in image-loading
// time. In other cases, it simply falls through to the original code
// and continues to read the data correctly as it did in previous
// versions of this class.
// In addition to bypassing the getBytesForSample() method,
// the 24-bit case also implements a special block for RGB
// formatted images. To get a sense of the contributions of each
// optimization (removing getSamplesAsBytes and removing the
// photometric interpreter), consider the following results from tests
// conducted with large TIFF images using the 24-bit RGB format
// bypass getSamplesAsBytes: 67.5 % reduction
// bypass both optimizations: 77.2 % reduction
//
//
// Future Changes
// Both of the 8-bit and 24-bit blocks make the assumption that a strip
// always begins on x = 0 and that each strip exactly fills out the rows
// it contains (no half rows). The original code did not make this
// assumption, but the approach is consistent with the TIFF 6.0 spec
// (1992),
// and should probably be considered as an enhancement to the
// original general-case code block that remains from the original
// implementation. Taking this approach saves one conditional
// operation per pixel or about 5 percent of the total run time
// in the 8 bits/pixel case.
// verify that all samples are one byte in size
final boolean allSamplesAreOneByte = isHomogenous(8);
if (predictor != 2 && bitsPerPixel == 8 && allSamplesAreOneByte) {
int k = 0;
int nRows = pixelsPerStrip / width;
if (y + nRows > yLimit) {
nRows = yLimit - y;
}
final int i0 = y;
final int i1 = y + nRows;
x = 0;
y += nRows;
final int[] samples = new int[1];
for (int i = i0; i < i1; i++) {
for (int j = 0; j < width; j++) {
samples[0] = bytes[k++] & 0xff;
photometricInterpreter.interpretPixel(imageBuilder,
samples, j, i);
}
}
return;
} else if (predictor != 2 && bitsPerPixel == 24 && allSamplesAreOneByte) {
int k = 0;
int nRows = pixelsPerStrip / width;
if (y + nRows > yLimit) {
nRows = yLimit - y;
}
final int i0 = y;
final int i1 = y + nRows;
x = 0;
y += nRows;
if (photometricInterpreter instanceof PhotometricInterpreterRgb) {
for (int i = i0; i < i1; i++) {
for (int j = 0; j < width; j++, k += 3) {
final int rgb = 0xff000000
| (((bytes[k] << 8) | (bytes[k + 1] & 0xff)) << 8)
| (bytes[k + 2] & 0xff);
imageBuilder.setRGB(j, i, rgb);
}
}
} else {
final int[] samples = new int[3];
for (int i = i0; i < i1; i++) {
for (int j = 0; j < width; j++) {
samples[0] = bytes[k++] & 0xff;
samples[1] = bytes[k++] & 0xff;
samples[2] = bytes[k++] & 0xff;
photometricInterpreter.interpretPixel(imageBuilder,
samples, j, i);
}
}
}
return;
}
// ------------------------------------------------------------
// original code before May 2012 modification
// this logic will handle all cases not conforming to the
// special case handled above
try (final BitInputStream bis = new BitInputStream(new ByteArrayInputStream(bytes), byteOrder)) {
int[] samples = new int[bitsPerSampleLength];
resetPredictor();
for (int i = 0; i < pixelsPerStrip; i++) {
getSamplesAsBytes(bis, samples);
if (x < width) {
samples = applyPredictor(samples);
photometricInterpreter.interpretPixel(imageBuilder, samples, x, y);
}
x++;
if (x >= width) {
x = 0;
resetPredictor();
y++;
bis.flushCache();
if (y >= yLimit) {
break;
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void checkGetICCProfileBytes(final File imageFile, final byte[] imageFileBytes)
throws Exception {
// check guessFormat()
final byte iccBytesFile[] = Imaging.getICCProfileBytes(imageFile);
final byte iccBytesBytes[] = Imaging.getICCProfileBytes(imageFileBytes);
assertTrue((iccBytesFile != null) == (iccBytesBytes != null));
if (iccBytesFile == null) {
return;
}
compareByteArrays(iccBytesFile, iccBytesBytes);
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
public void checkGetICCProfileBytes(final File imageFile, final byte[] imageFileBytes)
throws Exception {
// check guessFormat()
final byte iccBytesFile[] = Imaging.getICCProfileBytes(imageFile);
final byte iccBytesBytes[] = Imaging.getICCProfileBytes(imageFileBytes);
assertTrue((iccBytesFile != null) == (iccBytesBytes != null));
if (iccBytesFile == null) {
return;
}
assertArrayEquals(iccBytesFile, iccBytesBytes);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected List<IptcBlock> parseAllBlocks(byte bytes[], boolean verbose,
boolean strict) throws ImageReadException, IOException {
List<IptcBlock> blocks = new ArrayList<IptcBlock>();
BinaryInputStream bis = new BinaryInputStream(bytes, APP13_BYTE_ORDER);
// Note that these are unsigned quantities. Name is always an even
// number of bytes (including the 1st byte, which is the size.)
byte[] idString = bis.readByteArray(
PHOTOSHOP_IDENTIFICATION_STRING.size(),
"App13 Segment missing identification string");
if (!PHOTOSHOP_IDENTIFICATION_STRING.equals(idString))
throw new ImageReadException("Not a Photoshop App13 Segment");
// int index = PHOTOSHOP_IDENTIFICATION_STRING.length;
while (true) {
byte[] imageResourceBlockSignature = bis
.readByteArray(CONST_8BIM.size(),
"App13 Segment missing identification string",
false, false);
if (null == imageResourceBlockSignature)
break;
if (!CONST_8BIM.equals(imageResourceBlockSignature))
throw new ImageReadException(
"Invalid Image Resource Block Signature");
int blockType = bis
.read2ByteInteger("Image Resource Block missing type");
if (verbose)
Debug.debug("blockType",
blockType + " (0x" + Integer.toHexString(blockType)
+ ")");
int blockNameLength = bis
.read1ByteInteger("Image Resource Block missing name length");
if (verbose && blockNameLength > 0)
Debug.debug("blockNameLength", blockNameLength + " (0x"
+ Integer.toHexString(blockNameLength) + ")");
byte[] blockNameBytes;
if (blockNameLength == 0) {
bis.read1ByteInteger("Image Resource Block has invalid name");
blockNameBytes = new byte[0];
} else {
blockNameBytes = bis.readByteArray(blockNameLength,
"Invalid Image Resource Block name", verbose, strict);
if (null == blockNameBytes)
break;
if (blockNameLength % 2 == 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
int blockSize = bis
.read4ByteInteger("Image Resource Block missing size");
if (verbose)
Debug.debug("blockSize",
blockSize + " (0x" + Integer.toHexString(blockSize)
+ ")");
/*
* doesn't catch cases where blocksize is invalid but is still less
* than bytes.length but will at least prevent OutOfMemory errors
*/
if (blockSize > bytes.length) {
throw new ImageReadException("Invalid Block Size : "
+ blockSize + " > " + bytes.length);
}
byte[] blockData = bis.readByteArray(blockSize,
"Invalid Image Resource Block data", verbose, strict);
if (null == blockData)
break;
blocks.add(new IptcBlock(blockType, blockNameBytes, blockData));
if ((blockSize % 2) != 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
return blocks;
}
#location 82
#vulnerability type RESOURCE_LEAK | #fixed code
protected List<IptcBlock> parseAllBlocks(byte bytes[], boolean verbose,
boolean strict) throws ImageReadException, IOException {
List<IptcBlock> blocks = new ArrayList<IptcBlock>();
BinaryInputStream bis = null;
try {
bis = new BinaryInputStream(bytes, APP13_BYTE_ORDER);
// Note that these are unsigned quantities. Name is always an even
// number of bytes (including the 1st byte, which is the size.)
byte[] idString = bis.readByteArray(
PHOTOSHOP_IDENTIFICATION_STRING.size(),
"App13 Segment missing identification string");
if (!PHOTOSHOP_IDENTIFICATION_STRING.equals(idString))
throw new ImageReadException("Not a Photoshop App13 Segment");
// int index = PHOTOSHOP_IDENTIFICATION_STRING.length;
while (true) {
byte[] imageResourceBlockSignature = bis
.readByteArray(CONST_8BIM.size(),
"App13 Segment missing identification string",
false, false);
if (null == imageResourceBlockSignature)
break;
if (!CONST_8BIM.equals(imageResourceBlockSignature))
throw new ImageReadException(
"Invalid Image Resource Block Signature");
int blockType = bis
.read2ByteInteger("Image Resource Block missing type");
if (verbose)
Debug.debug("blockType",
blockType + " (0x" + Integer.toHexString(blockType)
+ ")");
int blockNameLength = bis
.read1ByteInteger("Image Resource Block missing name length");
if (verbose && blockNameLength > 0)
Debug.debug("blockNameLength", blockNameLength + " (0x"
+ Integer.toHexString(blockNameLength) + ")");
byte[] blockNameBytes;
if (blockNameLength == 0) {
bis.read1ByteInteger("Image Resource Block has invalid name");
blockNameBytes = new byte[0];
} else {
blockNameBytes = bis.readByteArray(blockNameLength,
"Invalid Image Resource Block name", verbose, strict);
if (null == blockNameBytes)
break;
if (blockNameLength % 2 == 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
int blockSize = bis
.read4ByteInteger("Image Resource Block missing size");
if (verbose)
Debug.debug("blockSize",
blockSize + " (0x" + Integer.toHexString(blockSize)
+ ")");
/*
* doesn't catch cases where blocksize is invalid but is still less
* than bytes.length but will at least prevent OutOfMemory errors
*/
if (blockSize > bytes.length) {
throw new ImageReadException("Invalid Block Size : "
+ blockSize + " > " + bytes.length);
}
byte[] blockData = bis.readByteArray(blockSize,
"Invalid Image Resource Block data", verbose, strict);
if (null == blockData)
break;
blocks.add(new IptcBlock(blockType, blockNameBytes, blockData));
if ((blockSize % 2) != 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
return blocks;
} finally {
if (bis != null) {
bis.close();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public byte[] compress(final byte[] bytes) throws IOException {
FastByteArrayOutputStream baos = null;
boolean canThrow = false;
try {
baos = new FastByteArrayOutputStream(
bytes.length * 2); // max length 1 extra byte for every 128
int ptr = 0;
while (ptr < bytes.length) {
int dup = findNextDuplicate(bytes, ptr);
if (dup == ptr) {
// write run length
final int len = findRunLength(bytes, dup);
final int actualLen = Math.min(len, 128);
baos.write(-(actualLen - 1));
baos.write(bytes[ptr]);
ptr += actualLen;
} else {
// write literals
int len = dup - ptr;
if (dup > 0) {
final int runlen = findRunLength(bytes, dup);
if (runlen < 3) {
// may want to discard next run.
final int nextptr = ptr + len + runlen;
final int nextdup = findNextDuplicate(bytes, nextptr);
if (nextdup != nextptr) {
// discard 2-byte run
dup = nextdup;
len = dup - ptr;
}
}
}
if (dup < 0) {
len = bytes.length - ptr;
}
final int actualLen = Math.min(len, 128);
baos.write(actualLen - 1);
for (int i = 0; i < actualLen; i++) {
baos.write(bytes[ptr]);
ptr++;
}
}
}
final byte[] result = baos.toByteArray();
canThrow = true;
return result;
} finally {
IoUtils.closeQuietly(canThrow, baos);
}
}
#location 53
#vulnerability type RESOURCE_LEAK | #fixed code
public byte[] compress(final byte[] bytes) throws IOException {
// max length 1 extra byte for every 128
try (FastByteArrayOutputStream baos = new FastByteArrayOutputStream(bytes.length * 2)) {
int ptr = 0;
while (ptr < bytes.length) {
int dup = findNextDuplicate(bytes, ptr);
if (dup == ptr) {
// write run length
final int len = findRunLength(bytes, dup);
final int actualLen = Math.min(len, 128);
baos.write(-(actualLen - 1));
baos.write(bytes[ptr]);
ptr += actualLen;
} else {
// write literals
int len = dup - ptr;
if (dup > 0) {
final int runlen = findRunLength(bytes, dup);
if (runlen < 3) {
// may want to discard next run.
final int nextptr = ptr + len + runlen;
final int nextdup = findNextDuplicate(bytes, nextptr);
if (nextdup != nextptr) {
// discard 2-byte run
dup = nextdup;
len = dup - ptr;
}
}
}
if (dup < 0) {
len = bytes.length - ptr;
}
final int actualLen = Math.min(len, 128);
baos.write(actualLen - 1);
for (int i = 0; i < actualLen; i++) {
baos.write(bytes[ptr]);
ptr++;
}
}
}
final byte[] result = baos.toByteArray();
return result;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void removeExifTag(final File jpegImageFile, final File dst) throws IOException,
ImageReadException, ImageWriteException {
OutputStream os = null;
boolean canThrow = false;
try {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
if (null == outputSet) {
// file does not contain any exif metadata. We don't need to
// update the file; just copy it.
FileUtils.copyFile(jpegImageFile, dst);
return;
}
{
// Example of how to remove a single tag/field.
// There are two ways to do this.
// Option 1: brute force
// Note that this approach is crude: Exif data is organized in
// directories. The same tag/field may appear in more than one
// directory, and have different meanings in each.
outputSet.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
// Option 2: precision
// We know the exact directory the tag should appear in, in this
// case the "exif" directory.
// One complicating factor is that in some cases, manufacturers
// will place the same tag in different directories.
// To learn which directory a tag appears in, either refer to
// the constants in ExifTagConstants.java or go to Phil Harvey's
// EXIF website.
final TiffOutputDirectory exifDirectory = outputSet
.getExifDirectory();
if (null != exifDirectory) {
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
}
}
os = new FileOutputStream(dst);
os = new BufferedOutputStream(os);
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
}
#location 68
#vulnerability type RESOURCE_LEAK | #fixed code
public void removeExifTag(final File jpegImageFile, final File dst) throws IOException,
ImageReadException, ImageWriteException {
try (FileOutputStream fos = new FileOutputStream(dst);
OutputStream os = new BufferedOutputStream(fos)) {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
if (null == outputSet) {
// file does not contain any exif metadata. We don't need to
// update the file; just copy it.
FileUtils.copyFile(jpegImageFile, dst);
return;
}
{
// Example of how to remove a single tag/field.
// There are two ways to do this.
// Option 1: brute force
// Note that this approach is crude: Exif data is organized in
// directories. The same tag/field may appear in more than one
// directory, and have different meanings in each.
outputSet.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
// Option 2: precision
// We know the exact directory the tag should appear in, in this
// case the "exif" directory.
// One complicating factor is that in some cases, manufacturers
// will place the same tag in different directories.
// To learn which directory a tag appears in, either refer to
// the constants in ExifTagConstants.java or go to Phil Harvey's
// EXIF website.
final TiffOutputDirectory exifDirectory = outputSet
.getExifDirectory();
if (null != exifDirectory) {
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
}
}
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void performTest(final String name) {
final File target = new File(name);
final Formatter fmt = new Formatter(System.out);
double sumTime = 0;
int n = 1;
for (int i = 0; i < 10; i++) {
try {
ByteSourceFile byteSource = new ByteSourceFile(target);
// This test code allows you to test cases where the
// input is processed using Apache Imaging's
// ByteSourceInputStream rather than the ByteSourceFile.
// You might also want to experiment with ByteSourceArray.
// FileInputStream fins = new FileInputStream(target);
// BufferedInputStream bins = new BufferedInputStream(fins);
// ByteSourceInputStream byteSource =
// new ByteSourceInputStream(bins, target.getName());
// ready the parser (you may modify this code block
// to use your parser of choice)
HashMap<String,Object> params = new HashMap<String,Object>();
TiffImageParser tiffImageParser = new TiffImageParser();
// load the file and record time needed to do so
final long time0 = System.nanoTime();
BufferedImage bImage = tiffImageParser.getBufferedImage(
byteSource, params);
final long time1 = System.nanoTime();
// tabulate results
final double testTime = (time1 - time0) / 1000000.0;
if (i > 1) {
n = i - 1;
sumTime += testTime;
}
final double avgTime = sumTime / n;
// tabulate the memory results. Note that the
// buffered image, the byte source, and the parser
// are all still in scope. This approach is taken
// to get some sense of peak memory use, but Java
// may have already started collecting garbage,
// so there are limits to the reliability of these
// statistics
final Runtime r = Runtime.getRuntime();
final long freeMemory = r.freeMemory();
final long totalMemory = r.totalMemory();
final long usedMemory = totalMemory - freeMemory;
if (i == 0) {
// print header info
fmt.format("\n");
fmt.format("Processing file: %s\n", target.getName());
fmt.format(" image size: %d by %d\n\n", bImage.getWidth(),
bImage.getHeight());
fmt.format(" time to load image -- memory\n");
fmt.format(" time ms avg ms -- used mb total mb\n");
}
fmt.format("%9.3f %9.3f -- %9.3f %9.3f \n", testTime,
avgTime, usedMemory / (1024.0 * 1024.0), totalMemory
/ (1024.0 * 1024.0));
bImage = null;
byteSource = null;
params = null;
tiffImageParser = null;
} catch (final ImageReadException ire) {
ire.printStackTrace();
System.exit(-1);
} catch (final IOException ioex) {
ioex.printStackTrace();
System.exit(-1);
}
try {
// sleep between loop iterations allows time
// for the JVM to clean up memory. The Netbeans IDE
// doesn't "get" the fact that we're doing this operation
// deliberately and is apt offer hints
// suggesting that the code should be modified
Runtime.getRuntime().gc();
Thread.sleep(1000);
} catch (final InterruptedException iex) {
// this isn't fatal, but shouldn't happen
iex.printStackTrace();
}
}
}
#location 35
#vulnerability type RESOURCE_LEAK | #fixed code
private void performTest(final String name) {
final File target = new File(name);
final Formatter fmt = new Formatter(System.out);
double sumTime = 0;
int n = 1;
for (int i = 0; i < 10; i++) {
try {
ByteSourceFile byteSource = new ByteSourceFile(target);
// This test code allows you to test cases where the
// input is processed using Apache Imaging's
// ByteSourceInputStream rather than the ByteSourceFile.
// You might also want to experiment with ByteSourceArray.
// FileInputStream fins = new FileInputStream(target);
// BufferedInputStream bins = new BufferedInputStream(fins);
// ByteSourceInputStream byteSource =
// new ByteSourceInputStream(bins, target.getName());
// ready the parser (you may modify this code block
// to use your parser of choice)
HashMap<String,Object> params = new HashMap<String,Object>();
TiffImageParser tiffImageParser = new TiffImageParser();
// load the file and record time needed to do so
final long time0 = System.nanoTime();
BufferedImage bImage = tiffImageParser.getBufferedImage(
byteSource, params);
final long time1 = System.nanoTime();
// tabulate results
final double testTime = (time1 - time0) / 1000000.0;
if (i > 1) {
n = i - 1;
sumTime += testTime;
}
final double avgTime = sumTime / n;
// tabulate the memory results. Note that the
// buffered image, the byte source, and the parser
// are all still in scope. This approach is taken
// to get some sense of peak memory use, but Java
// may have already started collecting garbage,
// so there are limits to the reliability of these
// statistics
final Runtime r = Runtime.getRuntime();
final long freeMemory = r.freeMemory();
final long totalMemory = r.totalMemory();
final long usedMemory = totalMemory - freeMemory;
if (i == 0) {
// print header info
fmt.format("\n");
fmt.format("Processing file: %s\n", target.getName());
fmt.format(" image size: %d by %d\n\n", bImage.getWidth(),
bImage.getHeight());
fmt.format(" time to load image -- memory\n");
fmt.format(" time ms avg ms -- used mb total mb\n");
}
fmt.format("%9.3f %9.3f -- %9.3f %9.3f \n", testTime,
avgTime, usedMemory / (1024.0 * 1024.0), totalMemory
/ (1024.0 * 1024.0));
bImage = null;
byteSource = null;
params = null;
tiffImageParser = null;
} catch (final ImageReadException ire) {
ire.printStackTrace();
System.exit(-1);
} catch (final IOException ioex) {
ioex.printStackTrace();
System.exit(-1);
} finally {
fmt.close();
}
try {
// sleep between loop iterations allows time
// for the JVM to clean up memory. The Netbeans IDE
// doesn't "get" the fact that we're doing this operation
// deliberately and is apt offer hints
// suggesting that the code should be modified
Runtime.getRuntime().gc();
Thread.sleep(1000);
} catch (final InterruptedException iex) {
// this isn't fatal, but shouldn't happen
iex.printStackTrace();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public byte[] getBlock(int blockStart, int blockLength) throws IOException
{
// We include a separate check for int overflow.
if ((blockStart < 0)
|| (blockLength < 0)
|| (blockStart + blockLength < 0)
|| (blockStart + blockLength > streamLength.longValue())) {
throw new IOException("Could not read block (block start: " + blockStart
+ ", block length: " + blockLength + ", data length: "
+ streamLength + ").");
}
InputStream is = getInputStream();
for (long skipped = 0; skipped < blockStart; ) {
long ret = is.skip(blockStart - skipped);
if (ret >= 0) {
skipped += ret;
}
}
byte bytes[] = new byte[blockLength];
int total = 0;
while (true)
{
int read = is.read(bytes, total, bytes.length - total);
if (read < 1)
throw new IOException("Could not read block.");
total += read;
if (total >= blockLength)
return bytes;
}
}
#location 30
#vulnerability type RESOURCE_LEAK | #fixed code
public byte[] getBlock(int blockStart, int blockLength) throws IOException
{
// We include a separate check for int overflow.
if ((blockStart < 0)
|| (blockLength < 0)
|| (blockStart + blockLength < 0)
|| (blockStart + blockLength > streamLength.longValue())) {
throw new IOException("Could not read block (block start: " + blockStart
+ ", block length: " + blockLength + ", data length: "
+ streamLength + ").");
}
InputStream is = getInputStream();
skipBytes(is, blockStart);
byte bytes[] = new byte[blockLength];
int total = 0;
while (true)
{
int read = is.read(bytes, total, bytes.length - total);
if (read < 1)
throw new IOException("Could not read block.");
total += read;
if (total >= blockLength)
return bytes;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public byte[] getBlock(final long start, final int length) throws IOException {
RandomAccessFile raf = null;
boolean canThrow = false;
try {
raf = new RandomAccessFile(file, "r");
// We include a separate check for int overflow.
if ((start < 0) || (length < 0) || (start + length < 0)
|| (start + length > raf.length())) {
throw new IOException("Could not read block (block start: "
+ start + ", block length: " + length
+ ", data length: " + raf.length() + ").");
}
final byte[] ret = BinaryFunctions.getRAFBytes(raf, start, length,
"Could not read value from file");
canThrow = true;
return ret;
} finally {
IoUtils.closeQuietly(canThrow, raf);
}
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public byte[] getBlock(final long start, final int length) throws IOException {
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
// We include a separate check for int overflow.
if ((start < 0) || (length < 0) || (start + length < 0)
|| (start + length > raf.length())) {
throw new IOException("Could not read block (block start: "
+ start + ", block length: " + length
+ ", data length: " + raf.length() + ").");
}
final byte[] ret = BinaryFunctions.getRAFBytes(raf, start, length,
"Could not read value from file");
return ret;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAddIptcData() throws Exception {
final ByteSource byteSource = new ByteSourceFile(imageFile);
final Map<String, Object> params = new HashMap<String, Object>();
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
params.put(PARAM_KEY_READ_THUMBNAILS, Boolean.valueOf(!ignoreImageData));
final JpegPhotoshopMetadata metadata = new JpegImageParser().getPhotoshopMetadata(byteSource, params);
{
final List<IptcBlock> newBlocks = new ArrayList<IptcBlock>();
List<IptcRecord> newRecords = new ArrayList<IptcRecord>();
if (null != metadata) {
final boolean keepOldIptcNonTextValues = true;
if (keepOldIptcNonTextValues) {
newBlocks.addAll(metadata.photoshopApp13Data
.getNonIptcBlocks());
}
final boolean keepOldIptcTextValues = true;
if (keepOldIptcTextValues) {
final List<IptcRecord> oldRecords = metadata.photoshopApp13Data
.getRecords();
newRecords = new ArrayList<IptcRecord>();
for (int j = 0; j < oldRecords.size(); j++) {
final IptcRecord record = oldRecords.get(j);
if (record.iptcType != IptcTypes.CITY
&& record.iptcType != IptcTypes.CREDIT) {
newRecords.add(record);
}
}
}
}
newRecords.add(new IptcRecord(IptcTypes.CITY, "Albany, NY"));
newRecords.add(new IptcRecord(IptcTypes.CREDIT,
"William Sorensen"));
final PhotoshopApp13Data newData = new PhotoshopApp13Data(newRecords,
newBlocks);
final File updated = createTempFile(imageFile.getName()
+ ".iptc.add.", ".jpg");
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(updated);
os = new BufferedOutputStream(os);
new JpegIptcRewriter().writeIPTC(byteSource, os, newData);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
// Debug.debug("Destination Segments:");
// new JpegUtils().dumpJFIF(new ByteSourceFile(updated));
final ByteSource updateByteSource = new ByteSourceFile(updated);
final JpegPhotoshopMetadata outMetadata = new JpegImageParser()
.getPhotoshopMetadata(updateByteSource, params);
// Debug.debug("outMetadata", outMetadata.toString());
// Debug.debug("hasIptcSegment", new JpegImageParser()
// .hasIptcSegment(updateByteSource));
assertNotNull(outMetadata);
assertTrue(outMetadata.getItems().size() == newRecords.size());
// assertEquals(metadata.toString(), outMetadata.toString());
}
}
#location 51
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAddIptcData() throws Exception {
final ByteSource byteSource = new ByteSourceFile(imageFile);
final Map<String, Object> params = new HashMap<String, Object>();
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
params.put(PARAM_KEY_READ_THUMBNAILS, Boolean.valueOf(!ignoreImageData));
final JpegPhotoshopMetadata metadata = new JpegImageParser().getPhotoshopMetadata(byteSource, params);
if (metadata == null) {
// FIXME select only files with meta for this test
return;
}
final List<IptcBlock> newBlocks = new ArrayList<IptcBlock>();
newBlocks.addAll(metadata.photoshopApp13Data.getNonIptcBlocks());
final List<IptcRecord> oldRecords = metadata.photoshopApp13Data.getRecords();
List<IptcRecord> newRecords = new ArrayList<IptcRecord>();
for (final IptcRecord record : oldRecords) {
if (record.iptcType != IptcTypes.CITY
&& record.iptcType != IptcTypes.CREDIT) {
newRecords.add(record);
}
}
newRecords.add(new IptcRecord(IptcTypes.CITY, "Albany, NY"));
newRecords.add(new IptcRecord(IptcTypes.CREDIT, "William Sorensen"));
final PhotoshopApp13Data newData = new PhotoshopApp13Data(newRecords, newBlocks);
final File updated = createTempFile(imageFile.getName() + ".iptc.add.", ".jpg");
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(updated);
os = new BufferedOutputStream(os);
new JpegIptcRewriter().writeIPTC(byteSource, os, newData);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
final ByteSource updateByteSource = new ByteSourceFile(updated);
final JpegPhotoshopMetadata outMetadata = new JpegImageParser()
.getPhotoshopMetadata(updateByteSource, params);
assertNotNull(outMetadata);
assertTrue(outMetadata.getItems().size() == newRecords.size());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected File createTempFile(final byte src[]) throws IOException {
final File file = createTempFile("raw_", ".bin");
// write test bytes to file.
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(file);
os = new BufferedOutputStream(os);
os.write(src);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
// test that all bytes written to file.
assertTrue(src.length == file.length());
return file;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
protected File createTempFile(final byte src[]) throws IOException {
final File file = createTempFile("raw_", ".bin");
// write test bytes to file.
try (FileOutputStream fos = new FileOutputStream(file);
OutputStream os = new BufferedOutputStream(fos)) {
os.write(src);
}
// test that all bytes written to file.
assertTrue(src.length == file.length());
return file;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected static ICC_Profile getICCProfile(ByteSource byteSource, Map params)
throws ImageReadException, IOException {
byte bytes[] = getICCProfileBytes(byteSource, params);
if (bytes == null)
return null;
IccProfileParser parser = new IccProfileParser();
IccProfileInfo info = parser.getICCProfileInfo(bytes);
if (info.issRGB())
return null;
ICC_Profile icc = ICC_Profile.getInstance(bytes);
return icc;
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
protected static ICC_Profile getICCProfile(ByteSource byteSource, Map params)
throws ImageReadException, IOException {
byte bytes[] = getICCProfileBytes(byteSource, params);
if (bytes == null)
return null;
IccProfileParser parser = new IccProfileParser();
IccProfileInfo info = parser.getICCProfileInfo(bytes);
if (info == null)
return null;
if (info.issRGB())
return null;
ICC_Profile icc = ICC_Profile.getInstance(bytes);
return icc;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void setData(final byte[] bytes) throws IOException {
data = bytes;
BinaryInputStream bis = null;
boolean canThrow = false;
try {
bis = new BinaryInputStream(new ByteArrayInputStream(
bytes), ByteOrder.BIG_ENDIAN);
dataTypeSignature = bis.read4Bytes("data type signature",
"ICC: corrupt tag data");
itdt = getIccTagDataType(dataTypeSignature);
// if (itdt != null)
// {
// System.out.println("\t\t\t" + "itdt: " + itdt.name);
// }
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, bis);
}
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
public void setData(final byte[] bytes) throws IOException {
data = bytes;
InputStream bis = null;
boolean canThrow = false;
try {
bis = new ByteArrayInputStream(bytes);
dataTypeSignature = BinaryFunctions.read4Bytes("data type signature", bis,
"ICC: corrupt tag data", ByteOrder.BIG_ENDIAN);
itdt = getIccTagDataType(dataTypeSignature);
// if (itdt != null)
// {
// System.out.println("\t\t\t" + "itdt: " + itdt.name);
// }
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, bis);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void writeImage(BufferedImage src, OutputStream os, Map params)
throws ImageWriteException, IOException {
// make copy of params; we'll clear keys as we consume them.
params = (params == null) ? new HashMap() : new HashMap(params);
// clear format key.
if (params.containsKey(PARAM_KEY_FORMAT))
params.remove(PARAM_KEY_FORMAT);
if (params.size() > 0) {
Object firstKey = params.keySet().iterator().next();
throw new ImageWriteException("Unknown parameter: " + firstKey);
}
final PaletteFactory paletteFactory = new PaletteFactory();
final SimplePalette palette = paletteFactory
.makePaletteSimple(src, 256);
final int bitCount;
final boolean hasTransparency = paletteFactory.hasTransparency(src);
if (palette == null) {
if (hasTransparency)
bitCount = 32;
else
bitCount = 24;
} else if (palette.length() <= 2)
bitCount = 1;
else if (palette.length() <= 16)
bitCount = 4;
else
bitCount = 8;
BinaryOutputStream bos = new BinaryOutputStream(os, BYTE_ORDER_INTEL);
int scanline_size = (bitCount * src.getWidth() + 7) / 8;
if ((scanline_size % 4) != 0)
scanline_size += 4 - (scanline_size % 4); // pad scanline to 4 byte
// size.
int t_scanline_size = (src.getWidth() + 7) / 8;
if ((t_scanline_size % 4) != 0)
t_scanline_size += 4 - (t_scanline_size % 4); // pad scanline to 4
// byte size.
int imageSize = 40 + 4 * (bitCount <= 8 ? (1 << bitCount) : 0)
+ src.getHeight() * scanline_size + src.getHeight()
* t_scanline_size;
// ICONDIR
bos.write2Bytes(0); // reserved
bos.write2Bytes(1); // 1=ICO, 2=CUR
bos.write2Bytes(1); // count
// ICONDIRENTRY
int iconDirEntryWidth = src.getWidth();
int iconDirEntryHeight = src.getHeight();
if (iconDirEntryWidth > 255 || iconDirEntryHeight > 255) {
iconDirEntryWidth = 0;
iconDirEntryHeight = 0;
}
bos.write(iconDirEntryWidth);
bos.write(iconDirEntryHeight);
bos.write((bitCount >= 8) ? 0 : (1 << bitCount));
bos.write(0); // reserved
bos.write2Bytes(1); // color planes
bos.write2Bytes(bitCount);
bos.write4Bytes(imageSize);
bos.write4Bytes(22); // image offset
// BITMAPINFOHEADER
bos.write4Bytes(40); // size
bos.write4Bytes(src.getWidth());
bos.write4Bytes(2 * src.getHeight());
bos.write2Bytes(1); // planes
bos.write2Bytes(bitCount);
bos.write4Bytes(0); // compression
bos.write4Bytes(0); // image size
bos.write4Bytes(0); // x pixels per meter
bos.write4Bytes(0); // y pixels per meter
bos.write4Bytes(0); // colors used, 0 = (1 << bitCount) (ignored)
bos.write4Bytes(0); // colors important
if (palette != null) {
for (int i = 0; i < (1 << bitCount); i++) {
if (i < palette.length()) {
int argb = palette.getEntry(i);
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
bos.write(0);
} else {
bos.write(0);
bos.write(0);
bos.write(0);
bos.write(0);
}
}
}
int bit_cache = 0;
int bits_in_cache = 0;
int row_padding = scanline_size - (bitCount * src.getWidth() + 7) / 8;
for (int y = src.getHeight() - 1; y >= 0; y--) {
for (int x = 0; x < src.getWidth(); x++) {
int argb = src.getRGB(x, y);
if (bitCount < 8) {
int rgb = 0xffffff & argb;
int index = palette.getPaletteIndex(rgb);
bit_cache <<= bitCount;
bit_cache |= index;
bits_in_cache += bitCount;
if (bits_in_cache >= 8) {
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
} else if (bitCount == 8) {
int rgb = 0xffffff & argb;
int index = palette.getPaletteIndex(rgb);
bos.write(0xff & index);
} else if (bitCount == 24) {
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
} else if (bitCount == 32) {
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
bos.write(0xff & (argb >> 24));
}
}
if (bits_in_cache > 0) {
bit_cache <<= (8 - bits_in_cache);
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
for (int x = 0; x < row_padding; x++)
bos.write(0);
}
int t_row_padding = t_scanline_size - (src.getWidth() + 7) / 8;
for (int y = src.getHeight() - 1; y >= 0; y--) {
for (int x = 0; x < src.getWidth(); x++) {
int argb = src.getRGB(x, y);
int alpha = 0xff & (argb >> 24);
bit_cache <<= 1;
if (alpha == 0)
bit_cache |= 1;
bits_in_cache++;
if (bits_in_cache >= 8) {
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
}
if (bits_in_cache > 0) {
bit_cache <<= (8 - bits_in_cache);
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
for (int x = 0; x < t_row_padding; x++)
bos.write(0);
}
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public void writeImage(BufferedImage src, OutputStream os, Map params)
throws ImageWriteException, IOException {
// make copy of params; we'll clear keys as we consume them.
params = (params == null) ? new HashMap() : new HashMap(params);
// clear format key.
if (params.containsKey(PARAM_KEY_FORMAT))
params.remove(PARAM_KEY_FORMAT);
PixelDensity pixelDensity = (PixelDensity) params.remove(PARAM_KEY_PIXEL_DENSITY);
if (params.size() > 0) {
Object firstKey = params.keySet().iterator().next();
throw new ImageWriteException("Unknown parameter: " + firstKey);
}
final PaletteFactory paletteFactory = new PaletteFactory();
final SimplePalette palette = paletteFactory
.makePaletteSimple(src, 256);
final int bitCount;
final boolean hasTransparency = paletteFactory.hasTransparency(src);
if (palette == null) {
if (hasTransparency)
bitCount = 32;
else
bitCount = 24;
} else if (palette.length() <= 2)
bitCount = 1;
else if (palette.length() <= 16)
bitCount = 4;
else
bitCount = 8;
BinaryOutputStream bos = new BinaryOutputStream(os, BYTE_ORDER_INTEL);
int scanline_size = (bitCount * src.getWidth() + 7) / 8;
if ((scanline_size % 4) != 0)
scanline_size += 4 - (scanline_size % 4); // pad scanline to 4 byte
// size.
int t_scanline_size = (src.getWidth() + 7) / 8;
if ((t_scanline_size % 4) != 0)
t_scanline_size += 4 - (t_scanline_size % 4); // pad scanline to 4
// byte size.
int imageSize = 40 + 4 * (bitCount <= 8 ? (1 << bitCount) : 0)
+ src.getHeight() * scanline_size + src.getHeight()
* t_scanline_size;
// ICONDIR
bos.write2Bytes(0); // reserved
bos.write2Bytes(1); // 1=ICO, 2=CUR
bos.write2Bytes(1); // count
// ICONDIRENTRY
int iconDirEntryWidth = src.getWidth();
int iconDirEntryHeight = src.getHeight();
if (iconDirEntryWidth > 255 || iconDirEntryHeight > 255) {
iconDirEntryWidth = 0;
iconDirEntryHeight = 0;
}
bos.write(iconDirEntryWidth);
bos.write(iconDirEntryHeight);
bos.write((bitCount >= 8) ? 0 : (1 << bitCount));
bos.write(0); // reserved
bos.write2Bytes(1); // color planes
bos.write2Bytes(bitCount);
bos.write4Bytes(imageSize);
bos.write4Bytes(22); // image offset
// BITMAPINFOHEADER
bos.write4Bytes(40); // size
bos.write4Bytes(src.getWidth());
bos.write4Bytes(2 * src.getHeight());
bos.write2Bytes(1); // planes
bos.write2Bytes(bitCount);
bos.write4Bytes(0); // compression
bos.write4Bytes(0); // image size
bos.write4Bytes(pixelDensity == null ? 0 : (int)Math.round(pixelDensity.horizontalDensityMetres())); // x pixels per meter
bos.write4Bytes(pixelDensity == null ? 0 : (int)Math.round(pixelDensity.horizontalDensityMetres())); // y pixels per meter
bos.write4Bytes(0); // colors used, 0 = (1 << bitCount) (ignored)
bos.write4Bytes(0); // colors important
if (palette != null) {
for (int i = 0; i < (1 << bitCount); i++) {
if (i < palette.length()) {
int argb = palette.getEntry(i);
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
bos.write(0);
} else {
bos.write(0);
bos.write(0);
bos.write(0);
bos.write(0);
}
}
}
int bit_cache = 0;
int bits_in_cache = 0;
int row_padding = scanline_size - (bitCount * src.getWidth() + 7) / 8;
for (int y = src.getHeight() - 1; y >= 0; y--) {
for (int x = 0; x < src.getWidth(); x++) {
int argb = src.getRGB(x, y);
if (bitCount < 8) {
int rgb = 0xffffff & argb;
int index = palette.getPaletteIndex(rgb);
bit_cache <<= bitCount;
bit_cache |= index;
bits_in_cache += bitCount;
if (bits_in_cache >= 8) {
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
} else if (bitCount == 8) {
int rgb = 0xffffff & argb;
int index = palette.getPaletteIndex(rgb);
bos.write(0xff & index);
} else if (bitCount == 24) {
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
} else if (bitCount == 32) {
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
bos.write(0xff & (argb >> 24));
}
}
if (bits_in_cache > 0) {
bit_cache <<= (8 - bits_in_cache);
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
for (int x = 0; x < row_padding; x++)
bos.write(0);
}
int t_row_padding = t_scanline_size - (src.getWidth() + 7) / 8;
for (int y = src.getHeight() - 1; y >= 0; y--) {
for (int x = 0; x < src.getWidth(); x++) {
int argb = src.getRGB(x, y);
int alpha = 0xff & (argb >> 24);
bit_cache <<= 1;
if (alpha == 0)
bit_cache |= 1;
bits_in_cache++;
if (bits_in_cache >= 8) {
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
}
if (bits_in_cache > 0) {
bit_cache <<= (8 - bits_in_cache);
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
for (int x = 0; x < t_row_padding; x++)
bos.write(0);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public byte[] getBlock(int blockStart, int blockLength) throws IOException
{
// We include a separate check for int overflow.
if ((blockStart < 0)
|| (blockLength < 0)
|| (blockStart + blockLength < 0)
|| (blockStart + blockLength > streamLength.longValue())) {
throw new IOException("Could not read block (block start: " + blockStart
+ ", block length: " + blockLength + ", data length: "
+ streamLength + ").");
}
InputStream is = getInputStream();
for (long skipped = 0; skipped < blockStart; ) {
long ret = is.skip(blockStart - skipped);
if (ret >= 0) {
skipped += ret;
}
}
byte bytes[] = new byte[blockLength];
int total = 0;
while (true)
{
int read = is.read(bytes, total, bytes.length - total);
if (read < 1)
throw new IOException("Could not read block.");
total += read;
if (total >= blockLength)
return bytes;
}
}
#location 27
#vulnerability type RESOURCE_LEAK | #fixed code
public byte[] getBlock(int blockStart, int blockLength) throws IOException
{
// We include a separate check for int overflow.
if ((blockStart < 0)
|| (blockLength < 0)
|| (blockStart + blockLength < 0)
|| (blockStart + blockLength > streamLength.longValue())) {
throw new IOException("Could not read block (block start: " + blockStart
+ ", block length: " + blockLength + ", data length: "
+ streamLength + ").");
}
InputStream is = getInputStream();
skipBytes(is, blockStart);
byte bytes[] = new byte[blockLength];
int total = 0;
while (true)
{
int read = is.read(bytes, total, bytes.length - total);
if (read < 1)
throw new IOException("Could not read block.");
total += read;
if (total >= blockLength)
return bytes;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void interpretTile(final ImageBuilder imageBuilder, final byte[] bytes,
final int startX, final int startY, final int xLimit, final int yLimit) throws ImageReadException, IOException {
// changes introduced May 2012
// The following block of code implements changes that
// reduce image loading time by using special-case processing
// instead of the general-purpose logic from the original
// implementation. For a detailed discussion, see the comments for
// a similar treatment in the DataReaderStrip class
//
// verify that all samples are one byte in size
final boolean allSamplesAreOneByte = isHomogenous(8);
if (predictor != 2 && bitsPerPixel == 24 && allSamplesAreOneByte) {
int k = 0;
final int i0 = startY;
int i1 = startY + tileLength;
if (i1 > yLimit) {
// the tile is padded past bottom of image
i1 = yLimit;
}
final int j0 = startX;
int j1 = startX + tileWidth;
if (j1 > xLimit) {
// the tile is padded to beyond the tile width
j1 = xLimit;
}
if (photometricInterpreter instanceof PhotometricInterpreterRgb) {
for (int i = i0; i < i1; i++) {
k = (i - i0) * tileWidth * 3;
for (int j = j0; j < j1; j++, k += 3) {
final int rgb = 0xff000000
| (((bytes[k] << 8) | (bytes[k + 1] & 0xff)) << 8)
| (bytes[k + 2] & 0xff);
imageBuilder.setRGB(j, i, rgb);
}
}
} else {
final int[] samples = new int[3];
for (int i = i0; i < i1; i++) {
k = (i - i0) * tileWidth * 3;
for (int j = j0; j < j1; j++) {
samples[0] = bytes[k++] & 0xff;
samples[1] = bytes[k++] & 0xff;
samples[2] = bytes[k++] & 0xff;
photometricInterpreter.interpretPixel(imageBuilder,
samples, j, i);
}
}
}
return;
}
// End of May 2012 changes
final BitInputStream bis = new BitInputStream(new ByteArrayInputStream(bytes), byteOrder);
final int pixelsPerTile = tileWidth * tileLength;
int tileX = 0;
int tileY = 0;
int[] samples = new int[bitsPerSampleLength];
resetPredictor();
for (int i = 0; i < pixelsPerTile; i++) {
final int x = tileX + startX;
final int y = tileY + startY;
getSamplesAsBytes(bis, samples);
if ((x < xLimit) && (y < yLimit)) {
samples = applyPredictor(samples);
photometricInterpreter.interpretPixel(imageBuilder, samples, x,
y);
}
tileX++;
if (tileX >= tileWidth) {
tileX = 0;
resetPredictor();
tileY++;
bis.flushCache();
if (tileY >= tileLength) {
break;
}
}
}
}
#location 65
#vulnerability type RESOURCE_LEAK | #fixed code
private void interpretTile(final ImageBuilder imageBuilder, final byte[] bytes,
final int startX, final int startY, final int xLimit, final int yLimit) throws ImageReadException, IOException {
// changes introduced May 2012
// The following block of code implements changes that
// reduce image loading time by using special-case processing
// instead of the general-purpose logic from the original
// implementation. For a detailed discussion, see the comments for
// a similar treatment in the DataReaderStrip class
//
// verify that all samples are one byte in size
final boolean allSamplesAreOneByte = isHomogenous(8);
if (predictor != 2 && bitsPerPixel == 24 && allSamplesAreOneByte) {
int k = 0;
final int i0 = startY;
int i1 = startY + tileLength;
if (i1 > yLimit) {
// the tile is padded past bottom of image
i1 = yLimit;
}
final int j0 = startX;
int j1 = startX + tileWidth;
if (j1 > xLimit) {
// the tile is padded to beyond the tile width
j1 = xLimit;
}
if (photometricInterpreter instanceof PhotometricInterpreterRgb) {
for (int i = i0; i < i1; i++) {
k = (i - i0) * tileWidth * 3;
for (int j = j0; j < j1; j++, k += 3) {
final int rgb = 0xff000000
| (((bytes[k] << 8) | (bytes[k + 1] & 0xff)) << 8)
| (bytes[k + 2] & 0xff);
imageBuilder.setRGB(j, i, rgb);
}
}
} else {
final int[] samples = new int[3];
for (int i = i0; i < i1; i++) {
k = (i - i0) * tileWidth * 3;
for (int j = j0; j < j1; j++) {
samples[0] = bytes[k++] & 0xff;
samples[1] = bytes[k++] & 0xff;
samples[2] = bytes[k++] & 0xff;
photometricInterpreter.interpretPixel(imageBuilder,
samples, j, i);
}
}
}
return;
}
// End of May 2012 changes
try (final BitInputStream bis = new BitInputStream(new ByteArrayInputStream(bytes), byteOrder)) {
final int pixelsPerTile = tileWidth * tileLength;
int tileX = 0;
int tileY = 0;
int[] samples = new int[bitsPerSampleLength];
resetPredictor();
for (int i = 0; i < pixelsPerTile; i++) {
final int x = tileX + startX;
final int y = tileY + startY;
getSamplesAsBytes(bis, samples);
if ((x < xLimit) && (y < yLimit)) {
samples = applyPredictor(samples);
photometricInterpreter.interpretPixel(imageBuilder, samples, x, y);
}
tileX++;
if (tileX >= tileWidth) {
tileX = 0;
resetPredictor();
tileY++;
bis.flushCache();
if (tileY >= tileLength) {
break;
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static byte[] decompressModifiedHuffman(final byte[] compressed,
final int width, final int height) throws ImageReadException {
final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(
new ByteArrayInputStream(compressed));
BitArrayOutputStream outputStream = null;
boolean canThrow = false;
try {
outputStream = new BitArrayOutputStream();
for (int y = 0; y < height; y++) {
int color = WHITE;
int rowLength;
for (rowLength = 0; rowLength < width;) {
final int runLength = readTotalRunLength(inputStream, color);
for (int i = 0; i < runLength; i++) {
outputStream.writeBit(color);
}
color = 1 - color;
rowLength += runLength;
}
if (rowLength == width) {
inputStream.flushCache();
outputStream.flush();
} else if (rowLength > width) {
throw new ImageReadException("Unrecoverable row length error in image row " + y);
}
}
final byte[] ret = outputStream.toByteArray();
canThrow = true;
return ret;
} finally {
try {
IoUtils.closeQuietly(canThrow, outputStream);
} catch (final IOException ioException) {
throw new ImageReadException("I/O error", ioException);
}
}
}
#location 33
#vulnerability type RESOURCE_LEAK | #fixed code
public static byte[] decompressModifiedHuffman(final byte[] compressed,
final int width, final int height) throws ImageReadException {
try (ByteArrayInputStream baos = new ByteArrayInputStream(compressed);
BitInputStreamFlexible inputStream = new BitInputStreamFlexible(baos);
BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
for (int y = 0; y < height; y++) {
int color = WHITE;
int rowLength;
for (rowLength = 0; rowLength < width;) {
final int runLength = readTotalRunLength(inputStream, color);
for (int i = 0; i < runLength; i++) {
outputStream.writeBit(color);
}
color = 1 - color;
rowLength += runLength;
}
if (rowLength == width) {
inputStream.flushCache();
outputStream.flush();
} else if (rowLength > width) {
throw new ImageReadException("Unrecoverable row length error in image row " + y);
}
}
final byte[] ret = outputStream.toByteArray();
return ret;
} catch (final IOException ioException) {
throw new ImageReadException("Error reading image to decompress", ioException);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void setExifGPSTag(final File jpegImageFile, final File dst) throws IOException,
ImageReadException, ImageWriteException {
OutputStream os = null;
boolean canThrow = false;
try {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
// if file does not contain any exif metadata, we create an empty
// set of exif metadata. Otherwise, we keep all of the other
// existing tags.
if (null == outputSet) {
outputSet = new TiffOutputSet();
}
{
// Example of how to add/update GPS info to output set.
// New York City
final double longitude = -74.0; // 74 degrees W (in Degrees East)
final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
// North)
outputSet.setGPSInDegrees(longitude, latitude);
}
os = new FileOutputStream(dst);
os = new BufferedOutputStream(os);
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
}
#location 53
#vulnerability type RESOURCE_LEAK | #fixed code
public void setExifGPSTag(final File jpegImageFile, final File dst) throws IOException,
ImageReadException, ImageWriteException {
try (FileOutputStream fos = new FileOutputStream(dst);
OutputStream os = new BufferedOutputStream(fos)) {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
// if file does not contain any exif metadata, we create an empty
// set of exif metadata. Otherwise, we keep all of the other
// existing tags.
if (null == outputSet) {
outputSet = new TiffOutputSet();
}
{
// Example of how to add/update GPS info to output set.
// New York City
final double longitude = -74.0; // 74 degrees W (in Degrees East)
final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
// North)
outputSet.setGPSInDegrees(longitude, latitude);
}
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected List<IptcBlock> parseAllBlocks(final byte[] bytes, final boolean verbose,
final boolean strict) throws ImageReadException, IOException {
final List<IptcBlock> blocks = new ArrayList<IptcBlock>();
BinaryInputStream bis = null;
boolean canThrow = false;
try {
bis = new BinaryInputStream(new ByteArrayInputStream(bytes), APP13_BYTE_ORDER);
// Note that these are unsigned quantities. Name is always an even
// number of bytes (including the 1st byte, which is the size.)
final byte[] idString = bis.readBytes(
JpegConstants.PHOTOSHOP_IDENTIFICATION_STRING.size(),
"App13 Segment missing identification string");
if (!JpegConstants.PHOTOSHOP_IDENTIFICATION_STRING.equals(idString)) {
throw new ImageReadException("Not a Photoshop App13 Segment");
}
// int index = PHOTOSHOP_IDENTIFICATION_STRING.length;
while (true) {
final int imageResourceBlockSignature;
try {
imageResourceBlockSignature = bis.read4Bytes(
"Image Resource Block missing identification string");
} catch (final IOException ioEx) {
break;
}
if (imageResourceBlockSignature != JpegConstants.CONST_8BIM) {
throw new ImageReadException(
"Invalid Image Resource Block Signature");
}
final int blockType = bis.read2Bytes("Image Resource Block missing type");
if (verbose) {
Debug.debug("blockType: " + blockType + " (0x" + Integer.toHexString(blockType) + ")");
}
final int blockNameLength = bis.readByte("Name length", "Image Resource Block missing name length");
if (verbose && blockNameLength > 0) {
Debug.debug("blockNameLength: " + blockNameLength + " (0x"
+ Integer.toHexString(blockNameLength) + ")");
}
byte[] blockNameBytes;
if (blockNameLength == 0) {
bis.readByte("Block name bytes", "Image Resource Block has invalid name");
blockNameBytes = new byte[0];
} else {
try {
blockNameBytes = bis.readBytes(blockNameLength,
"Invalid Image Resource Block name");
} catch (final IOException ioEx) {
if (strict) {
throw ioEx;
}
break;
}
if (blockNameLength % 2 == 0) {
bis.readByte("Padding byte", "Image Resource Block missing padding byte");
}
}
final int blockSize = bis.read4Bytes("Image Resource Block missing size");
if (verbose) {
Debug.debug("blockSize: " + blockSize + " (0x" + Integer.toHexString(blockSize) + ")");
}
/*
* doesn't catch cases where blocksize is invalid but is still less
* than bytes.length but will at least prevent OutOfMemory errors
*/
if (blockSize > bytes.length) {
throw new ImageReadException("Invalid Block Size : " + blockSize + " > " + bytes.length);
}
final byte[] blockData;
try {
blockData = bis.readBytes(blockSize, "Invalid Image Resource Block data");
} catch (final IOException ioEx) {
if (strict) {
throw ioEx;
}
break;
}
blocks.add(new IptcBlock(blockType, blockNameBytes, blockData));
if ((blockSize % 2) != 0) {
bis.readByte("Padding byte", "Image Resource Block missing padding byte");
}
}
canThrow = true;
return blocks;
} finally {
IoUtils.closeQuietly(canThrow, bis);
}
}
#location 98
#vulnerability type RESOURCE_LEAK | #fixed code
protected List<IptcBlock> parseAllBlocks(final byte[] bytes, final boolean verbose,
final boolean strict) throws ImageReadException, IOException {
final List<IptcBlock> blocks = new ArrayList<IptcBlock>();
InputStream bis = null;
boolean canThrow = false;
try {
bis = new ByteArrayInputStream(bytes);
// Note that these are unsigned quantities. Name is always an even
// number of bytes (including the 1st byte, which is the size.)
final byte[] idString = readBytes("", bis,
JpegConstants.PHOTOSHOP_IDENTIFICATION_STRING.size(),
"App13 Segment missing identification string");
if (!JpegConstants.PHOTOSHOP_IDENTIFICATION_STRING.equals(idString)) {
throw new ImageReadException("Not a Photoshop App13 Segment");
}
// int index = PHOTOSHOP_IDENTIFICATION_STRING.length;
while (true) {
final int imageResourceBlockSignature;
try {
imageResourceBlockSignature = read4Bytes("", bis,
"Image Resource Block missing identification string", APP13_BYTE_ORDER);
} catch (final IOException ioEx) {
break;
}
if (imageResourceBlockSignature != JpegConstants.CONST_8BIM) {
throw new ImageReadException(
"Invalid Image Resource Block Signature");
}
final int blockType = read2Bytes("", bis, "Image Resource Block missing type", APP13_BYTE_ORDER);
if (verbose) {
Debug.debug("blockType: " + blockType + " (0x" + Integer.toHexString(blockType) + ")");
}
final int blockNameLength = readByte("Name length", bis, "Image Resource Block missing name length");
if (verbose && blockNameLength > 0) {
Debug.debug("blockNameLength: " + blockNameLength + " (0x"
+ Integer.toHexString(blockNameLength) + ")");
}
byte[] blockNameBytes;
if (blockNameLength == 0) {
readByte("Block name bytes", bis, "Image Resource Block has invalid name");
blockNameBytes = new byte[0];
} else {
try {
blockNameBytes = readBytes("", bis, blockNameLength,
"Invalid Image Resource Block name");
} catch (final IOException ioEx) {
if (strict) {
throw ioEx;
}
break;
}
if (blockNameLength % 2 == 0) {
readByte("Padding byte", bis, "Image Resource Block missing padding byte");
}
}
final int blockSize = read4Bytes("", bis, "Image Resource Block missing size", APP13_BYTE_ORDER);
if (verbose) {
Debug.debug("blockSize: " + blockSize + " (0x" + Integer.toHexString(blockSize) + ")");
}
/*
* doesn't catch cases where blocksize is invalid but is still less
* than bytes.length but will at least prevent OutOfMemory errors
*/
if (blockSize > bytes.length) {
throw new ImageReadException("Invalid Block Size : " + blockSize + " > " + bytes.length);
}
final byte[] blockData;
try {
blockData = readBytes("", bis, blockSize, "Invalid Image Resource Block data");
} catch (final IOException ioEx) {
if (strict) {
throw ioEx;
}
break;
}
blocks.add(new IptcBlock(blockType, blockNameBytes, blockData));
if ((blockSize % 2) != 0) {
readByte("Padding byte", bis, "Image Resource Block missing padding byte");
}
}
canThrow = true;
return blocks;
} finally {
IoUtils.closeQuietly(canThrow, bis);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testRemove() throws Exception {
final ByteSource byteSource = new ByteSourceFile(imageFile);
final Map<String, Object> params = new HashMap<String, Object>();
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
params.put(PARAM_KEY_READ_THUMBNAILS, new Boolean(!ignoreImageData));
final JpegPhotoshopMetadata metadata = new JpegImageParser()
.getPhotoshopMetadata(byteSource, params);
assertNotNull(metadata);
// metadata.dump();
final File noIptcFile = createTempFile(imageFile.getName()
+ ".iptc.remove.", ".jpg");
{
// test remove
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(noIptcFile);
os = new BufferedOutputStream(os);
new JpegIptcRewriter().removeIPTC(byteSource, os);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
final JpegPhotoshopMetadata outMetadata = new JpegImageParser()
.getPhotoshopMetadata(new ByteSourceFile(noIptcFile),
params);
assertTrue(outMetadata == null
|| outMetadata.getItems().size() == 0);
}
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testRemove() throws Exception {
final ByteSource byteSource = new ByteSourceFile(imageFile);
final Map<String, Object> params = new HashMap<String, Object>();
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
params.put(PARAM_KEY_READ_THUMBNAILS, Boolean.valueOf(!ignoreImageData));
final JpegPhotoshopMetadata metadata = new JpegImageParser()
.getPhotoshopMetadata(byteSource, params);
assertNotNull(metadata);
final File noIptcFile = removeIptc(byteSource);
final JpegPhotoshopMetadata outMetadata = new JpegImageParser()
.getPhotoshopMetadata(new ByteSourceFile(noIptcFile),
params);
// FIXME should either be null or empty
assertTrue(outMetadata == null
|| outMetadata.getItems().size() == 0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void dump()
{
dump(new PrintWriter(new OutputStreamWriter(System.out)));
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
public void dump()
{
PrintWriter pw = new PrintWriter(System.out);
dump(pw);
pw.flush();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void writeImage(final BufferedImage src, final File file,
final ImageFormat format, final Map<String, Object> params) throws ImageWriteException,
IOException {
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(file);
os = new BufferedOutputStream(os);
writeImage(src, os, format, params);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
public static void writeImage(final BufferedImage src, final File file,
final ImageFormat format, final Map<String, Object> params) throws ImageWriteException,
IOException {
try (FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream os = new BufferedOutputStream(fos)) {
writeImage(src, os, format, params);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static byte[] decompressT4_1D(final byte[] compressed, final int width,
final int height, final boolean hasFill) throws ImageReadException {
final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(compressed));
BitArrayOutputStream outputStream = null;
boolean canThrow = false;
try {
outputStream = new BitArrayOutputStream();
for (int y = 0; y < height; y++) {
int rowLength;
try {
T4_T6_Tables.Entry entry = CONTROL_CODES.decode(inputStream);
if (!isEOL(entry, hasFill)) {
throw new ImageReadException("Expected EOL not found");
}
int color = WHITE;
for (rowLength = 0; rowLength < width;) {
final int runLength = readTotalRunLength(inputStream, color);
for (int i = 0; i < runLength; i++) {
outputStream.writeBit(color);
}
color = 1 - color;
rowLength += runLength;
}
} catch (final HuffmanTreeException huffmanException) {
throw new ImageReadException("Decompression error", huffmanException);
}
if (rowLength == width) {
outputStream.flush();
} else if (rowLength > width) {
throw new ImageReadException("Unrecoverable row length error in image row " + y);
}
}
final byte[] ret = outputStream.toByteArray();
canThrow = true;
return ret;
} finally {
try {
IoUtils.closeQuietly(canThrow, outputStream);
} catch (final IOException ioException) {
throw new ImageReadException("I/O error", ioException);
}
}
}
#location 39
#vulnerability type RESOURCE_LEAK | #fixed code
public static byte[] decompressT4_1D(final byte[] compressed, final int width,
final int height, final boolean hasFill) throws ImageReadException {
final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(compressed));
try (BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
for (int y = 0; y < height; y++) {
int rowLength;
try {
T4_T6_Tables.Entry entry = CONTROL_CODES.decode(inputStream);
if (!isEOL(entry, hasFill)) {
throw new ImageReadException("Expected EOL not found");
}
int color = WHITE;
for (rowLength = 0; rowLength < width;) {
final int runLength = readTotalRunLength(inputStream, color);
for (int i = 0; i < runLength; i++) {
outputStream.writeBit(color);
}
color = 1 - color;
rowLength += runLength;
}
} catch (final HuffmanTreeException huffmanException) {
throw new ImageReadException("Decompression error", huffmanException);
}
if (rowLength == width) {
outputStream.flush();
} else if (rowLength > width) {
throw new ImageReadException("Unrecoverable row length error in image row " + y);
}
}
final byte[] ret = outputStream.toByteArray();
return ret;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void changeSelection(int row, int column, boolean toggle, boolean extend) {
// For shift+click
lastRow = currentRow;
lastColumn = currentColumn;
currentRow = row;
currentColumn = column;
super.changeSelection(row, column, toggle, extend);
// If file changed
if (currentRow != lastRow || (currentColumn != lastColumn && viewMode != TableViewMode.FULL)) {
// Update selection changed timestamp
selectionChangedTimestamp = System.currentTimeMillis();
// notify registered TableSelectionListener instances that the currently selected file has changed
fireSelectedFileChangedEvent();
}
// // Don't refresh status bar if up, down, space or insert key is pressed (repeated key strokes).
// // Status bar will be refreshed whenever the key is released.
// // We need this limit because refreshing status bar takes time.
// if(downKeyDown || upKeyDown || spaceKeyDown || insertKeyDown)
// return;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void changeSelection(int row, int column, boolean toggle, boolean extend) {
// For shift+click
lastRow = currentRow;
int lastColumn = currentColumn;
currentRow = row;
currentColumn = column;
super.changeSelection(row, column, toggle, extend);
// If file changed
if (currentRow != lastRow || (currentColumn != lastColumn && viewMode != TableViewMode.FULL)) {
// Update selection changed timestamp
selectionChangedTimestamp = System.currentTimeMillis();
// notify registered TableSelectionListener instances that the currently selected file has changed
fireSelectedFileChangedEvent();
}
// // Don't refresh status bar if up, down, space or insert key is pressed (repeated key strokes).
// // Status bar will be refreshed whenever the key is released.
// // We need this limit because refreshing status bar takes time.
// if(downKeyDown || upKeyDown || spaceKeyDown || insertKeyDown)
// return;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void performAction() {
AbstractFile targetFile = mainFrame.getActiveTable().getSelectedFile();
if (targetFile == null) {
targetFile = mainFrame.getInactiveTable().getFileTableModel().getFileAt(0).getParent();
}
AbstractFile linkPath = mainFrame.getActivePanel().getCurrentFolder();
new CreateSymLinkDialog(mainFrame, linkPath, targetFile).showDialog();
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void performAction() {
AbstractFile targetFile = mainFrame.getActiveTable().getSelectedFile();
if (targetFile == null) {
targetFile = mainFrame.getActiveTable().getFileTableModel().getFileAt(0).getParent();
}
AbstractFile linkPath = mainFrame.getInactivePanel().getCurrentFolder();
new CreateSymLinkDialog(mainFrame, linkPath, targetFile).showDialog();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void performAction() {
AbstractFile targetFile = mainFrame.getActiveTable().getSelectedFile();
if (targetFile == null) {
targetFile = mainFrame.getInactiveTable().getFileTableModel().getFileAt(0).getParent();
}
AbstractFile linkPath = mainFrame.getActivePanel().getCurrentFolder();
new CreateSymLinkDialog(mainFrame, linkPath, targetFile).showDialog();
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void performAction() {
AbstractFile targetFile = mainFrame.getActiveTable().getSelectedFile();
if (targetFile == null) {
targetFile = mainFrame.getActiveTable().getFileTableModel().getFileAt(0).getParent();
}
AbstractFile linkPath = mainFrame.getInactivePanel().getCurrentFolder();
new CreateSymLinkDialog(mainFrame, linkPath, targetFile).showDialog();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void shouldHandleExceptionDuringRequestCreation() throws URISyntaxException, IOException {
exception.expect(IOException.class);
exception.expectMessage("Could not create request");
final AsyncClientHttpRequestFactory factory = (uri, httpMethod) -> {
throw new IOException("Could not create request");
};
Rest.create(factory, emptyList())
.get("http://localhost/")
.dispatch(series(),
on(SUCCESSFUL).call(pass()));
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void shouldHandleExceptionDuringRequestCreation() throws URISyntaxException, IOException {
exception.expect(IOException.class);
exception.expectMessage("Could not create request");
final AsyncClientHttpRequestFactory factory = (uri, httpMethod) -> {
throw new IOException("Could not create request");
};
Rest.builder().requestFactory(factory).build()
.get("http://localhost/")
.dispatch(series(),
on(SUCCESSFUL).call(pass()));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public String getType() {
return ElementUtils.contains(getRoot(), "name").getTextTrim();
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public String getType() {
return ElementUtils.contains(getRoot(), "type").getTextTrim();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testPublishDeleteShapeZip() throws FileNotFoundException, IOException {
if (!enabled()) {
return;
}
// Assume.assumeTrue(enabled);
String ns = "it.geosolutions";
String storeName = "resttestshp";
String layerName = "cities";
File zipFile = new ClassPathResource("testdata/resttestshp.zip").getFile();
// known state?
cleanupTestFT(layerName, ns, storeName);
// test insert
boolean published = publisher.publishShp(ns, storeName, layerName, zipFile);
assertTrue("publish() failed", published);
assertTrue(existsLayer(layerName));
RESTLayer layer = reader.getLayer(layerName);
LOGGER.info("Layer style is " + layer.getDefaultStyle());
//test delete
boolean ok = publisher.unpublishFeatureType(ns, storeName, layerName);
assertTrue("Unpublish() failed", ok);
assertFalse(existsLayer(layerName));
// remove also datastore
boolean dsRemoved = publisher.removeDatastore(ns, storeName);
assertTrue("removeDatastore() failed", dsRemoved);
}
#location 23
#vulnerability type NULL_DEREFERENCE | #fixed code
public void testPublishDeleteShapeZip() throws FileNotFoundException, IOException {
if (!enabled()) {
return;
}
// Assume.assumeTrue(enabled);
deleteAllWorkspaces();
assertTrue(publisher.createWorkspace(DEFAULT_WS));
// String ns = "it.geosolutions";
String storeName = "resttestshp";
String layerName = "cities";
File zipFile = new ClassPathResource("testdata/resttestshp.zip").getFile();
// known state?
cleanupTestFT(layerName, DEFAULT_WS, storeName);
// test insert
boolean published = publisher.publishShp(DEFAULT_WS, storeName, layerName, zipFile);
assertTrue("publish() failed", published);
assertTrue(existsLayer(layerName));
RESTLayer layer = reader.getLayer(layerName);
LOGGER.info("Layer style is " + layer.getDefaultStyle());
//test delete
boolean ok = publisher.unpublishFeatureType(DEFAULT_WS, storeName, layerName);
assertTrue("Unpublish() failed", ok);
assertFalse(existsLayer(layerName));
// remove also datastore
boolean dsRemoved = publisher.removeDatastore(DEFAULT_WS, storeName);
assertTrue("removeDatastore() failed", dsRemoved);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Before
public void setup() throws Exception {
String ws = "topp";
String storeName = "testshpcollection";
// Delete all resources except styles
deleteAllWorkspacesRecursively();
// Create workspace
assertTrue(publisher.createWorkspace(ws));
// Publish shp collection
URI location = new ClassPathResource("testdata/multipleshp.zip").getFile().toURI();
assertTrue(publisher.publishShpCollection(ws, storeName, location));
String storeType = reader.getDatastore(ws, storeName).getStoreType();
assertEquals(storeType, "Shapefile");
// Test published layer names
List<String> layers = reader.getLayers().getNames();
assertTrue(layers.contains("cities"));
assertTrue(layers.contains("boundaries"));
// Publish style
publisher.publishStyle(new ClassPathResource("testdata/default_line.sld").getFile(), "default_line");
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Before
public void setup() throws Exception {
if (enabled()){
init();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCreateDeletePostGISDatastore() {
if (!enabled()) {
return;
}
String wsName = "it.geosolutions";
String datastoreName = "resttestpostgis";
String description = "description";
String dsNamespace = "http://www.geo-solutions.it";
boolean exposePrimaryKeys = true;
boolean validateConnections = false;
String primaryKeyMetadataTable = "test";
GSPostGISDatastoreEncoder datastoreEncoder = new GSPostGISDatastoreEncoder();
datastoreEncoder.defaultInit();
datastoreEncoder.addName(datastoreName);
datastoreEncoder.addDescription(description);
datastoreEncoder.addNamespace(dsNamespace);
datastoreEncoder.addHost(pgHost);
datastoreEncoder.addPort(pgPort);
datastoreEncoder.addDatabase(pgDatabase);
datastoreEncoder.addSchema(pgSchema);
datastoreEncoder.addUser(pgUser);
datastoreEncoder.addPassword(pgPassword);
datastoreEncoder.addExposePrimaryKeys(exposePrimaryKeys);
datastoreEncoder.addValidateConnections(validateConnections);
datastoreEncoder.addPrimaryKeyMetadataTable(primaryKeyMetadataTable);
// creation test
boolean created = publisher.createPostGISDatastore(wsName, datastoreEncoder);
if( ! pgIgnore )
assertTrue("PostGIS datastore not created", created);
else if( ! created)
LOGGER.error("*** Datastore " + datastoreName + " has not been created.");
RESTDataStore datastore = reader.getDatastore(wsName, datastoreName);
LOGGER.info("The type of the created datastore is: " + datastore.getType());
// removing test
boolean removed = publisher.removeDatastore(wsName, datastoreName);
if( ! pgIgnore )
assertTrue("PostGIS datastore not removed", removed);
else if( ! removed )
LOGGER.error("*** Datastore " + datastoreName + " has not been removed.");
}
#location 39
#vulnerability type NULL_DEREFERENCE | #fixed code
public void testCreateDeletePostGISDatastore() {
if (!enabled()) {
return;
}
deleteAll();
String wsName = DEFAULT_WS;
String datastoreName = "resttestpostgis";
String description = "description";
String dsNamespace = "http://www.geo-solutions.it";
boolean exposePrimaryKeys = true;
boolean validateConnections = false;
String primaryKeyMetadataTable = "test";
GSPostGISDatastoreEncoder datastoreEncoder = new GSPostGISDatastoreEncoder();
datastoreEncoder.defaultInit();
datastoreEncoder.addName(datastoreName);
datastoreEncoder.addDescription(description);
datastoreEncoder.addNamespace(dsNamespace);
datastoreEncoder.addHost(pgHost);
datastoreEncoder.addPort(pgPort);
datastoreEncoder.addDatabase(pgDatabase);
datastoreEncoder.addSchema(pgSchema);
datastoreEncoder.addUser(pgUser);
datastoreEncoder.addPassword(pgPassword);
datastoreEncoder.addExposePrimaryKeys(exposePrimaryKeys);
datastoreEncoder.addValidateConnections(validateConnections);
datastoreEncoder.addPrimaryKeyMetadataTable(primaryKeyMetadataTable);
assertTrue(publisher.createWorkspace(wsName));
// creation test
boolean created = publisher.createPostGISDatastore(wsName, datastoreEncoder);
if( ! pgIgnore )
assertTrue("PostGIS datastore not created", created);
else if( ! created)
LOGGER.error("*** Datastore " + datastoreName + " has not been created.");
RESTDataStore datastore = reader.getDatastore(wsName, datastoreName);
LOGGER.info("The type of the created datastore is: " + datastore.getType());
// removing test
boolean removed = publisher.removeDatastore(wsName, datastoreName);
if( ! pgIgnore )
assertTrue("PostGIS datastore not removed", removed);
else if( ! removed )
LOGGER.error("*** Datastore " + datastoreName + " has not been removed.");
assertTrue(publisher.removeWorkspace(wsName));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void deleteAllLayerGroups() {
List<String> groups = reader.getLayerGroups().getNames();
LOGGER.info("Found " + groups.size() + " layerGroups");
for (String groupName : groups) {
RESTLayerGroup group = reader.getLayerGroup(groupName);
if (groups != null) {
StringBuilder sb = new StringBuilder("Group: ").append(groupName).append(":");
for (NameLinkElem layer : group.getLayerList()) {
sb.append(" ").append(layer);
}
boolean removed = publisher.removeLayerGroup(groupName);
LOGGER.info(sb.toString() + ": removed: " + removed);
assertTrue("LayerGroup not removed: " + groupName, removed);
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
private void deleteAllLayerGroups() {
List<String> groups = reader.getLayerGroups().getNames();
LOGGER.info("Found " + groups.size() + " layerGroups");
for (String groupName : groups) {
RESTLayerGroup group = reader.getLayerGroup(groupName);
if (groups != null) {
StringBuilder sb = new StringBuilder("Group: ").append(groupName).append(":");
for (NameLinkElem layer : group.getPublishedList()) {
sb.append(" ").append(layer);
}
boolean removed = publisher.removeLayerGroup(groupName);
LOGGER.info(sb.toString() + ": removed: " + removed);
assertTrue("LayerGroup not removed: " + groupName, removed);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<String> getWorkspaceNames() {
RESTWorkspaceList list = getWorkspaces();
List<String> names = new ArrayList<String>(list.size());
for (RESTWorkspaceList.RESTShortWorkspace item : list) {
names.add(item.getName());
}
return names;
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
public List<String> getWorkspaceNames() {
RESTWorkspaceList list = getWorkspaces();
if(list==null){
return Collections.emptyList();
}
List<String> names = new ArrayList<String>(list.size());
for (RESTWorkspaceList.RESTShortWorkspace item : list) {
names.add(item.getName());
}
return names;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private GSImageMosaicEncoder copyParameters(String wsName, String coverageStoreName,
String csname) throws NumberFormatException {
// get current config for the coverage to extract the params we want to set again
final RESTCoverage coverage = reader.getCoverage(wsName, coverageStoreName, csname);
final Map<String, String> params = coverage.getParametersList();
// prepare and fill the encoder
final GSImageMosaicEncoder coverageEncoder = new GSImageMosaicEncoder();
coverageEncoder.setName("mosaic");
// set the current params, change here if you want to change the values
for(Map.Entry<String, String> entry:params.entrySet()){
if(entry.getKey().equals(GSImageMosaicEncoder.allowMultithreading)){
coverageEncoder.setAllowMultithreading(Boolean.parseBoolean(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.backgroundValues)){
coverageEncoder.setBackgroundValues(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.filter)){
coverageEncoder.setFilter(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.inputTransparentColor)){
coverageEncoder.setInputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.maxAllowedTiles)){
coverageEncoder.setMaxAllowedTiles(Integer.parseInt(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.MERGEBEHAVIOR)){
coverageEncoder.setMergeBehavior(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.outputTransparentColor)){
coverageEncoder.setOutputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SORTING)){
coverageEncoder.setSORTING(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SUGGESTED_TILE_SIZE)){
coverageEncoder.setSUGGESTED_TILE_SIZE(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.USE_JAI_IMAGEREAD)){
coverageEncoder.setUSE_JAI_IMAGEREAD(Boolean.parseBoolean(entry.getValue()));
continue;
}
}
return coverageEncoder;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
private GSImageMosaicEncoder copyParameters(String wsName, String coverageStoreName,
String csname) throws NumberFormatException {
// get current config for the coverage to extract the params we want to set again
final RESTCoverage coverage = reader.getCoverage(wsName, coverageStoreName, csname);
if (coverage==null)
return null;
final Map<String, String> params = coverage.getParametersList();
// prepare and fill the encoder
final GSImageMosaicEncoder coverageEncoder = new GSImageMosaicEncoder();
coverageEncoder.setName("mosaic");
// set the current params, change here if you want to change the values
for(Map.Entry<String, String> entry:params.entrySet()){
if(entry.getKey().equals(GSImageMosaicEncoder.allowMultithreading)){
coverageEncoder.setAllowMultithreading(Boolean.parseBoolean(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.backgroundValues)){
coverageEncoder.setBackgroundValues(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.filter)){
coverageEncoder.setFilter(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.inputTransparentColor)){
coverageEncoder.setInputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.maxAllowedTiles)){
coverageEncoder.setMaxAllowedTiles(Integer.parseInt(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.MERGEBEHAVIOR)){
coverageEncoder.setMergeBehavior(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.outputTransparentColor)){
coverageEncoder.setOutputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SORTING)){
coverageEncoder.setSORTING(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SUGGESTED_TILE_SIZE)){
coverageEncoder.setSUGGESTED_TILE_SIZE(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.USE_JAI_IMAGEREAD)){
coverageEncoder.setUSE_JAI_IMAGEREAD(Boolean.parseBoolean(entry.getValue()));
continue;
}
}
return coverageEncoder;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean configureCoverage(final GSCoverageEncoder ce, final String wsname,
final String csname) {
final String cname = ce.getName();
if (cname == null) {
if (LOGGER.isErrorEnabled())
LOGGER.error("Unable to configure a coverage with no name try using GSCoverageEncoder.setName(String)");
return false;
}
// retrieve coverage name
GeoServerRESTReader reader;
try {
reader = new GeoServerRESTReader(restURL, gsuser, gspass);
} catch (MalformedURLException e) {
if (LOGGER.isErrorEnabled())
LOGGER.error(e.getLocalizedMessage(), e);
return false;
}
final RESTCoverageList covList = reader.getCoverages(wsname, csname);
if (covList.isEmpty()) {
if (LOGGER.isErrorEnabled())
LOGGER.error("No coverages found in new coveragestore " + csname);
return false;
}
final Iterator<NameLinkElem> it = covList.iterator();
boolean found = false;
while (it.hasNext()) {
NameLinkElem nameElem = it.next();
if (nameElem.getName().equals(cname)) {
found = true;
break;
}
}
// if no coverage to configure is found return false
if (!found) {
if (LOGGER.isErrorEnabled())
LOGGER.error("No coverages found in new coveragestore " + csname + " called "
+ cname);
return false;
}
// configure the selected coverage
final String url = restURL + "/rest/workspaces/" + wsname + "/coveragestores/" + csname
+ "/coverages/" + cname + ".xml";
final String xmlBody = ce.toString();
final String sendResult = HTTPUtils.putXml(url, xmlBody, gsuser, gspass);
if (sendResult != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Coverage successfully configured " + wsname + ":" + csname + ":"
+ cname);
}
} else {
if (LOGGER.isWarnEnabled())
LOGGER.warn("Error configuring coverage " + wsname + ":" + csname + ":" + cname
+ " (" + sendResult + ")");
}
return sendResult != null;
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
public boolean configureCoverage(final GSCoverageEncoder ce, final String wsname,
final String csname) {
return configureCoverage(ce, wsname, csname, ce.getName());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void deleteStylesForWorkspace(String workspace) {
RESTStyleList styles = styleManager.getStyles(workspace);
for (NameLinkElem nameLinkElem : styles) {
removeStyleInWorkspace(workspace, nameLinkElem.getName(), true);
}
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
private void deleteStylesForWorkspace(String workspace) {
RESTStyleList styles = styleManager.getStyles(workspace);
if (styles==null)
return;
for (NameLinkElem nameLinkElem : styles) {
removeStyleInWorkspace(workspace, nameLinkElem.getName(), true);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Before
public void setup() throws Exception {
String ws = "topp";
String storeName = "testshpcollection";
// Delete all resources except styles
deleteAllWorkspacesRecursively();
// Create workspace
assertTrue(publisher.createWorkspace(ws));
// Publish shp collection
URI location = new ClassPathResource("testdata/multipleshp.zip").getFile().toURI();
assertTrue(publisher.publishShpCollection(ws, storeName, location));
String storeType = reader.getDatastore(ws, storeName).getStoreType();
assertEquals(storeType, "Shapefile");
// Test published layer names
List<String> layers = reader.getLayers().getNames();
assertTrue(layers.contains("cities"));
assertTrue(layers.contains("boundaries"));
// Publish style
publisher.publishStyle(new ClassPathResource("testdata/default_line.sld").getFile(), "default_line");
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
@Before
public void setup() throws Exception {
if (enabled()){
init();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void fixDimensions(String wsName, String coverageStoreName, String csname) {
// get current config for the coverage to extract the params we want to set again
final RESTCoverage coverage = reader.getCoverage(wsName, coverageStoreName, csname);
final Map<String, String> params = coverage.getParametersList();
// prepare and fill the encoder
final GSImageMosaicEncoder coverageEncoder = new GSImageMosaicEncoder();
coverageEncoder.setName("mosaic");
// set the current params, change here if you want to change the values
for(Map.Entry<String, String> entry:params.entrySet()){
if(entry.getKey().equals(GSImageMosaicEncoder.allowMultithreading)){
coverageEncoder.setAllowMultithreading(Boolean.parseBoolean(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.backgroundValues)){
coverageEncoder.setBackgroundValues(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.filter)){
coverageEncoder.setFilter(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.inputTransparentColor)){
coverageEncoder.setInputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.maxAllowedTiles)){
coverageEncoder.setMaxAllowedTiles(Integer.parseInt(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.MERGEBEHAVIOR)){
coverageEncoder.setMergeBehavior(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.outputTransparentColor)){
coverageEncoder.setOutputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SORTING)){
coverageEncoder.setSORTING(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SUGGESTED_TILE_SIZE)){
coverageEncoder.setSUGGESTED_TILE_SIZE(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.USE_JAI_IMAGEREAD)){
coverageEncoder.setUSE_JAI_IMAGEREAD(Boolean.parseBoolean(entry.getValue()));
continue;
}
}
// activate time dimension
final GSDimensionInfoEncoder time=new GSDimensionInfoEncoder(true);
time.setUnit("Seconds");
time.setUnitSymbol("s");
time.setPresentation(Presentation.CONTINUOUS_INTERVAL);
coverageEncoder.setMetadataDimension("time", time);
// activate run which is a custom dimension
final GSDimensionInfoEncoder run=new GSDimensionInfoEncoder(true);
run.setPresentation(Presentation.LIST);
run.setUnit("Hours");
run.setUnitSymbol("h");
coverageEncoder.setMetadataDimension("run", run,true);
// persiste the changes
boolean config=publisher.configureCoverage(coverageEncoder, wsName, csname);
assertTrue(config);
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
private void fixDimensions(String wsName, String coverageStoreName, String csname) {
final GSImageMosaicEncoder coverageEncoder = copyParameters(wsName, coverageStoreName,
csname);
// activate time dimension
final GSDimensionInfoEncoder time=new GSDimensionInfoEncoder(true);
time.setUnit("Seconds");
time.setUnitSymbol("s");
time.setPresentation(Presentation.CONTINUOUS_INTERVAL);
coverageEncoder.setMetadataDimension("time", time);
// activate run which is a custom dimension
final GSDimensionInfoEncoder run=new GSDimensionInfoEncoder(true);
run.setPresentation(Presentation.LIST);
run.setUnit("Hours");
run.setUnitSymbol("h");
coverageEncoder.setMetadataDimension("run", run,true);
// persiste the changes
boolean config=publisher.configureCoverage(coverageEncoder, wsName, csname);
assertTrue(config);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCreateDeletePostGISDatastore() {
if (!enabled()) {
return;
}
String wsName = "it.geosolutions";
String datastoreName = "resttestpostgis";
String description = "description";
String dsNamespace = "http://www.geo-solutions.it";
boolean exposePrimaryKeys = true;
boolean validateConnections = false;
String primaryKeyMetadataTable = "test";
GSPostGISDatastoreEncoder datastoreEncoder = new GSPostGISDatastoreEncoder();
datastoreEncoder.defaultInit();
datastoreEncoder.addName(datastoreName);
datastoreEncoder.addDescription(description);
datastoreEncoder.addNamespace(dsNamespace);
datastoreEncoder.addHost(pgHost);
datastoreEncoder.addPort(pgPort);
datastoreEncoder.addDatabase(pgDatabase);
datastoreEncoder.addSchema(pgSchema);
datastoreEncoder.addUser(pgUser);
datastoreEncoder.addPassword(pgPassword);
datastoreEncoder.addExposePrimaryKeys(exposePrimaryKeys);
datastoreEncoder.addValidateConnections(validateConnections);
datastoreEncoder.addPrimaryKeyMetadataTable(primaryKeyMetadataTable);
// creation test
boolean created = publisher.createPostGISDatastore(wsName, datastoreEncoder);
if( ! pgIgnore )
assertTrue("PostGIS datastore not created", created);
else if( ! created)
LOGGER.error("*** Datastore " + datastoreName + " has not been created.");
RESTDataStore datastore = reader.getDatastore(wsName, datastoreName);
LOGGER.info("The type of the created datastore is: " + datastore.getType());
// removing test
boolean removed = publisher.removeDatastore(wsName, datastoreName);
if( ! pgIgnore )
assertTrue("PostGIS datastore not removed", removed);
else if( ! removed )
LOGGER.error("*** Datastore " + datastoreName + " has not been removed.");
}
#location 39
#vulnerability type NULL_DEREFERENCE | #fixed code
public void testCreateDeletePostGISDatastore() {
if (!enabled()) {
return;
}
deleteAll();
String wsName = DEFAULT_WS;
String datastoreName = "resttestpostgis";
String description = "description";
String dsNamespace = "http://www.geo-solutions.it";
boolean exposePrimaryKeys = true;
boolean validateConnections = false;
String primaryKeyMetadataTable = "test";
GSPostGISDatastoreEncoder datastoreEncoder = new GSPostGISDatastoreEncoder();
datastoreEncoder.defaultInit();
datastoreEncoder.addName(datastoreName);
datastoreEncoder.addDescription(description);
datastoreEncoder.addNamespace(dsNamespace);
datastoreEncoder.addHost(pgHost);
datastoreEncoder.addPort(pgPort);
datastoreEncoder.addDatabase(pgDatabase);
datastoreEncoder.addSchema(pgSchema);
datastoreEncoder.addUser(pgUser);
datastoreEncoder.addPassword(pgPassword);
datastoreEncoder.addExposePrimaryKeys(exposePrimaryKeys);
datastoreEncoder.addValidateConnections(validateConnections);
datastoreEncoder.addPrimaryKeyMetadataTable(primaryKeyMetadataTable);
assertTrue(publisher.createWorkspace(wsName));
// creation test
boolean created = publisher.createPostGISDatastore(wsName, datastoreEncoder);
if( ! pgIgnore )
assertTrue("PostGIS datastore not created", created);
else if( ! created)
LOGGER.error("*** Datastore " + datastoreName + " has not been created.");
RESTDataStore datastore = reader.getDatastore(wsName, datastoreName);
LOGGER.info("The type of the created datastore is: " + datastore.getType());
// removing test
boolean removed = publisher.removeDatastore(wsName, datastoreName);
if( ! pgIgnore )
assertTrue("PostGIS datastore not removed", removed);
else if( ! removed )
LOGGER.error("*** Datastore " + datastoreName + " has not been removed.");
assertTrue(publisher.removeWorkspace(wsName));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void failRequestLimitExceeded(Operation request) {
// Add a header indicating retry should be attempted after some interval.
// Currently set to just one second, subject to change in the future
request.addResponseHeader(Operation.RETRY_AFTER_HEADER, "1");
// a specific ServiceErrorResponse will be added in the future with retry hints
request.setStatusCode(Operation.STATUS_CODE_UNAVAILABLE)
.fail(new CancellationException("queue limit exceeded"));
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
ScheduledExecutorService getScheduledExecutor() {
return this.scheduledExecutor;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
this.isStarted = false;
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
// In practice, it's safe not to synchornize here, but this make Findbugs happy.
synchronized (this) {
this.isStarted = false;
}
if (this.host != null) {
this.host.stopService(this.callbackService);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void paginatedbroadcastQueryTasksOnExampleStates () throws Throwable {
VerificationHost targetHost = this.host.getPeerHost();
URI exampleFactoryURI = UriUtils.buildUri(targetHost, ExampleFactoryService.SELF_LINK);
int serviceCount = 100;
int resultLimit = 30;
this.host.testStart(serviceCount);
List<URI> exampleServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
ExampleServiceState s = new ExampleServiceState();
s.name = "document" + i;
s.documentSelfLink = s.name;
exampleServices.add(UriUtils.buildUri(this.host.getUri(),
ExampleFactoryService.SELF_LINK, s.documentSelfLink));
this.host.send(Operation.createPost(exampleFactoryURI)
.setBody(s)
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
QuerySpecification q = new QuerySpecification();
Query kindClause = new Query();
kindClause.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
q.query = kindClause;
q.options = EnumSet.of(QueryOption.EXPAND_CONTENT, QueryOption.BROADCAST);
q.resultLimit = resultLimit;
QueryTask task = QueryTask.create(q);
URI taskUri = this.host.createQueryTaskService(task, false, task.taskInfo.isDirect, task, null);
task = this.host.waitForQueryTaskCompletion(task.querySpec, 0, 0, taskUri, false, false);
targetHost.testStart(1);
Operation startGet = Operation
.createGet(taskUri)
.setCompletion((o, e) -> {
if (e != null) {
targetHost.failIteration(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
assertTrue(0 == rsp.results.documentCount);
assertTrue(rsp.results.nextPageLink.contains(UriUtils.buildUriPath(ServiceUriPaths.CORE,
BroadcastQueryPageService.SELF_LINK_PREFIX)));
targetHost.completeIteration();
});
targetHost.send(startGet);
targetHost.testWait();
String nextPageLink = task.results.nextPageLink;
Set<String> documentLinks = new HashSet<>();
while (nextPageLink != null) {
List<String> pageLinks = new ArrayList<>();
URI u = UriUtils.buildUri(targetHost, nextPageLink);
targetHost.testStart(1);
Operation get = Operation
.createGet(u)
.setCompletion((o, e) -> {
if (e != null) {
targetHost.failIteration(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
pageLinks.add(rsp.results.nextPageLink);
documentLinks.addAll(rsp.results.documentLinks);
targetHost.completeIteration();
});
targetHost.send(get);
targetHost.testWait();
nextPageLink = pageLinks.isEmpty() ? null : pageLinks.get(0);
}
assertEquals(serviceCount, documentLinks.size());
for (int i = 0; i < serviceCount; i++) {
assertTrue(documentLinks.contains(ExampleFactoryService.SELF_LINK + "/document" + i));
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
private void paginatedbroadcastQueryTasksOnExampleStates () throws Throwable {
VerificationHost targetHost = this.host.getPeerHost();
int serviceCount = 100;
int resultLimit = 30;
QuerySpecification q = new QuerySpecification();
Query kindClause = new Query();
kindClause.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
q.query = kindClause;
q.options = EnumSet.of(QueryOption.EXPAND_CONTENT, QueryOption.BROADCAST);
q.resultLimit = resultLimit;
QueryTask task = QueryTask.create(q);
URI taskUri = this.host.createQueryTaskService(task, false, task.taskInfo.isDirect, task, null);
task = this.host.waitForQueryTaskCompletion(task.querySpec, 0, 0, taskUri, false, false);
targetHost.testStart(1);
Operation startGet = Operation
.createGet(taskUri)
.setCompletion((o, e) -> {
if (e != null) {
targetHost.failIteration(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
assertTrue(0 == rsp.results.documentCount);
assertTrue(rsp.results.nextPageLink.contains(UriUtils.buildUriPath(ServiceUriPaths.CORE,
BroadcastQueryPageService.SELF_LINK_PREFIX)));
targetHost.completeIteration();
});
targetHost.send(startGet);
targetHost.testWait();
String nextPageLink = task.results.nextPageLink;
Set<String> documentLinks = new HashSet<>();
while (nextPageLink != null) {
List<String> pageLinks = new ArrayList<>();
URI u = UriUtils.buildUri(targetHost, nextPageLink);
targetHost.testStart(1);
Operation get = Operation
.createGet(u)
.setCompletion((o, e) -> {
if (e != null) {
targetHost.failIteration(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
pageLinks.add(rsp.results.nextPageLink);
documentLinks.addAll(rsp.results.documentLinks);
targetHost.completeIteration();
});
targetHost.send(get);
targetHost.testWait();
nextPageLink = pageLinks.isEmpty() ? null : pageLinks.get(0);
}
assertEquals(serviceCount, documentLinks.size());
for (int i = 0; i < serviceCount; i++) {
assertTrue(documentLinks.contains(ExampleFactoryService.SELF_LINK + "/document" + i));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
this.isStarted = false;
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
// In practice, it's safe not to synchornize here, but this make Findbugs happy.
synchronized (this) {
this.isStarted = false;
}
if (this.host != null) {
this.host.stopService(this.callbackService);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private Map<String, LoaderServiceInfo> discoverServices(File libDir,
Map<String, LoaderServiceInfo> existingPackages) {
logFine("Checking for updates in " + libDir.toURI());
Map<String, LoaderServiceInfo> discoveredPackages = new HashMap<String, LoaderService.LoaderServiceInfo>();
boolean updated = false;
for (File file : libDir.listFiles()) {
if (!file.getName().endsWith(".jar")) {
continue;
}
logFine("Found jar file %s", file.toURI());
LoaderServiceInfo packageInfo = existingPackages.get(file.toURI().toString());
if (packageInfo != null) {
long lastModified = file.lastModified();
if (lastModified == packageInfo.fileUpdateTimeMillis) {
// Jar file has been previously loaded.
// Add to the list of discovered packages and skip.
discoveredPackages.put(file.toURI().toString(), packageInfo);
continue;
}
}
try (JarInputStream jar =
new JarInputStream(new FileInputStream(file))) {
while (true) {
JarEntry e = jar.getNextJarEntry();
if (e == null) {
break;
}
String name = e.getName();
// Assuming specific naming convention for
// Service classes
if (isValidServiceClassName(name)) {
logFine("Found service class %s", name);
String className =
name.replaceAll(".class", "").replaceAll("/", ".");
if (packageInfo == null) {
packageInfo = new LoaderServiceInfo();
}
packageInfo.name = file.getName();
packageInfo.fileUpdateTimeMillis = file.lastModified();
updated |= (null == packageInfo.serviceClasses.put(className, null));
discoveredPackages.put(file.toURI().toString(), packageInfo);
}
}
} catch (IOException e) {
logWarning("Problem loading package %s, Exception %s",
file.getName(), Utils.toString(e));
}
}
if (updated) {
return discoveredPackages;
}
return null;
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
private Map<String, LoaderServiceInfo> discoverServices(File libDir,
Map<String, LoaderServiceInfo> existingPackages) {
logFine("Checking for updates in " + libDir.toURI());
Map<String, LoaderServiceInfo> discoveredPackages = new HashMap<String, LoaderService.LoaderServiceInfo>();
boolean updated = false;
File[] files = libDir.listFiles();
if (files == null) {
return null;
}
for (File file : files) {
if (!file.getName().endsWith(".jar")) {
continue;
}
logFine("Found jar file %s", file.toURI());
LoaderServiceInfo packageInfo = existingPackages.get(file.toURI().toString());
if (packageInfo != null) {
long lastModified = file.lastModified();
if (lastModified == packageInfo.fileUpdateTimeMillis) {
// Jar file has been previously loaded.
// Add to the list of discovered packages and skip.
discoveredPackages.put(file.toURI().toString(), packageInfo);
continue;
}
}
try (JarInputStream jar =
new JarInputStream(new FileInputStream(file))) {
while (true) {
JarEntry e = jar.getNextJarEntry();
if (e == null) {
break;
}
String name = e.getName();
// Assuming specific naming convention for
// Service classes
if (isValidServiceClassName(name)) {
logFine("Found service class %s", name);
String className =
name.replaceAll(".class", "").replaceAll("/", ".");
if (packageInfo == null) {
packageInfo = new LoaderServiceInfo();
}
packageInfo.name = file.getName();
packageInfo.fileUpdateTimeMillis = file.lastModified();
updated |= (null == packageInfo.serviceClasses.put(className, null));
discoveredPackages.put(file.toURI().toString(), packageInfo);
}
}
} catch (IOException e) {
logWarning("Problem loading package %s, Exception %s",
file.getName(), Utils.toString(e));
}
}
if (updated) {
return discoveredPackages;
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
this.isStarted = false;
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
// In practice, it's safe not to synchornize here, but this make Findbugs happy.
synchronized (this) {
this.isStarted = false;
}
if (this.host != null) {
this.host.stopService(this.callbackService);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void handleRestore(Operation op, RestoreRequest req) {
IndexWriter w = this.writer;
if (w == null) {
op.fail(new CancellationException());
return;
}
// We already have a slot in the semaphore. Acquire the rest.
final int semaphoreCount = QUERY_THREAD_COUNT + UPDATE_THREAD_COUNT - 1;
try {
this.writerAvailable.acquire(semaphoreCount);
close(w);
File directory = new File(new File(getHost().getStorageSandbox()), this.indexDirectory);
// Copy whatever was there out just in case.
if (directory.exists() && directory.listFiles().length > 0) {
this.logInfo("archiving existing index %s", directory);
archiveCorruptIndexFiles(directory);
}
this.logInfo("restoring index %s from %s md5sum(%s)", directory, req.backupFile,
FileUtils.md5sum(new File(req.backupFile)));
FileUtils.extractZipArchive(new File(req.backupFile), directory.toPath());
this.indexUpdateTimeMicros = Utils.getNowMicrosUtc();
createWriter(directory, true);
op.complete();
this.logInfo("restore complete");
} catch (Throwable e) {
logSevere(e);
op.fail(e);
} finally {
this.writerAvailable.release(semaphoreCount);
}
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
private void handleRestore(Operation op, RestoreRequest req) {
IndexWriter w = this.writer;
if (w == null) {
op.fail(new CancellationException());
return;
}
// We already have a slot in the semaphore. Acquire the rest.
final int semaphoreCount = QUERY_THREAD_COUNT + UPDATE_THREAD_COUNT - 1;
try {
this.writerAvailable.acquire(semaphoreCount);
close(w);
File directory = new File(new File(getHost().getStorageSandbox()), this.indexDirectory);
// Copy whatever was there out just in case.
if (directory.exists()) {
// We know the file list won't be null because directory.exists() returned true,
// but Findbugs doesn't know that, so we make it happy.
File[] files = directory.listFiles();
if (files != null && files.length > 0) {
this.logInfo("archiving existing index %s", directory);
archiveCorruptIndexFiles(directory);
}
}
this.logInfo("restoring index %s from %s md5sum(%s)", directory, req.backupFile,
FileUtils.md5sum(new File(req.backupFile)));
FileUtils.extractZipArchive(new File(req.backupFile), directory.toPath());
this.indexUpdateTimeMicros = Utils.getNowMicrosUtc();
createWriter(directory, true);
op.complete();
this.logInfo("restore complete");
} catch (Throwable e) {
logSevere(e);
op.fail(e);
} finally {
this.writerAvailable.release(semaphoreCount);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
this.isStarted = false;
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
// In practice, it's safe not to synchornize here, but this make Findbugs happy.
synchronized (this) {
this.isStarted = false;
}
if (this.host != null) {
this.host.stopService(this.callbackService);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
this.isStarted = false;
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
// In practice, it's safe not to synchornize here, but this make Findbugs happy.
synchronized (this) {
this.isStarted = false;
}
if (this.host != null) {
this.host.stopService(this.callbackService);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void startOrSynchService(Operation post, Service child) {
Service s = findService(post.getUri().getPath());
if (s == null) {
startService(post, child);
return;
}
Operation synchPut = Operation.createPut(post.getUri())
.setBody(new ServiceDocument())
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_FORWARDING)
.setReplicationDisabled(true)
.addRequestHeader(Operation.REPLICATION_PHASE_HEADER,
Operation.REPLICATION_PHASE_SYNCHRONIZE)
.setReferer(post.getReferer())
.setCompletion((o, e) -> {
if (e != null) {
post.setStatusCode(o.getStatusCode()).setBodyNoCloning(o.getBodyRaw())
.fail(e);
return;
}
post.complete();
});
sendRequest(synchPut);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
ScheduledExecutorService getScheduledExecutor() {
return this.scheduledExecutor;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Autowired(type = PandaTypes.TYPES_LABEL)
@AutowiredParameters(skip = 3, value = {
@Type(with = Src.class, value = "return"),
@Type(with = Src.class, value = "name"),
@Type(with = Src.class, value = "*parameters")
})
boolean parse(ParserData data, LocalData local, ExtractorResult result, Tokens type, String method, Tokens parametersSource) {
MethodVisibility visibility = MethodVisibility.PUBLIC;
boolean isStatic = result.getIdentifiers().contains("static");
ModuleLoader registry = data.getComponent(PandaComponents.PANDA_SCRIPT).getModuleLoader();
ClassPrototype returnType = registry.forClass(type.asString()).get();
ParameterParser parameterParser = new ParameterParser();
List<Parameter> parameters = parameterParser.parse(data, parametersSource);
ClassPrototype[] parameterTypes = ParameterUtils.toTypes(parameters);
MethodScope methodScope = local.allocateInstance(new MethodScope(method, parameters));
ParameterUtils.addAll(methodScope.getVariables(), parameters, 0);
data.setComponent(PandaComponents.SCOPE, methodScope);
ClassPrototype prototype = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE);
ClassPrototypeScope classScope = data.getComponent(ClassPrototypeComponents.CLASS_SCOPE);
PrototypeMethod prototypeMethod = PandaMethod.builder()
.prototype(prototype)
.parameterTypes(parameterTypes)
.methodName(method)
.visibility(visibility)
.returnType(returnType)
.isStatic(isStatic)
.methodBody(new PandaMethodCallback(methodScope))
.build();
prototype.getMethods().registerMethod(prototypeMethod);
return true;
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Autowired(type = PandaTypes.TYPES_LABEL)
@AutowiredParameters(skip = 3, value = {
@Type(with = Src.class, value = "return"),
@Type(with = Src.class, value = "name"),
@Type(with = Src.class, value = "*parameters")
})
boolean parse(ParserData data, LocalData local, ExtractorResult result, Tokens type, String method, Tokens parametersSource) {
MethodVisibility visibility = MethodVisibility.PUBLIC;
boolean isStatic = result.getIdentifiers().contains("static");
ModuleLoader registry = data.getComponent(PandaComponents.PANDA_SCRIPT).getModuleLoader();
ClassPrototypeReference returnType = registry.forClass(type.asString());
ParameterParser parameterParser = new ParameterParser();
List<Parameter> parameters = parameterParser.parse(data, parametersSource);
ClassPrototypeReference[] parameterTypes = ParameterUtils.toTypes(parameters);
MethodScope methodScope = local.allocateInstance(new MethodScope(method, parameters));
ParameterUtils.addAll(methodScope.getVariables(), parameters, 0);
data.setComponent(PandaComponents.SCOPE, methodScope);
ClassPrototype prototype = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE);
ClassPrototypeScope classScope = data.getComponent(ClassPrototypeComponents.CLASS_SCOPE);
PrototypeMethod prototypeMethod = PandaMethod.builder()
.prototype(prototype.getReference())
.parameterTypes(parameterTypes)
.methodName(method)
.visibility(visibility)
.returnType(returnType)
.isStatic(isStatic)
.methodBody(new PandaMethodCallback(methodScope))
.build();
prototype.getMethods().registerMethod(prototypeMethod);
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTokenPattern() {
TokenPattern pattern = TokenPattern.builder()
.compile("(method|hidden|local) [static] <return-type> <name>(<parameters>) \\{ <body> \\}[;]")
.build();
LexicalPatternElement content = pattern.getPatternContent();
Assertions.assertNotNull(content);
TokenExtractorResult result = pattern.extract(SOURCE);
Assertions.assertNotNull(result);
Assertions.assertTrue(result.isMatched());
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testTokenPattern() {
TokenPattern pattern = TokenPattern.builder()
.compile("(method|hidden|local) [static] <return-type> <name>(<parameters>) \\{ <body> \\}[;]")
.build();
LexicalPatternElement content = pattern.getPatternContent();
Assertions.assertNotNull(content);
TokenExtractorResult result = pattern.extract(SOURCE);
Assertions.assertNotNull(result);
//Assertions.assertTrue(result.isMatched());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public NamedExecutable parse(Atom atom) {
final String source = atom.getSourceCode();
final StringBuilder importBuilder = new StringBuilder();
int stage = 0;
Import importElement = null;
String operator = null;
for (char c : source.toCharArray()) {
if (Character.isWhitespace(c) || c == ';') {
switch (stage) {
case 0:
stage = 1;
break;
case 1:
importElement = new Import(importBuilder.toString());
importBuilder.setLength(0);
stage = 2;
break;
case 2:
operator = importBuilder.toString();
importBuilder.setLength(0);
stage = 3;
break;
case 3:
if (operator.equals(">")) {
String specific = importBuilder.toString();
importElement.setSpecific(specific);
} else if (operator.equals("as")) {
String as = importBuilder.toString();
importElement.setAs(as);
}
importBuilder.setLength(0);
stage = 2;
break;
default:
break;
}
} else if (stage == 1) {
importBuilder.append(c);
}
}
return importElement;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public NamedExecutable parse(Atom atom) {
final String source = atom.getSourcesDivider().getLine();
final StringBuilder importBuilder = new StringBuilder();
int stage = 0;
Import importElement = null;
String operator = null;
for (char c : source.toCharArray()) {
if (Character.isWhitespace(c) || c == ';') {
switch (stage) {
case 0:
stage = 1;
break;
case 1:
importElement = new Import(importBuilder.toString());
importBuilder.setLength(0);
stage = 2;
break;
case 2:
operator = importBuilder.toString();
importBuilder.setLength(0);
stage = 3;
break;
case 3:
if (operator.equals(">")) {
String specific = importBuilder.toString();
importElement.setSpecific(specific);
} else if (operator.equals("as")) {
String as = importBuilder.toString();
importElement.setAs(as);
}
importBuilder.setLength(0);
stage = 2;
break;
default:
break;
}
} else if (stage != 0) {
importBuilder.append(c);
}
}
return importElement;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Expression parse(ParserInfo info, TokenizedSource expressionSource) {
if (expressionSource.size() == 1) {
Token token = expressionSource.getToken(0);
String value = token.getTokenValue();
if (token.getType() == TokenType.LITERAL) {
switch (token.getTokenValue()) {
case "null":
return new Expression(new PandaValue(null, null));
case "true":
return toSimpleKnownExpression("panda.lang:Boolean", true);
case "false":
return toSimpleKnownExpression("panda.lang:Boolean", false);
case "this":
ClassPrototype type = info.getComponent(Components.CLASS_PROTOTYPE);
return new Expression(type, new ThisExpressionCallback());
default:
throw new PandaParserException("Unknown literal: " + token);
}
}
if (token.getType() == TokenType.SEQUENCE) {
switch (token.getName()) {
case "String":
return toSimpleKnownExpression("panda.lang:String", value);
default:
throw new PandaParserException("Unknown sequence: " + token);
}
}
if (NumberUtils.isNumber(value)) {
return toSimpleKnownExpression("panda.lang:Int", Integer.parseInt(value));
}
ScopeLinker scopeLinker = info.getComponent(Components.SCOPE_LINKER);
Scope scope = scopeLinker.getCurrentScope();
Variable variable = VariableParserUtils.getVariable(scope, value);
if (variable != null) {
int memoryIndex = VariableParserUtils.indexOf(scope, variable);
return new Expression(variable.getType(), new VariableExpressionCallback(memoryIndex));
}
ClassPrototype prototype = info.getComponent(Components.CLASS_PROTOTYPE);
Field field = prototype.getField(value);
if (field != null) {
int memoryIndex = prototype.getFields().indexOf(field);
return new Expression(field.getType(), new FieldExpressionCallback(field, memoryIndex));
}
}
else if (TokenUtils.equals(expressionSource.get(0), TokenType.KEYWORD, "new")) {
InstanceExpressionParser callbackParser = new InstanceExpressionParser();
callbackParser.parse(expressionSource, info);
InstanceExpressionCallback callback = callbackParser.toCallback();
return new Expression(callback.getReturnType(), callback);
}
PandaTokenReader expressionReader = new PandaTokenReader(expressionSource);
List<TokenizedSource> methodMatches = MethodInvokerExpressionParser.PATTERN.match(expressionReader);
if (methodMatches != null && methodMatches.size() > 0) {
MethodInvokerExpressionParser callbackParser = new MethodInvokerExpressionParser(methodMatches);
callbackParser.parse(expressionSource, info);
MethodInvokerExpressionCallback callback = callbackParser.toCallback();
return new Expression(callback.getReturnType(), callback);
}
List<TokenizedSource> fieldMatches = FieldParser.PATTERN.match(expressionReader);
if (fieldMatches != null && fieldMatches.size() > 0) {
}
throw new PandaParserException("Cannot recognize expression: " + expressionSource.toString());
}
#location 58
#vulnerability type NULL_DEREFERENCE | #fixed code
public Expression parse(ParserInfo info, TokenizedSource expressionSource) {
if (expressionSource.size() == 1) {
Token token = expressionSource.getToken(0);
String value = token.getTokenValue();
if (token.getType() == TokenType.LITERAL) {
switch (token.getTokenValue()) {
case "null":
return new Expression(new PandaValue(null, null));
case "true":
return toSimpleKnownExpression("panda.lang:Boolean", true);
case "false":
return toSimpleKnownExpression("panda.lang:Boolean", false);
case "this":
ClassPrototype type = info.getComponent(Components.CLASS_PROTOTYPE);
return new Expression(type, new ThisExpressionCallback());
default:
throw new PandaParserException("Unknown literal: " + token);
}
}
if (token.getType() == TokenType.SEQUENCE) {
switch (token.getName()) {
case "String":
return toSimpleKnownExpression("panda.lang:String", value);
default:
throw new PandaParserException("Unknown sequence: " + token);
}
}
if (NumberUtils.isNumber(value)) {
return toSimpleKnownExpression("panda.lang:Int", Integer.parseInt(value));
}
ScopeLinker scopeLinker = info.getComponent(Components.SCOPE_LINKER);
Scope scope = scopeLinker.getCurrentScope();
Variable variable = VariableParserUtils.getVariable(scope, value);
if (variable != null) {
int memoryIndex = VariableParserUtils.indexOf(scope, variable);
return new Expression(variable.getType(), new VariableExpressionCallback(memoryIndex));
}
ClassPrototype prototype = info.getComponent(Components.CLASS_PROTOTYPE);
Field field = prototype.getField(value);
if (field != null) {
int memoryIndex = prototype.getFields().indexOf(field);
return new Expression(field.getType(), new FieldExpressionCallback(ThisExpressionCallback.asExpression(prototype), field, memoryIndex));
}
}
else if (TokenUtils.equals(expressionSource.get(0), TokenType.KEYWORD, "new")) {
InstanceExpressionParser callbackParser = new InstanceExpressionParser();
callbackParser.parse(expressionSource, info);
InstanceExpressionCallback callback = callbackParser.toCallback();
return new Expression(callback.getReturnType(), callback);
}
PandaTokenReader expressionReader = new PandaTokenReader(expressionSource);
List<TokenizedSource> methodMatches = MethodInvokerExpressionParser.PATTERN.match(expressionReader);
if (methodMatches != null && methodMatches.size() > 0) {
MethodInvokerExpressionParser callbackParser = new MethodInvokerExpressionParser(methodMatches);
callbackParser.parse(expressionSource, info);
MethodInvokerExpressionCallback callback = callbackParser.toCallback();
return new Expression(callback.getReturnType(), callback);
}
List<TokenizedSource> fieldMatches = FIELD_PATTERN.match(expressionReader);
if (fieldMatches != null && fieldMatches.size() == 2) {
Expression instanceExpression = parse(info, fieldMatches.get(0));
ClassPrototype instanceType = instanceExpression.getReturnType();
Field instanceField = instanceType.getField(fieldMatches.get(1).getLast().getToken().getTokenValue());
if (instanceField == null) {
}
int memoryIndex = instanceType.getFields().indexOf(instanceField);
return new Expression(instanceType, new FieldExpressionCallback(instanceExpression, instanceField, memoryIndex));
}
throw new PandaParserException("Cannot recognize expression: " + expressionSource.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Essence run(Particle particle) {
while (parameters[0].getValue(PBoolean.class).isTrue()) {
Essence o = super.run(particle);
if (o != null) {
return o;
}
}
return null;
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Essence run(Particle particle) {
while (factors[0].getValue(PBoolean.class).isTrue()) {
Essence o = super.run(particle);
if (o != null) {
return o;
}
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean isPublic(Object o) {
int accessFlags = o instanceof ClassFile ?
((ClassFile) o).getAccessFlags() :
o instanceof FieldInfo ? ((FieldInfo) o).getAccessFlags() :
o instanceof MethodInfo ? ((MethodInfo) o).getAccessFlags() : null;
return AccessFlag.isPublic(accessFlags);
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public boolean isPublic(Object o) {
if (o == null) {
return false;
}
if (o instanceof ClassFile) {
return AccessFlag.isPublic(((ClassFile) o).getAccessFlags());
}
if (o instanceof MethodInfo) {
return AccessFlag.isPublic(((MethodInfo) o).getAccessFlags());
}
if (o instanceof FieldInfo) {
return AccessFlag.isPublic(((FieldInfo) o).getAccessFlags());
}
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean extract(TokenizedSource tokenizedSource) {
TokenPatternUnit[] units = pattern.getUnits();
ArrayDistributor<TokenPatternUnit> unitsDistributor = new ArrayDistributor<>(units);
TokenReader tokenReader = new PandaTokenReader(tokenizedSource);
Stack<Separator> separators = new Stack<>();
for (int unitIndex = 0; unitIndex < units.length; unitIndex++) {
TokenPatternUnit unit = unitsDistributor.get(unitIndex);
TokenPatternUnit nextUnit = unitsDistributor.get(unitIndex + 1);
loop:
if (!unit.isHollow()) {
}
else {
}
}
return tokenReader.getIndex() >= tokenizedSource.size();
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
public boolean extract(TokenizedSource tokenizedSource) {
TokenPatternUnit[] units = pattern.getUnits();
ArrayDistributor<TokenPatternUnit> unitsDistributor = new ArrayDistributor<>(units);
TokenReader tokenReader = new PandaTokenReader(tokenizedSource);
TokenHollow hollow = new TokenHollow();
for (int unitIndex = 0; unitIndex < units.length; unitIndex++) {
TokenPatternUnit unit = unitsDistributor.get(unitIndex);
tokenReader.synchronize();
for (TokenRepresentation representation : tokenReader) {
Token token = representation.getToken();
if (unit.equals(token)) {
tokenReader.read();
break;
}
if (!unit.isHollow()) {
return false;
}
TokenPatternUnit nextUnit = unitsDistributor.get(unitIndex + 1);
if (!token.equals(nextUnit) || extractorOpposites.isLocked()) {
extractorOpposites.report(token);
tokenReader.read();
hollow.addToken(token);
continue;
}
hollows.add(hollow);
hollow = new TokenHollow();
break;
}
}
return tokenReader.getIndex() + 1 >= tokenizedSource.size();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public @Nullable Expression parse(ParserData data, TokenizedSource expressionSource, boolean silence) {
ModuleRegistry registry = data.getComponent(PandaComponents.MODULE_REGISTRY);
if (expressionSource.size() == 1) {
Token token = expressionSource.getToken(0);
String value = token.getTokenValue();
if (token.getType() == TokenType.LITERAL) {
switch (token.getTokenValue()) {
case "null":
return new PandaExpression(new PandaValue(null, null));
case "true":
return toSimpleKnownExpression(registry, "boolean", true);
case "false":
return toSimpleKnownExpression(registry, "boolean", false);
case "this":
ClassPrototype type = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE);
return new PandaExpression(type, new ThisExpressionCallback());
default:
throw new PandaParserException("Unknown literal: " + token);
}
}
if (token.getType() == TokenType.SEQUENCE) {
switch (token.getName()) {
case "String":
return toSimpleKnownExpression(registry, "java.lang:String", value);
default:
throw new PandaParserException("Unknown sequence: " + token);
}
}
NumberExpressionParser numberExpressionParser = new NumberExpressionParser();
Value numericValue = numberExpressionParser.parse(data, expressionSource);
if (numericValue != null) {
return new PandaExpression(numericValue);
}
ScopeLinker scopeLinker = data.getComponent(PandaComponents.SCOPE_LINKER);
Scope scope = scopeLinker.getCurrentScope();
Variable variable = VariableParserUtils.getVariable(scope, value);
if (variable != null) {
int memoryIndex = VariableParserUtils.indexOf(scope, variable);
return new PandaExpression(variable.getType(), new VariableExpressionCallback(memoryIndex));
}
ClassPrototype prototype = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE);
if (prototype != null) {
PrototypeField field = prototype.getField(value);
if (field != null) {
int memoryIndex = prototype.getFields().indexOf(field);
return new PandaExpression(field.getType(), new FieldExpressionCallback(ThisExpressionCallback.asExpression(prototype), field, memoryIndex));
}
}
}
if (TokenUtils.equals(expressionSource.getFirst(), Operators.NOT)) {
Expression expression = parse(data, expressionSource.subSource(1, expressionSource.size()));
return new PandaExpression(expression.getReturnType(), new NotLogicalExpressionCallback(expression));
}
MethodInvokerExpressionParser methodInvokerParser = MethodInvokerExpressionUtils.match(expressionSource);
if (methodInvokerParser != null) {
methodInvokerParser.parse(expressionSource, data);
MethodInvokerExpressionCallback callback = methodInvokerParser.toCallback();
return new PandaExpression(callback.getReturnType(), callback);
}
TokenReader expressionReader = new PandaTokenReader(expressionSource);
List<TokenizedSource> constructorMatches = ExpressionPatterns.INSTANCE_PATTERN.match(expressionReader);
if (constructorMatches != null && constructorMatches.size() == 3 && constructorMatches.get(2).size() == 0) {
InstanceExpressionParser callbackParser = new InstanceExpressionParser();
callbackParser.parse(expressionSource, data);
InstanceExpressionCallback callback = callbackParser.toCallback();
return new PandaExpression(callback.getReturnType(), callback);
}
List<TokenizedSource> fieldMatches = ExpressionPatterns.FIELD_PATTERN.match(expressionReader);
if (fieldMatches != null && fieldMatches.size() == 2 && !NumberUtils.startsWithNumber(fieldMatches.get(1))) {
PandaScript script = data.getComponent(PandaComponents.PANDA_SCRIPT);
ImportRegistry importRegistry = script.getImportRegistry();
TokenizedSource instanceSource = fieldMatches.get(0);
ClassPrototype instanceType = null;
Expression fieldLocationExpression = null;
if (instanceSource.size() == 1) {
instanceType = importRegistry.forClass(fieldMatches.get(0).asString());
}
if (instanceType == null) {
fieldLocationExpression = parse(data, fieldMatches.get(0));
instanceType = fieldLocationExpression.getReturnType();
}
if (instanceType == null) {
throw new PandaParserException("Unknown instance source at line " + TokenUtils.getLine(instanceSource));
}
String instanceFieldName = fieldMatches.get(1).asString();
PrototypeField instanceField = instanceType.getField(instanceFieldName);
if (instanceField == null) {
throw new PandaParserException("Class " + instanceType.getClassName() + " does not contain field " + instanceFieldName + " at " + TokenUtils.getLine(expressionSource));
}
int memoryIndex = instanceType.getFields().indexOf(instanceField);
return new PandaExpression(instanceField.getType(), new FieldExpressionCallback(fieldLocationExpression, instanceField, memoryIndex));
}
NumberExpressionParser numberExpressionParser = new NumberExpressionParser();
Value numericValue = numberExpressionParser.parse(data, expressionSource);
if (numericValue != null) {
return new PandaExpression(numericValue);
}
if (MathExpressionUtils.isMathExpression(expressionSource)) {
MathParser mathParser = new MathParser();
MathExpressionCallback expression = mathParser.parse(expressionSource, data);
return new PandaExpression(expression.getReturnType(), expression);
}
if (!silence) {
throw new PandaParserException("Cannot recognize expression: " + expressionSource.toString());
}
return null;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
public @Nullable Expression parse(ParserData data, TokenizedSource expressionSource, boolean silence) {
ModuleRegistry registry = data.getComponent(PandaComponents.MODULE_REGISTRY);
if (expressionSource.size() == 1) {
Token token = expressionSource.getToken(0);
if (token == null) {
throw new PandaParserException("Internal error, token is null");
}
String value = token.getTokenValue();
if (token.getType() == TokenType.LITERAL) {
switch (token.getTokenValue()) {
case "null":
return new PandaExpression(new PandaValue(null, null));
case "true":
return toSimpleKnownExpression(registry, "boolean", true);
case "false":
return toSimpleKnownExpression(registry, "boolean", false);
case "this":
ClassPrototype type = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE);
return new PandaExpression(type, new ThisExpressionCallback());
default:
throw new PandaParserException("Unknown literal: " + token);
}
}
if (token.getType() == TokenType.SEQUENCE) {
switch (token.getName()) {
case "String":
return toSimpleKnownExpression(registry, "java.lang:String", value);
default:
throw new PandaParserException("Unknown sequence: " + token);
}
}
NumberExpressionParser numberExpressionParser = new NumberExpressionParser();
Value numericValue = numberExpressionParser.parse(data, expressionSource);
if (numericValue != null) {
return new PandaExpression(numericValue);
}
ScopeLinker scopeLinker = data.getComponent(PandaComponents.SCOPE_LINKER);
Scope scope = scopeLinker.getCurrentScope();
Variable variable = VariableParserUtils.getVariable(scope, value);
if (variable != null) {
int memoryIndex = VariableParserUtils.indexOf(scope, variable);
return new PandaExpression(variable.getType(), new VariableExpressionCallback(memoryIndex));
}
ClassPrototype prototype = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE);
if (prototype != null) {
PrototypeField field = prototype.getField(value);
if (field != null) {
int memoryIndex = prototype.getFields().indexOf(field);
return new PandaExpression(field.getType(), new FieldExpressionCallback(ThisExpressionCallback.asExpression(prototype), field, memoryIndex));
}
}
}
if (TokenUtils.equals(expressionSource.getFirst(), Operators.NOT)) {
Expression expression = parse(data, expressionSource.subSource(1, expressionSource.size()));
return new PandaExpression(expression.getReturnType(), new NotLogicalExpressionCallback(expression));
}
MethodInvokerExpressionParser methodInvokerParser = MethodInvokerExpressionUtils.match(expressionSource);
if (methodInvokerParser != null) {
methodInvokerParser.parse(expressionSource, data);
MethodInvokerExpressionCallback callback = methodInvokerParser.toCallback();
return new PandaExpression(callback.getReturnType(), callback);
}
TokenReader expressionReader = new PandaTokenReader(expressionSource);
List<TokenizedSource> constructorMatches = ExpressionPatterns.INSTANCE_PATTERN.match(expressionReader);
if (constructorMatches != null && constructorMatches.size() == 3 && constructorMatches.get(2).size() == 0) {
InstanceExpressionParser callbackParser = new InstanceExpressionParser();
callbackParser.parse(expressionSource, data);
InstanceExpressionCallback callback = callbackParser.toCallback();
return new PandaExpression(callback.getReturnType(), callback);
}
List<TokenizedSource> fieldMatches = ExpressionPatterns.FIELD_PATTERN.match(expressionReader);
if (fieldMatches != null && fieldMatches.size() == 2 && !NumberUtils.startsWithNumber(fieldMatches.get(1))) {
PandaScript script = data.getComponent(PandaComponents.PANDA_SCRIPT);
ImportRegistry importRegistry = script.getImportRegistry();
TokenizedSource instanceSource = fieldMatches.get(0);
ClassPrototype instanceType = null;
Expression fieldLocationExpression = null;
if (instanceSource.size() == 1) {
instanceType = importRegistry.forClass(fieldMatches.get(0).asString());
}
if (instanceType == null) {
fieldLocationExpression = parse(data, fieldMatches.get(0));
instanceType = fieldLocationExpression.getReturnType();
}
if (instanceType == null) {
throw new PandaParserException("Unknown instance source at line " + TokenUtils.getLine(instanceSource));
}
String instanceFieldName = fieldMatches.get(1).asString();
PrototypeField instanceField = instanceType.getField(instanceFieldName);
if (instanceField == null) {
throw new PandaParserException("Class " + instanceType.getClassName() + " does not contain field " + instanceFieldName + " at " + TokenUtils.getLine(expressionSource));
}
int memoryIndex = instanceType.getFields().indexOf(instanceField);
return new PandaExpression(instanceField.getType(), new FieldExpressionCallback(fieldLocationExpression, instanceField, memoryIndex));
}
NumberExpressionParser numberExpressionParser = new NumberExpressionParser();
Value numericValue = numberExpressionParser.parse(data, expressionSource);
if (numericValue != null) {
return new PandaExpression(numericValue);
}
if (MathExpressionUtils.isMathExpression(expressionSource)) {
MathParser mathParser = new MathParser();
MathExpressionCallback expression = mathParser.parse(expressionSource, data);
return new PandaExpression(expression.getReturnType(), expression);
}
if (!silence) {
throw new PandaParserException("Cannot recognize expression: " + expressionSource);
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public @Nullable Tokens read(ExpressionParser main, Tokens source) {
Tokens selected = SubparserUtils.readSeparated(main, source, ARRAY_SEPARATORS, SubparserUtils.NAMES_FILTER, MatchableDistributor::hasNext);
MatchableDistributor matchable = new MatchableDistributor(new TokenDistributor(source));
matchable.getDistributor().setIndex(selected != null ? selected.size() : 0);
// at least 4 elements required: <field/variable> [ <index> ]
if ((source.size() - matchable.getIndex()) < 4) {
return null;
}
// read field name
matchable.nextVerified();
// check if the opening section is the square bracket
if (!matchable.nextVerified().contentEquals(Separators.SQUARE_BRACKET_LEFT)) {
return null;
}
// parameters content
while (matchable.hasNext() && !matchable.isMatchable()) {
matchable.nextVerified();
}
// check if the [ ] section is closed
if (!matchable.isMatchable()) {
return null;
}
// check if the closing character was square brace
if (!matchable.current().contentEquals(Separators.SQUARE_BRACKET_RIGHT)) {
return null;
}
selected = source.subSource(0, matchable.getIndex() + 1);
// at least 4 elements required: <field-name> [ <index> ]
if (selected == null || selected.size() < 4 ) {
return null;
}
// array value source has to end with parenthesis
if (!selected.getLast().contentEquals(Separators.SQUARE_BRACKET_RIGHT)) {
return null;
}
return selected;
}
#location 32
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public @Nullable Tokens read(ExpressionParser main, Tokens source) {
SourceStream stream = new PandaSourceStream(source);
ExpressionSubparsers subparsers = main.getSubparsers().fork();
subparsers.removeSubparser(getName());
ExpressionParser parser = new ExpressionParser(main, subparsers);
Tokens value = parser.read(stream);
if (TokensUtils.isEmpty(value)) {
return null;
}
MatchableDistributor matchable = new MatchableDistributor(new TokenDistributor(source));
matchable.getDistributor().setIndex(source.size() - stream.getUnreadLength());
// at least 3 elements required: [ <index> ]
if ((source.size() - matchable.getIndex()) < 3) {
return null;
}
// check if the opening section is the square bracket
if (!matchable.nextVerified().contentEquals(Separators.SQUARE_BRACKET_LEFT)) {
return null;
}
// parameters content
while (matchable.hasNext() && !matchable.isMatchable()) {
matchable.nextVerified();
}
// check if the [ ] section is closed
if (!matchable.isMatchable()) {
return null;
}
// check if the closing character was square brace
if (!matchable.current().contentEquals(Separators.SQUARE_BRACKET_RIGHT)) {
return null;
}
Tokens selected = source.subSource(0, matchable.getIndex() + 1);
// at least 4 elements required: <field-name> [ <index> ]
if (selected == null || selected.size() < 4 ) {
return null;
}
// array value source has to end with parenthesis
if (!selected.getLast().contentEquals(Separators.SQUARE_BRACKET_RIGHT)) {
return null;
}
return selected;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private TokenExtractorResult matchDynamics(List<LexicalPatternElement> elements, TokenizedSource[] dynamics) {
TokenExtractorResult result = new TokenExtractorResult(true);
for (int i = 0; i < elements.size(); i++) {
LexicalPatternElement nodeElement = elements.get(i);
if (nodeElement.isUnit()) {
continue;
}
if (dynamics.length == 0 && nodeElement.isOptional()) {
continue;
}
TokenizedSource nodeContent = dynamics[i];
dynamics[i] = null;
if (nodeContent == null) {
return new TokenExtractorResult();
}
TokenExtractorResult nodeElementResult = this.extract(nodeElement, new PandaTokenReader(nodeContent));
if (!nodeElementResult.isMatched()) {
return new TokenExtractorResult();
}
result.addIdentifier(nodeElement.getIdentifier());
result.merge(nodeElementResult);
}
for (TokenizedSource dynamicContent : dynamics) {
if (dynamicContent != null) {
return new TokenExtractorResult(false);
}
}
return result;
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
private TokenExtractorResult matchDynamics(List<LexicalPatternElement> elements, TokenizedSource[] dynamics) {
TokenExtractorResult result = new TokenExtractorResult(true);
for (int i = 0; i < elements.size(); i++) {
LexicalPatternElement nodeElement = elements.get(i);
if (nodeElement.isUnit()) {
continue;
}
if (dynamics.length == 0 && nodeElement.isOptional()) {
continue;
}
TokenizedSource nodeContent = dynamics[i];
dynamics[i] = null;
if (nodeContent == null) {
return new TokenExtractorResult();
}
TokenDistributor content = new TokenDistributor(nodeContent);
TokenExtractorResult nodeElementResult = this.extract(nodeElement, content);
if (!nodeElementResult.isMatched()) {
return new TokenExtractorResult();
}
if (content.hasNext()) {
int nextIndex = i + 1;
if (nextIndex >= dynamics.length || dynamics[nextIndex] != null) {
return new TokenExtractorResult();
}
dynamics[nextIndex] = new PandaTokenizedSource(content.next(content.length() - content.getIndex()));
}
result.addIdentifier(nodeElement.getIdentifier());
result.merge(nodeElementResult);
}
for (TokenizedSource dynamicContent : dynamics) {
if (dynamicContent != null) {
return new TokenExtractorResult();
}
}
return result;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Variable createVariable(ParserData data, ModuleLoader loader, Scope scope, boolean mutable, boolean nullable, String type, String name) {
ClassPrototype prototype = loader.forClass(type).fetch();
if (!StringUtils.isEmpty(type) && prototype == null) {
throw new PandaParserFailure("Cannot recognize variable type: " + type, data);
}
Variable variable = new PandaVariable(prototype, name, 0, mutable, nullable);
scope.addVariable(variable);
return variable;
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public Variable createVariable(ParserData data, ModuleLoader loader, Scope scope, boolean mutable, boolean nullable, String type, String name) {
if (StringUtils.isEmpty(type)) {
throw new PandaParserFailure("Type does not specified", data);
}
Optional<ClassPrototypeReference> prototype = loader.forClass(type);
if (!prototype.isPresent()) {
throw new PandaParserFailure("Cannot recognize variable type: " + type, data);
}
Variable variable = new PandaVariable(prototype.get(), name, 0, mutable, nullable);
scope.addVariable(variable);
return variable;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<Parameter> parse(ParserData info, @Nullable Tokens tokens) {
if (TokensUtils.isEmpty(tokens)) {
return new ArrayList<>(0);
}
TokenRepresentation[] tokenRepresentations = tokens.toArray();
List<Parameter> parameters = new ArrayList<>(tokenRepresentations.length / 3 + 1);
if (tokens.size() == 0) {
return parameters;
}
for (int i = 0; i < tokenRepresentations.length; i += 3) {
TokenRepresentation parameterTypeRepresentation = tokenRepresentations[i];
TokenRepresentation parameterNameRepresentation = tokenRepresentations[i + 1];
String parameterType = parameterTypeRepresentation.getToken().getTokenValue();
String parameterName = parameterNameRepresentation.getToken().getTokenValue();
PandaScript script = info.getComponent(PandaComponents.PANDA_SCRIPT);
ModuleLoader moduleLoader = script.getModuleLoader();
ClassPrototype type = moduleLoader.forClass(parameterType).get();
if (type == null) {
throw new PandaParserException("Unknown type '" + parameterType + "'");
}
Parameter parameter = new PandaParameter(type, parameterName);
parameters.add(parameter);
if (i + 2 < tokenRepresentations.length) {
TokenRepresentation separatorRepresentation = tokenRepresentations[i + 2];
Token separator = separatorRepresentation.getToken();
if (separator.getType() != TokenType.SEPARATOR) {
throw new PandaParserException("Unexpected token " + separatorRepresentation);
}
}
}
return parameters;
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
public List<Parameter> parse(ParserData info, @Nullable Tokens tokens) {
if (TokensUtils.isEmpty(tokens)) {
return new ArrayList<>(0);
}
TokenRepresentation[] tokenRepresentations = tokens.toArray();
List<Parameter> parameters = new ArrayList<>(tokenRepresentations.length / 3 + 1);
if (tokens.size() == 0) {
return parameters;
}
for (int i = 0; i < tokenRepresentations.length; i += 3) {
TokenRepresentation parameterTypeRepresentation = tokenRepresentations[i];
TokenRepresentation parameterNameRepresentation = tokenRepresentations[i + 1];
String parameterType = parameterTypeRepresentation.getToken().getTokenValue();
String parameterName = parameterNameRepresentation.getToken().getTokenValue();
PandaScript script = info.getComponent(PandaComponents.PANDA_SCRIPT);
ModuleLoader moduleLoader = script.getModuleLoader();
ClassPrototypeReference type = moduleLoader.forClass(parameterType);
if (type == null) {
throw new PandaParserException("Unknown type '" + parameterType + "'");
}
Parameter parameter = new PandaParameter(type, parameterName);
parameters.add(parameter);
if (i + 2 < tokenRepresentations.length) {
TokenRepresentation separatorRepresentation = tokenRepresentations[i + 2];
Token separator = separatorRepresentation.getToken();
if (separator.getType() != TokenType.SEPARATOR) {
throw new PandaParserException("Unexpected token " + separatorRepresentation);
}
}
}
return parameters;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected LookupResult extractNode(List<LexicalPatternElement> nextElements, TokenDistributor distributor) {
int skip = 0;
for (LexicalPatternElement nextElement : nextElements) {
if (!nextElement.isWildcard()) {
break;
}
skip++;
}
int indexBackup = distributor.getIndex();
for (int i = skip; i < nextElements.size(); i++) {
LexicalPatternElement element = nextElements.get(i);
distributor.setIndex(indexBackup);
LookupResult result = elementLookupExtractor.extractNode(nextElements.subList(0, skip), element, distributor);
result.matchedIndex = i;
if (result.getMergedResults().isMatched()) {
return result;
}
if (element.isOptional()) {
continue;
}
break;
}
return new LookupResult();
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
protected LookupResult extractNode(List<LexicalPatternElement> nextElements, TokenDistributor distributor) {
int skip = 0;
for (LexicalPatternElement nextElement : nextElements) {
if (!nextElement.isWildcard()) {
break;
}
skip++;
}
int indexBackup = distributor.getIndex();
for (int i = skip; i < nextElements.size(); i++) {
LexicalPatternElement element = nextElements.get(i);
distributor.setIndex(indexBackup);
// consider exclusion of wildcards here
LookupResult result = elementLookupExtractor.extractNode(nextElements.subList(0, skip), element, distributor);
result.matchedIndex = i;
if (result.getMergedResults().isMatched()) {
return result;
}
if (element.isOptional()) {
continue;
}
break;
}
return new LookupResult();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void parse(TokenizedSource source, ParserInfo info) {
PandaScript script = info.getComponent(Components.SCRIPT);
TokenReader reader = new PandaTokenReader(source);
Extractor extractor = PATTERN.extractor();
List<TokenizedSource> gaps = extractor.extract(reader);
if (gaps == null) {
throw new PandaParserException("Cannot parse expression::instance");
}
String className = gaps.get(0).asString();
ImportRegistry importRegistry = script.getImportRegistry();
this.returnType = importRegistry.forClass(className);
ArgumentParser argumentParser = new ArgumentParser();
this.arguments = argumentParser.parse(info, gaps.get(1));
this.constructor = ConstructorUtils.matchConstructor(returnType, arguments);
if (constructor == null) {
throw new PandaParserException("Cannot find " + className + " constructor for the specified arguments");
}
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void parse(TokenizedSource source, ParserInfo info) {
PandaScript script = info.getComponent(Components.SCRIPT);
TokenReader reader = new PandaTokenReader(source);
Extractor extractor = PATTERN.extractor();
List<TokenizedSource> gaps = extractor.extract(reader);
if (gaps == null) {
throw new PandaParserException("Cannot parse expression::instance");
}
String className = gaps.get(0).asString();
ImportRegistry importRegistry = script.getImportRegistry();
this.returnType = importRegistry.forClass(className);
if (returnType == null) {
throw new PandaParserException("Unknown return type '" + className + "'");
}
ArgumentParser argumentParser = new ArgumentParser();
this.arguments = argumentParser.parse(info, gaps.get(1));
this.constructor = ConstructorUtils.matchConstructor(returnType, arguments);
if (constructor == null) {
throw new PandaParserException("Cannot find " + className + " constructor for the specified arguments");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void run() {
CommandLine commandLine = new CommandLine(this);
if (usageHelpRequested) {
CommandLine.usage(this, System.out);
return;
}
if (versionInfoRequested) {
commandLine.printVersionHelp(System.out);
return;
}
Application application = cli.getPanda().getPandaLoader().load(script, script.getParentFile());
application.launch();
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void run() {
CommandLine commandLine = new CommandLine(this);
if (usageHelpRequested) {
CommandLine.usage(this, System.out);
return;
}
if (versionInfoRequested) {
commandLine.printVersionHelp(System.out);
return;
}
cli.getPanda().getPandaLoader()
.load(script, script.getParentFile())
.ifPresent(application -> application.launch());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void parse(@Nullable Tokens source, ParserData data) {
PandaScript script = data.getComponent(PandaComponents.PANDA_SCRIPT);
ModuleLoader registry = script.getModuleLoader();
Expression instance = null;
ClassPrototype prototype;
if (instanceSource != null) {
String surmiseClassName = instanceSource.asString();
prototype = registry.forClass(surmiseClassName).get();
if (prototype == null) {
instance = data.getComponent(PandaComponents.EXPRESSION).parse(data, instanceSource);
prototype = instance.getReturnType();
}
}
else {
prototype = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE);
instance = ThisExpressionCallback.asExpression(prototype);
}
ArgumentParser argumentParser = new ArgumentParser();
Expression[] arguments = argumentParser.parse(data, argumentsSource);
ClassPrototype[] parameterTypes = ExpressionUtils.toTypes(arguments);
String methodName = methodNameSource.asString();
PrototypeMethod prototypeMethod = prototype.getMethods().getMethod(methodName, parameterTypes);
if (prototypeMethod == null) {
throw new PandaParserFailure("Class " + prototype.getClassName() + " does not have method " + methodName, data, methodNameSource);
}
if (!voids && prototypeMethod.isVoid()) {
throw new PandaParserFailure("Method " + prototypeMethod.getMethodName() + " returns nothing", data, methodNameSource);
}
this.invoker = new MethodInvoker(prototypeMethod, instance, arguments);
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void parse(@Nullable Tokens source, ParserData data) {
PandaScript script = data.getComponent(PandaComponents.PANDA_SCRIPT);
ModuleLoader registry = script.getModuleLoader();
Expression instance = null;
ClassPrototype prototype;
if (instanceSource != null) {
String surmiseClassName = instanceSource.asString();
ClassPrototypeReference reference = registry.forClass(surmiseClassName);
prototype = reference != null ? reference.get() : null;
if (prototype == null) {
instance = data.getComponent(PandaComponents.EXPRESSION).parse(data, instanceSource);
prototype = instance.getReturnType();
}
}
else {
prototype = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE);
instance = ThisExpressionCallback.asExpression(prototype);
}
ArgumentParser argumentParser = new ArgumentParser();
Expression[] arguments = argumentParser.parse(data, argumentsSource);
ClassPrototype[] parameterTypes = ExpressionUtils.toTypes(arguments);
String methodName = methodNameSource.asString();
PrototypeMethod prototypeMethod = prototype.getMethods().getMethod(methodName, parameterTypes);
if (prototypeMethod == null) {
throw new PandaParserFailure("Class " + prototype.getClassName() + " does not have method " + methodName, data, methodNameSource);
}
if (!voids && prototypeMethod.isVoid()) {
throw new PandaParserFailure("Method " + prototypeMethod.getMethodName() + " returns nothing", data, methodNameSource);
}
this.invoker = new MethodInvoker(prototypeMethod, instance, arguments);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public InterceptorData handle(UnifiedBootstrapParser parser, ParserData data) {
InterceptorData interceptorData = new InterceptorData();
if (pattern != null) {
TokenExtractorResult result = pattern.extract(null);
}
return interceptorData;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public InterceptorData handle(UnifiedBootstrapParser parser, ParserData data) {
InterceptorData interceptorData = new InterceptorData();
if (pattern != null) {
TokenExtractorResult result = pattern.extract(data.getComponent(UniversalComponents.SOURCE_STREAM));
}
return interceptorData;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SafeVarargs
@SuppressWarnings("unchecked")
public static <T> T[] mergeArrays(T[]... arrays) {
int size = 0;
Class<?> type = null;
for (T[] array : arrays) {
size += array.length;
type = array.getClass().getComponentType();
}
T[] mergedArray = (T[]) Array.newInstance(type, size);
int index = 0;
for (T[] array : arrays) {
for (T element : array) {
mergedArray[index++] = element;
}
}
return mergedArray;
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@SafeVarargs
@SuppressWarnings("unchecked")
public static <T> T[] mergeArrays(T[]... arrays) {
if (isEmpty(arrays)) {
throw new IllegalArgumentException("Merge arrays requires at least one array as argument");
}
return mergeArrays(length -> (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), length), arrays);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Autowired
public void parse(ParserData data, LocalData localData) {
if (localData == null || data.getComponent(PandaComponents.CONTAINER) == null) {
System.out.println("xxx");
}
localData.allocateInstance(data.getComponent(PandaComponents.CONTAINER).reserveCell());
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Autowired
public void parse(ParserData data, LocalData localData) {
localData.allocateInstance(data.getComponent(PandaComponents.CONTAINER).reserveCell());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public PrototypeMethod generate(ModuleRegistry registry) {
ClassPrototype returnType = PandaModuleRegistryAssistant.forClass(registry, method.getReturnType());
ClassPrototype[] parametersTypes = PandaClassPrototypeUtils.toTypes(registry, method.getParameterTypes());
boolean isVoid = returnType.getClassName().equals("void");
// TODO: Generate bytecode
MethodCallback<Object> methodBody = (branch, instance, parameters) -> {
try {
int amountOfArgs = parameters.length;
int parameterCount = method.getParameterCount();
Object varargs = null;
if (amountOfArgs != parameterCount) {
if (parameterCount < 1) {
throw new PandaRuntimeException("Too many arguments");
}
Class<?> last = method.getParameterTypes()[parameterCount - 1];
String lastName = last.getName();
Class<?> rootLast = Class.forName(lastName.substring(2, lastName.length() - 1));
if (amountOfArgs + 1 != parameterCount || !last.isArray()) {
throw new PandaRuntimeException("Cannot invoke mapped mapped method (args.length != parameters.length)");
}
varargs = Array.newInstance(rootLast, 0);
++amountOfArgs;
}
Object[] args = new Object[amountOfArgs];
for (int i = 0; i < parameters.length; i++) {
Value parameter = parameters[i];
if (parameter == null) {
continue;
}
args[i] = parameter.getValue();
}
if (varargs != null) {
args[amountOfArgs - 1] = varargs;
}
Object returnValue = method.invoke(instance, args);
if (isVoid) {
return;
}
Value value = new PandaValue(returnType, returnValue);
branch.setReturnValue(value);
} catch (Exception e) {
e.printStackTrace();
}
};
return PandaMethod.builder()
.prototype(prototype)
.visibility(MethodVisibility.PUBLIC)
.isStatic(Modifier.isStatic(method.getModifiers()))
.returnType(returnType)
.methodName(method.getName())
.methodBody(methodBody)
.parameterTypes(parametersTypes)
.build();
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
public PrototypeMethod generate(ModuleRegistry registry) {
ClassPrototype returnType = PandaModuleRegistryAssistant.forClass(registry, method.getReturnType());
ClassPrototype[] parametersTypes = PandaClassPrototypeUtils.toTypes(registry, method.getParameterTypes());
if (returnType == null) {
throw new PandaRuntimeException("Cannot generate method for 'null' return type");
}
boolean isVoid = returnType.getClassName().equals("void");
// TODO: Generate bytecode
MethodCallback<Object> methodBody = (branch, instance, parameters) -> {
try {
int amountOfArgs = parameters.length;
int parameterCount = method.getParameterCount();
Object varargs = null;
if (amountOfArgs != parameterCount) {
if (parameterCount < 1) {
throw new PandaRuntimeException("Too many arguments");
}
Class<?> last = method.getParameterTypes()[parameterCount - 1];
String lastName = last.getName();
Class<?> rootLast = Class.forName(lastName.substring(2, lastName.length() - 1));
if (amountOfArgs + 1 != parameterCount || !last.isArray()) {
throw new PandaRuntimeException("Cannot invoke mapped mapped method (args.length != parameters.length)");
}
varargs = Array.newInstance(rootLast, 0);
amountOfArgs++;
}
Object[] args = new Object[amountOfArgs];
for (int i = 0; i < parameters.length; i++) {
Value parameter = parameters[i];
if (parameter == null) {
continue;
}
args[i] = parameter.getValue();
}
if (varargs != null) {
args[amountOfArgs - 1] = varargs;
}
Object returnValue = method.invoke(instance, args);
if (isVoid) {
return;
}
Value value = new PandaValue(returnType, returnValue);
branch.setReturnValue(value);
} catch (Exception e) {
e.printStackTrace();
}
};
return PandaMethod.builder()
.prototype(prototype)
.visibility(MethodVisibility.PUBLIC)
.isStatic(Modifier.isStatic(method.getModifiers()))
.returnType(returnType)
.methodName(method.getName())
.methodBody(methodBody)
.parameterTypes(parametersTypes)
.build();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
void getURLContent() {
String urlContent = IOUtils.getURLContent("https://panda-lang.org/");
Assertions.assertNotNull(urlContent);
Assertions.assertTrue(urlContent.contains("<html"));
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
void getURLContent() {
Result<String, IOException> result = IOUtils.fetchContent("https://panda-lang.org/");
assertTrue(result.isDefined());
assertNotNull(result.getValue());
assertTrue(result.getValue().contains("<html"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Expression parse(ParserData data, SourceStream source, ExpressionParserSettings settings) {
ExpressionContext context = new ExpressionContext(this, data, source);
ExpressionParserWorker worker = new ExpressionParserWorker(this, context, source, subparsers, settings.isCombined());
for (TokenRepresentation representation : context.getDiffusedSource()) {
if (!worker.next(context.withUpdatedToken(representation))) {
break;
}
}
worker.finish(context);
// if something went wrong
if (worker.hasError()) {
throw new ExpressionParserException(worker.getError().getErrorMessage(), context, worker.getError().getSource());
}
// if context does not contain any results
if (!context.hasResults()) {
throw new ExpressionParserException("Unknown expression", context, source.toSnippet());
}
for (ExpressionResultProcessor processor : new ReversedIterable<>(context.getProcessors())) {
ExpressionResult<Expression> result = processor.process(context, context.getResults());
if (result.containsError()) {
throw new ExpressionParserException("Error occurred while processing the result: ", result.getErrorMessage(), context, context.getSource().toSnippet());
}
context.getResults().push(result.get());
}
// if worker couldn't prepare the final result
if (context.getResults().size() > 1) {
throw new ExpressionParserException("Source contains " + context.getResults().size() + " expressions", context, source.toSnippet());
}
source.read(worker.getLastSucceededRead());
return context.getResults().pop();
}
#location 23
#vulnerability type NULL_DEREFERENCE | #fixed code
public Expression parse(ParserData data, SourceStream source, ExpressionParserSettings settings) {
return parse(data, source, settings, null);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public ClassPrototype generate(Class<?> type) {
Module module = ModuleRegistry.getDefault().getOrCreate(type.getPackage().getName());
ClassPrototype prototype = new ClassPrototype(module, type.getSimpleName());
prototype.getAssociated().add(type);
for (Field field : type.getFields()) {
ClassPrototypeFieldGenerator generator = new ClassPrototypeFieldGenerator(type, prototype, field);
PrototypeField prototypeField = generator.generate();
prototype.getFields().add(prototypeField);
}
for (Constructor<?> constructor : type.getConstructors()) {
ClassPrototypeConstructorGenerator generator = new ClassPrototypeConstructorGenerator(type, prototype, constructor);
PrototypeConstructor prototypeField = generator.generate();
prototype.getConstructors().add(prototypeField);
}
for (Method method : type.getMethods()) {
ClassPrototypeMethodGenerator generator = new ClassPrototypeMethodGenerator(type, prototype, method);
PrototypeMethod prototypeMethod = generator.generate();
prototype.getMethods().registerMethod(prototypeMethod);
}
return prototype;
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
public ClassPrototype generate(Class<?> type) {
Module module = ModuleRegistry.getDefault().getOrCreate(type.getPackage().getName());
ClassPrototype prototype = module.get(type.getSimpleName());
if (prototype != null) {
return prototype;
}
prototype = new ClassPrototype(module, type.getSimpleName());
prototype.getAssociated().add(type);
for (Field field : type.getFields()) {
ClassPrototypeFieldGenerator generator = new ClassPrototypeFieldGenerator(type, prototype, field);
PrototypeField prototypeField = generator.generate();
prototype.getFields().add(prototypeField);
}
for (Constructor<?> constructor : type.getConstructors()) {
ClassPrototypeConstructorGenerator generator = new ClassPrototypeConstructorGenerator(type, prototype, constructor);
PrototypeConstructor prototypeField = generator.generate();
prototype.getConstructors().add(prototypeField);
}
for (Method method : type.getMethods()) {
switch (method.getName()) {
case "finalize":
case "notify":
case "notifyAll":
case "wait":
continue;
}
ClassPrototypeMethodGenerator generator = new ClassPrototypeMethodGenerator(type, prototype, method);
PrototypeMethod prototypeMethod = generator.generate();
prototype.getMethods().registerMethod(prototypeMethod);
}
return prototype;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public PandaMethodBuilder parameterTypes(ModuleLoader moduleLoader, String... parameterTypes) {
ClassPrototype[] prototypes = new ClassPrototype[parameterTypes.length];
for (int i = 0; i < prototypes.length; i++) {
prototypes[i] = moduleLoader.forClass(parameterTypes[i]).get();
}
this.parameterTypes = prototypes;
return this;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public PandaMethodBuilder parameterTypes(ModuleLoader moduleLoader, String... parameterTypes) {
ClassPrototypeReference[] prototypes = new ClassPrototypeReference[parameterTypes.length];
for (int i = 0; i < prototypes.length; i++) {
prototypes[i] = moduleLoader.forClass(parameterTypes[i]);
}
this.parameterTypes = prototypes;
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTokenPattern() {
TokenPattern pattern = TokenPattern.builder()
.compile("(method|hidden|local) [static] <return-type> <name> `(<*parameters>`) `{ <*body> `}[;]")
.build();
LexicalPatternElement content = pattern.getPatternContent();
Assertions.assertNotNull(content);
TokenExtractorResult result = pattern.extract(SOURCE);
Assertions.assertNotNull(result);
if (result.hasErrorMessage()) {
System.out.println("Error message: " + result.getErrorMessage());
}
Assertions.assertTrue(result.isMatched());
Assertions.assertNotNull(result.getWildcards());
Assertions.assertEquals(4, result.getWildcards().size());
Assertions.assertEquals("void", result.getWildcards().get("return-type").asString());
Assertions.assertEquals("test", result.getWildcards().get("name").asString());
Assertions.assertEquals("15,()25", result.getWildcards().get("*parameters").asString());
Assertions.assertEquals("Console.print(test)", result.getWildcards().get("*body").asString());
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testTokenPattern() {
TokenPattern pattern = TokenPattern.builder()
.compile("class <name> [extends <inherited>] `{ <*body> `}")
.build();
LexicalPatternElement content = pattern.getPatternContent();
Assertions.assertNotNull(content);
TokenExtractorResult result = pattern.extract(SOURCE);
Assertions.assertNotNull(result);
if (result.hasErrorMessage()) {
System.out.println("Error message: " + result.getErrorMessage());
}
Assertions.assertTrue(result.isMatched());
Assertions.assertNotNull(result.getWildcards());
System.out.println(result.getWildcards());
Assertions.assertEquals(2, result.getWildcards().size());
Assertions.assertEquals("Foo", result.getWildcards().get("name").asString());
Assertions.assertEquals("methodanotherEcho(Stringmessage){Console.print(message);}", result.getWildcards().get("*body").asString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void prepare() {
AbyssExtractorOpposites opposites = new AbyssExtractorOpposites();
for (int i = 0; i < tokenizedSource.size(); i++) {
TokenRepresentation representation = tokenizedSource.get(i);
Token token = representation.getToken();
boolean levelUp = opposites.report(token);
int nestingLevel = levelUp ? opposites.getNestingLevel() - 1 : opposites.getNestingLevel();
AbyssTokenRepresentation abyssRepresentation = new AbyssTokenRepresentation(representation, nestingLevel);
abyssRepresentations[i] = abyssRepresentation;
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
private void prepare() {
AbyssExtractorOpposites opposites = new AbyssExtractorOpposites();
for (int i = 0; i < tokenizedSource.size(); i++) {
TokenRepresentation representation = tokenizedSource.get(i);
if (representation == null) {
throw new PandaRuntimeException("Representation is null");
}
Token token = representation.getToken();
boolean levelUp = opposites.report(token);
int nestingLevel = levelUp ? opposites.getNestingLevel() - 1 : opposites.getNestingLevel();
AbyssTokenRepresentation abyssRepresentation = new AbyssTokenRepresentation(representation, nestingLevel);
abyssRepresentations[i] = abyssRepresentation;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static ArrayClassPrototype obtain(ModuleLoader loader, String type) {
ClassPrototype prototype = loader.forClass(type.replace(PandaArray.IDENTIFIER, StringUtils.EMPTY));
if (prototype == null) {
return null;
}
int dimensions = StringUtils.countOccurrences(type, PandaArray.IDENTIFIER);
Class<?> arrayType = ArrayUtils.getDimensionalArrayType(prototype.getAssociated(), dimensions);
Class<?> arrayClass = ArrayUtils.getArrayClass(arrayType);
ArrayClassPrototype arrayPrototype = new ArrayClassPrototype(arrayClass, arrayType);
loader.get(null).add(arrayPrototype);
arrayPrototype.getMethods().registerMethod(PandaMethod.builder()
.methodName("toString")
.returnType(PrimitivePrototypeLiquid.OBJECT)
.methodBody((branch, instance, parameters) -> {
if (!instance.getClass().isArray()) {
throw new RuntimeException();
}
branch.returnValue(new PandaValue(PrimitivePrototypeLiquid.OBJECT, Arrays.toString((Object[]) instance)));
})
.build());
return arrayPrototype;
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
public static ArrayClassPrototype obtain(ModuleLoader loader, String type) {
ArrayClassPrototype cached = ARRAY_PROTOTYPES.get(type);
if (cached != null) {
return cached;
}
ClassPrototype prototype = loader.forClass(type.replace(PandaArray.IDENTIFIER, StringUtils.EMPTY));
if (prototype == null) {
return null;
}
int dimensions = StringUtils.countOccurrences(type, PandaArray.IDENTIFIER);
Class<?> arrayType = ArrayUtils.getDimensionalArrayType(prototype.getAssociated(), dimensions);
Class<?> arrayClass = ArrayUtils.getArrayClass(arrayType);
ArrayClassPrototype arrayPrototype = new ArrayClassPrototype(loader.get(null), arrayClass, arrayType);
loader.get(null).add(arrayPrototype);
arrayPrototype.getMethods().registerMethod(PandaMethod.builder()
.methodName("toString")
.returnType(PrimitivePrototypeLiquid.OBJECT)
.methodBody((branch, instance, parameters) -> {
if (!instance.getClass().isArray()) {
throw new RuntimeException();
}
branch.setReturnValue(new PandaValue(PrimitivePrototypeLiquid.OBJECT, Arrays.toString((Object[]) instance)));
})
.build());
ARRAY_PROTOTYPES.put(type, arrayPrototype);
return arrayPrototype;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void parse(Tokens source, ParserData data) {
PandaScript script = data.getComponent(PandaComponents.PANDA_SCRIPT);
TokenReader reader = new PandaTokenReader(source);
GappedPatternExtractor extractor = PATTERN.extractor();
List<Tokens> gaps = extractor.extract(reader);
if (gaps == null) {
throw new PandaParserException("Cannot parse expression::instance");
}
String className = gaps.get(0).asString();
ModuleLoader moduleLoader = script.getModuleLoader();
this.returnType = moduleLoader.forClass(className).fetch();
if (returnType == null) {
throw PandaParserFailure.builder()
.message("Unknown return type '" + className + "'")
.data(data)
.source(source)
.build();
}
ArgumentParser argumentParser = new ArgumentParser();
this.arguments = argumentParser.parse(data, gaps.get(1));
this.constructor = ConstructorUtils.matchConstructor(returnType, arguments);
if (constructor == null) {
throw new PandaParserFailure("Cannot find constructor of " + returnType.getClassName() + " for the specified arguments " + Arrays.toString(this.arguments), data);
}
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void parse(Tokens source, ParserData data) {
PandaScript script = data.getComponent(PandaComponents.PANDA_SCRIPT);
TokenReader reader = new PandaTokenReader(source);
GappedPatternExtractor extractor = PATTERN.extractor();
List<Tokens> gaps = extractor.extract(reader);
if (gaps == null) {
throw new PandaParserException("Cannot parse expression::instance");
}
String className = gaps.get(0).asString();
ModuleLoader moduleLoader = script.getModuleLoader();
Optional<ClassPrototypeReference> reference = moduleLoader.forClass(className);
if (!reference.isPresent()) {
throw new PandaParserFailure("Unknown return type", data, source);
}
this.returnType = reference.get();
this.arguments = new ArgumentParser().parse(data, gaps.get(1));
this.constructor = ConstructorUtils.matchConstructor(returnType.fetch(), arguments);
if (constructor == null) {
throw new PandaParserFailure("Cannot find constructor of " + returnType.getClassName() + " for the specified arguments " + Arrays.toString(this.arguments), data);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public NamedExecutable parse(Atom atom) {
final String source = atom.getSourceCode();
final StringBuilder groupBuilder = new StringBuilder();
boolean nsFlag = false;
for (char c : source.toCharArray()) {
if (Character.isWhitespace(c)) {
nsFlag = true;
} else if (c == ';') {
break;
} else if (nsFlag) {
groupBuilder.append(c);
}
}
String groupName = groupBuilder.toString();
Group group = GroupCenter.getGroup(groupName);
atom.getPandaParser().getPandaBlock().setGroup(group);
return group;
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public NamedExecutable parse(Atom atom) {
final String source = atom.getSourcesDivider().getLine();
final StringBuilder groupBuilder = new StringBuilder();
boolean nsFlag = false;
for (char c : source.toCharArray()) {
if (Character.isWhitespace(c)) {
nsFlag = true;
} else if (c == ';') {
break;
} else if (nsFlag) {
groupBuilder.append(c);
}
}
String groupName = groupBuilder.toString();
Group group = GroupCenter.getGroup(groupName);
atom.getPandaParser().getPandaBlock().setGroup(group);
return group;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Type getArrayOf(Module module, Referencable baseReferencable, int dimensions) {
Reference baseReference = baseReferencable.toReference();
Class<?> componentType = ArrayUtils.getDimensionalArrayType(baseReference.getAssociatedClass().fetchImplementation(), dimensions);
Class<?> arrayType = ArrayUtils.getArrayClass(componentType);
Reference componentReference;
if (componentType.isArray()) {
componentReference = fetch(module, componentType).getOrElseThrow((Supplier<PandaFrameworkException>) () -> {
throw new PandaFrameworkException("Cannot fetch array class for array type " + componentType);
});
}
else {
componentReference = module.forClass(componentType).getOrElseThrow((Supplier<PandaFrameworkException>) () -> {
throw new PandaFrameworkException("Cannot fetch array class for " + componentType);
});
}
ArrayType arrayPrototype = new ArrayType(module, arrayType, componentReference.fetch());
ARRAY_PROTOTYPES.put(baseReference.getName() + dimensions, arrayPrototype);
ModuleLoader loader = module.getModuleLoader();
arrayPrototype.getMethods().declare("size", () -> ArrayClassTypeConstants.SIZE.apply(loader));
arrayPrototype.getMethods().declare("toString", () -> ArrayClassTypeConstants.TO_STRING.apply(loader));
module.add(arrayPrototype);
return arrayPrototype;
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
public static Type getArrayOf(Module module, Referencable baseReferencable, int dimensions) {
Reference baseReference = baseReferencable.toReference();
Class<?> componentType = ArrayUtils.getDimensionalArrayType(baseReference.getAssociatedClass().fetchImplementation(), dimensions);
Class<?> arrayType = ArrayUtils.getArrayClass(componentType);
Reference componentReference;
if (componentType.isArray()) {
componentReference = fetch(module, componentType).getOrElseThrow((Supplier<PandaFrameworkException>) () -> {
throw new PandaFrameworkException("Cannot fetch array class for array type " + componentType);
});
}
else {
componentReference = module.forClass(componentType).getOrElseThrow((Supplier<PandaFrameworkException>) () -> {
throw new PandaFrameworkException("Cannot fetch array class for " + componentType);
});
}
ArrayType arraType = new ArrayType(module, arrayType, componentReference.fetch());
ARRAY_PROTOTYPES.put(baseReference.getName() + dimensions, arraType);
ModuleLoader loader = module.getModuleLoader();
arraType.getMethods().declare("size", () -> ArrayClassTypeConstants.SIZE.apply(loader));
arraType.getMethods().declare("toString", () -> ArrayClassTypeConstants.TO_STRING.apply(loader));
module.add(arraType);
return arraType;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void assumeDocker() throws Exception {
Launcher.LocalLauncher localLauncher = new Launcher.LocalLauncher(StreamTaskListener.NULL);
try {
Assume.assumeThat("Docker working", localLauncher.launch().cmds(DockerTool.getExecutable(null, null, null, null), "ps").start().joinWithTimeout(DockerClient.CLIENT_TIMEOUT, TimeUnit.SECONDS, localLauncher.getListener()), is(0));
} catch (IOException x) {
Assume.assumeNoException("have Docker installed", x);
}
DockerClient dockerClient = new DockerClient(localLauncher, null, null);
Assume.assumeFalse("Docker version not < 1.3", dockerClient.version().isOlderThan(new VersionNumber("1.3")));
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void assumeDocker() throws Exception {
assumeDocker(new VersionNumber(DEFAULT_MINIMUM_VERSION));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void extractConfigurationParameters() {
super.extractConfigurationParameters();
// Load configuration parameters.
configColor = ChatColor.getByChar(mainConfig.getString("Color", "5"));
configIcon = StringEscapeUtils.unescapeJava(mainConfig.getString("Icon", "\u2618"));
configAdditionalEffects = mainConfig.getBoolean("AdditionalEffects", true);
configSound = mainConfig.getBoolean("Sound", true);
configSoundStats = mainConfig.getString("SoundStats", "ENTITY_FIREWORK_ROCKET_BLAST").toUpperCase();
langNumberAchievements = pluginHeader + LangHelper.get(CmdLang.NUMBER_ACHIEVEMENTS, langConfig) + " " + configColor;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void extractConfigurationParameters() {
super.extractConfigurationParameters();
// Load configuration parameters.
configColor = ChatColor.getByChar(mainConfig.getString("Color", "5"));
configIcon = mainConfig.getString("Icon", "\u2618");
configAdditionalEffects = mainConfig.getBoolean("AdditionalEffects", true);
configSound = mainConfig.getBoolean("Sound", true);
configSoundStats = mainConfig.getString("SoundStats", "ENTITY_FIREWORK_ROCKET_BLAST").toUpperCase();
langNumberAchievements = pluginHeader + LangHelper.get(CmdLang.NUMBER_ACHIEVEMENTS, langConfig) + " " + configColor;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void saveConfig(String configString, File file) throws IOException {
String configuration = this.prepareConfigString(configString);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
writer.write(configuration);
writer.flush();
writer.close();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
public void saveConfig(String configString, File file) throws IOException {
String configuration = this.prepareConfigString(configString);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
writer.write(configuration);
writer.flush();
} catch (IOException e) {
throw e;
} finally {
if (writer != null)
writer.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private boolean isButtonClicked(InventoryClickEvent event, ItemStack button) {
if (event.getCurrentItem().isSimilar(button)) {
// Clicked item seems to be the button. But player could have clicked on item in his personal inventory that
// matches the properties of the button used by Advanced Achievements. The first item matching the
// properties of the button is the real one, check that this is indeed the clicked one.
Map<Integer, ItemStack> backButtonCandidates = new TreeMap<>(
event.getInventory().all(event.getCurrentItem().getType()));
for (Entry<Integer, ItemStack> entry : backButtonCandidates.entrySet()) {
if (event.getCurrentItem().isSimilar(entry.getValue())) {
// Found real button. Did the player click on it?
if (entry.getKey() == event.getRawSlot()) {
return true;
}
break;
}
}
}
return false;
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
private boolean isButtonClicked(InventoryClickEvent event, ItemStack button) {
if (event.getCurrentItem() != null && event.getCurrentItem().isSimilar(button)) {
// Clicked item seems to be the button. But player could have clicked on item in his personal inventory that
// matches the properties of the button used by Advanced Achievements. The first item matching the
// properties of the button is the real one, check that this is indeed the clicked one.
Map<Integer, ItemStack> backButtonCandidates = new TreeMap<>(
event.getInventory().all(event.getCurrentItem().getType()));
for (Entry<Integer, ItemStack> entry : backButtonCandidates.entrySet()) {
if (event.getCurrentItem().isSimilar(entry.getValue())) {
// Found real button. Did the player click on it?
if (entry.getKey() == event.getRawSlot()) {
return true;
}
break;
}
}
}
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Reader getConfigContent(File file) throws IOException {
if (!file.exists())
return null;
int commentNum = 0;
String addLine;
String currentLine;
StringBuilder whole = new StringBuilder("");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((currentLine = reader.readLine()) != null) {
// Rework comment line so it becomes a normal value in the config file.
// This workaround allows the comment to be saved in the Yaml file.
if (currentLine.startsWith("#")) {
addLine = currentLine.replace(":", "_COLON_").replace("|", "_VERT_").replace("-", "_HYPHEN_")
.replaceFirst("#", plugin.getDescription().getName() + "_COMMENT_" + commentNum + ": ");
whole.append(addLine + "\n");
commentNum++;
} else {
whole.append(currentLine + "\n");
}
}
String config = whole.toString();
StringReader configStream = new StringReader(config);
reader.close();
return configStream;
}
#location 30
#vulnerability type RESOURCE_LEAK | #fixed code
public Reader getConfigContent(File file) throws IOException {
if (!file.exists())
return null;
int commentNum = 0;
String addLine;
String currentLine;
StringBuilder whole = new StringBuilder("");
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((currentLine = reader.readLine()) != null) {
// Rework comment line so it becomes a normal value in the config file.
// This workaround allows the comment to be saved in the Yaml file.
if (currentLine.startsWith("#")) {
addLine = currentLine.replace(":", "_COLON_").replace("|", "_VERT_").replace("-", "_HYPHEN_")
.replaceFirst("#", plugin.getDescription().getName() + "_COMMENT_" + commentNum + ": ");
whole.append(addLine + "\n");
commentNum++;
} else {
whole.append(currentLine + "\n");
}
}
String config = whole.toString();
StringReader configStream = new StringReader(config);
return configStream;
} catch (IOException e) {
throw e;
} finally {
if (reader != null)
reader.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
if (event.getInventory().getType() != InventoryType.BREWING || event.getAction() == InventoryAction.NOTHING
|| event.getClick() == ClickType.NUMBER_KEY && event.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD
|| !isBrewablePotion(event)) {
return;
}
Player player = (Player) event.getWhoClicked();
int eventAmount = event.getCurrentItem().getAmount();
if (event.isShiftClick()) {
eventAmount = Math.min(eventAmount, inventoryHelper.getAvailableSpace(player, event.getCurrentItem()));
if (eventAmount == 0) {
return;
}
}
updateStatisticAndAwardAchievementsIfAvailable(player, eventAmount, event.getRawSlot());
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
ItemStack item = event.getCurrentItem();
if (event.getInventory().getType() != InventoryType.BREWING || event.getAction() == InventoryAction.NOTHING
|| event.getClick() == ClickType.NUMBER_KEY && event.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD
|| !isBrewablePotion(item)) {
return;
}
Player player = (Player) event.getWhoClicked();
int eventAmount = item.getAmount();
if (event.isShiftClick()) {
eventAmount = Math.min(eventAmount, inventoryHelper.getAvailableSpace(player, item));
if (eventAmount == 0) {
return;
}
}
updateStatisticAndAwardAchievementsIfAvailable(player, eventAmount, event.getRawSlot());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void copyResource(InputStream resource, File file) throws IOException {
OutputStream out = new FileOutputStream(file);
int length;
byte[] buf = new byte[1024];
while ((length = resource.read(buf)) > 0)
out.write(buf, 0, length);
out.close();
resource.close();
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
private void copyResource(InputStream resource, File file) throws IOException {
OutputStream out = null;
try {
out = new FileOutputStream(file);
int length;
byte[] buf = new byte[1024];
while ((length = resource.read(buf)) > 0)
out.write(buf, 0, length);
} catch (IOException e) {
throw e;
} finally {
if (out != null)
out.close();
resource.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<String> getRewardListing(String path, Player player) {
List<String> rewardTypes = new ArrayList<>();
Set<String> keyNames = mainConfig.getKeys(true);
if (economy != null && keyNames.contains(path + ".Money")) {
int amount = getRewardAmount(path, "Money");
rewardTypes.add(StringUtils.replaceOnce(langListRewardMoney, "AMOUNT", amount + " " + getCurrencyName(amount)));
}
if (keyNames.contains(path + ".Item")) {
ItemStack itemReward = getItemReward(path, player);
ItemMeta itemMeta = itemReward.getItemMeta();
String name = itemMeta.hasDisplayName() ? itemMeta.getDisplayName() : getItemName(itemReward);
rewardTypes.add(StringUtils.replaceEach(langListRewardItem, new String[] { "AMOUNT", "ITEM" },
new String[] { Integer.toString(itemReward.getAmount()), name }));
}
if (keyNames.contains(path + ".Experience")) {
int amount = getRewardAmount(path, "Experience");
rewardTypes.add(StringUtils.replaceOnce(langListRewardExperience, "AMOUNT", Integer.toString(amount)));
}
if (keyNames.contains(path + ".IncreaseMaxHealth")) {
int amount = getRewardAmount(path, "IncreaseMaxHealth");
rewardTypes.add(StringUtils.replaceOnce(langListRewardIncreaseMaxHealth, "AMOUNT", Integer.toString(amount)));
}
if (keyNames.contains(path + ".IncreaseMaxOxygen")) {
int amount = getRewardAmount(path, "IncreaseMaxOxygen");
rewardTypes.add(StringUtils.replaceOnce(langListRewardIncreaseMaxOxygen, "AMOUNT", Integer.toString(amount)));
}
if (keyNames.contains(path + ".Command")) {
List<String> messages = getCustomCommandMessages(path);
if (messages.isEmpty()) {
rewardTypes.add(langListRewardCommand);
} else {
rewardTypes.addAll(messages);
}
}
return rewardTypes;
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
public List<String> getRewardListing(String path, Player player) {
List<String> rewardTypes = new ArrayList<>();
Set<String> keyNames = mainConfig.getKeys(true);
if (economy != null && keyNames.contains(path + ".Money")) {
int amount = getRewardAmount(path, "Money");
rewardTypes.add(StringUtils.replaceOnce(langListRewardMoney, "AMOUNT", amount + " " + getCurrencyName(amount)));
}
if (keyNames.contains(path + ".Item")) {
ItemStack[] items = getItemRewards(path, player);
for (ItemStack item : items) {
ItemMeta itemMeta = item.getItemMeta();
String name = itemMeta.hasDisplayName() ? itemMeta.getDisplayName() : getItemName(item);
rewardTypes.add(StringUtils.replaceEach(langListRewardItem, new String[] { "AMOUNT", "ITEM" },
new String[] { Integer.toString(item.getAmount()), name }));
}
}
if (keyNames.contains(path + ".Experience")) {
int amount = getRewardAmount(path, "Experience");
rewardTypes.add(StringUtils.replaceOnce(langListRewardExperience, "AMOUNT", Integer.toString(amount)));
}
if (keyNames.contains(path + ".IncreaseMaxHealth")) {
int amount = getRewardAmount(path, "IncreaseMaxHealth");
rewardTypes.add(StringUtils.replaceOnce(langListRewardIncreaseMaxHealth, "AMOUNT", Integer.toString(amount)));
}
if (keyNames.contains(path + ".IncreaseMaxOxygen")) {
int amount = getRewardAmount(path, "IncreaseMaxOxygen");
rewardTypes.add(StringUtils.replaceOnce(langListRewardIncreaseMaxOxygen, "AMOUNT", Integer.toString(amount)));
}
if (keyNames.contains(path + ".Command")) {
List<String> messages = getCustomCommandMessages(path);
if (messages.isEmpty()) {
rewardTypes.add(langListRewardCommand);
} else {
rewardTypes.addAll(messages);
}
}
return rewardTypes;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void parseDisabledCategories() throws PluginLoadError {
extractDisabledCategoriesFromConfig();
// Need PetMaster with a minimum version of 1.4 for PetMasterGive and PetMasterReceive categories.
if ((!disabledCategories.contains(NormalAchievements.PETMASTERGIVE)
|| !disabledCategories.contains(NormalAchievements.PETMASTERRECEIVE))
&& (!Bukkit.getPluginManager().isPluginEnabled("PetMaster") || Integer.parseInt(Character.toString(
Bukkit.getPluginManager().getPlugin("PetMaster").getDescription().getVersion().charAt(2))) < 4)) {
disabledCategories.add(NormalAchievements.PETMASTERGIVE);
disabledCategories.add(NormalAchievements.PETMASTERRECEIVE);
logger.warning("Overriding configuration: disabling PetMasterGive and PetMasterReceive categories.");
logger.warning(
"Ensure you have placed Pet Master with a minimum version of 1.4 in your plugins folder or add PetMasterGive and PetMasterReceive to the DisabledCategories list in config.yml.");
}
// Elytras introduced in Minecraft 1.9.
if (!disabledCategories.contains(NormalAchievements.DISTANCEGLIDING) && serverVersion < 9) {
disabledCategories.add(NormalAchievements.DISTANCEGLIDING);
logger.warning("Overriding configuration: disabling DistanceGliding category.");
logger.warning(
"Elytra are not available in your Minecraft version, please add DistanceGliding to the DisabledCategories list in config.yml.");
}
// Llamas introduced in Minecraft 1.11.
if (!disabledCategories.contains(NormalAchievements.DISTANCELLAMA) && serverVersion < 11) {
disabledCategories.add(NormalAchievements.DISTANCELLAMA);
logger.warning("Overriding configuration: disabling DistanceLlama category.");
logger.warning(
"Llamas not available in your Minecraft version, please add DistanceLlama to the DisabledCategories list in config.yml.");
}
// Breeding event introduced in Bukkit 1.10.2.
if (!disabledCategories.contains(MultipleAchievements.BREEDING) && serverVersion < 10) {
disabledCategories.add(MultipleAchievements.BREEDING);
logger.warning("Overriding configuration: disabling Breeding category.");
logger.warning(
"The breeding event is not available in your server version, please add Breeding to the DisabledCategories list in config.yml.");
}
// Proper ProjectileHitEvent introduced in Bukkit 1.11.
if (!disabledCategories.contains(MultipleAchievements.TARGETSSHOT) && serverVersion < 11) {
disabledCategories.add(MultipleAchievements.TARGETSSHOT);
logger.warning("Overriding configuration: disabling TargetsShot category.");
logger.warning(
"The projectile hit event is not fully available in your server version, please add TargetsShot to the DisabledCategories list in config.yml.");
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
private void parseDisabledCategories() throws PluginLoadError {
extractDisabledCategoriesFromConfig();
// Need PetMaster with a minimum version of 1.4 for PetMasterGive and PetMasterReceive categories.
if ((!disabledCategories.contains(NormalAchievements.PETMASTERGIVE)
|| !disabledCategories.contains(NormalAchievements.PETMASTERRECEIVE))
&& (!Bukkit.getPluginManager().isPluginEnabled("PetMaster") || getPetMasterMinorVersion() < 4)) {
disabledCategories.add(NormalAchievements.PETMASTERGIVE);
disabledCategories.add(NormalAchievements.PETMASTERRECEIVE);
logger.warning("Overriding configuration: disabling PetMasterGive and PetMasterReceive categories.");
logger.warning(
"Ensure you have placed Pet Master with a minimum version of 1.4 in your plugins folder or add PetMasterGive and PetMasterReceive to the DisabledCategories list in config.yml.");
}
// Elytras introduced in Minecraft 1.9.
if (!disabledCategories.contains(NormalAchievements.DISTANCEGLIDING) && serverVersion < 9) {
disabledCategories.add(NormalAchievements.DISTANCEGLIDING);
logger.warning("Overriding configuration: disabling DistanceGliding category.");
logger.warning(
"Elytra are not available in your Minecraft version, please add DistanceGliding to the DisabledCategories list in config.yml.");
}
// Llamas introduced in Minecraft 1.11.
if (!disabledCategories.contains(NormalAchievements.DISTANCELLAMA) && serverVersion < 11) {
disabledCategories.add(NormalAchievements.DISTANCELLAMA);
logger.warning("Overriding configuration: disabling DistanceLlama category.");
logger.warning(
"Llamas not available in your Minecraft version, please add DistanceLlama to the DisabledCategories list in config.yml.");
}
// Breeding event introduced in Bukkit 1.10.2.
if (!disabledCategories.contains(MultipleAchievements.BREEDING) && serverVersion < 10) {
disabledCategories.add(MultipleAchievements.BREEDING);
logger.warning("Overriding configuration: disabling Breeding category.");
logger.warning(
"The breeding event is not available in your server version, please add Breeding to the DisabledCategories list in config.yml.");
}
// Proper ProjectileHitEvent introduced in Bukkit 1.11.
if (!disabledCategories.contains(MultipleAchievements.TARGETSSHOT) && serverVersion < 11) {
disabledCategories.add(MultipleAchievements.TARGETSSHOT);
logger.warning("Overriding configuration: disabling TargetsShot category.");
logger.warning(
"The projectile hit event is not fully available in your server version, please add TargetsShot to the DisabledCategories list in config.yml.");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void extractConfigurationParameters() {
configHideNotReceivedCategories = mainConfig.getBoolean("HideNotReceivedCategories");
configHideNoPermissionCategories = mainConfig.getBoolean("HideNoPermissionCategories");
langListGUITitle = ChatColor.translateAlternateColorCodes('&', LangHelper.get(GuiLang.GUI_TITLE, langConfig));
ItemMeta itemMeta = lockedItem.getItemMeta();
String displayName = "&8" + LangHelper.get(GuiLang.CATEGORY_NOT_UNLOCKED, langConfig);
itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', displayName));
lockedItem.setItemMeta(itemMeta);
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void extractConfigurationParameters() {
configHideNotReceivedCategories = mainConfig.getBoolean("HideNotReceivedCategories");
configHideNoPermissionCategories = mainConfig.getBoolean("HideNoPermissionCategories");
langListGUITitle = ChatColor.translateAlternateColorCodes('&', LangHelper.get(GuiLang.GUI_TITLE, langConfig));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
Inventory inventory = event.getInventory();
if (!(inventory.getHolder() instanceof AchievementInventoryHolder) || event.getRawSlot() < 0) {
return;
}
// Prevent players from taking items out of the GUI.
event.setCancelled(true);
int currentPage = ((AchievementInventoryHolder) inventory.getHolder()).getPageIndex();
Player player = (Player) event.getWhoClicked();
if (currentPage == MAIN_GUI_PAGE) {
// Main GUI, check whether player can interact with the selected item.
if (event.getCurrentItem().getType() != lockedMaterial && event.getRawSlot() < getMainGUIItemCount()) {
categoryGUI.displayCategoryGUI(event.getCurrentItem(), player, 0);
}
return;
}
ItemStack categoryItem = inventory.getItem(0);
// Check whether a navigation button was clicked in a category GUI.
if (isButtonClicked(event, guiItems.getBackButton())) {
mainGUI.displayMainGUI(player);
} else if (isButtonClicked(event, guiItems.getPreviousButton())) {
categoryGUI.displayCategoryGUI(categoryItem, player, currentPage - 1);
} else if (isButtonClicked(event, guiItems.getNextButton())) {
categoryGUI.displayCategoryGUI(categoryItem, player, currentPage + 1);
}
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
Inventory inventory = event.getInventory();
if (!(inventory.getHolder() instanceof AchievementInventoryHolder) || event.getRawSlot() < 0) {
return;
}
// Prevent players from taking items out of the GUI.
event.setCancelled(true);
// Clicking empty slots should do nothing
if (event.getCurrentItem() == null) {
return;
}
int currentPage = ((AchievementInventoryHolder) inventory.getHolder()).getPageIndex();
Player player = (Player) event.getWhoClicked();
if (currentPage == MAIN_GUI_PAGE) {
// Main GUI, check whether player can interact with the selected item.
if (event.getCurrentItem().getType() != lockedMaterial && event.getRawSlot() < getMainGUIItemCount()) {
categoryGUI.displayCategoryGUI(event.getCurrentItem(), player, 0);
}
return;
}
ItemStack categoryItem = inventory.getItem(0);
// Check whether a navigation button was clicked in a category GUI.
if (isButtonClicked(event, guiItems.getBackButton())) {
mainGUI.displayMainGUI(player);
} else if (isButtonClicked(event, guiItems.getPreviousButton())) {
categoryGUI.displayCategoryGUI(categoryItem, player, currentPage - 1);
} else if (isButtonClicked(event, guiItems.getNextButton())) {
categoryGUI.displayCategoryGUI(categoryItem, player, currentPage + 1);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String rewardItem(Player player, ItemStack item) {
if (player.getInventory().firstEmpty() != -1) {
player.getInventory().addItem(item);
} else {
player.getWorld().dropItem(player.getLocation(), item);
}
String name = item.getItemMeta().getDisplayName();
if (name == null || name.isEmpty()) {
name = rewardParser.getItemName(item);
}
return langItemRewardReceived + name;
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
private String rewardItem(Player player, ItemStack item) {
if (player.getInventory().firstEmpty() != -1) {
player.getInventory().addItem(item);
} else {
player.getWorld().dropItem(player.getLocation(), item);
}
ItemMeta itemMeta = item.getItemMeta();
String name = itemMeta.hasDisplayName() ? itemMeta.getDisplayName() : rewardParser.getItemName(item);
return StringUtils.replaceEach(langItemRewardReceived, new String[] { "AMOUNT", "ITEM" },
new String[] { Integer.toString(item.getAmount()), name });
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private int getCommentsAmount(File file) throws IOException {
if (!file.exists())
return 0;
int comments = 0;
String currentLine;
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((currentLine = reader.readLine()) != null)
if (currentLine.startsWith("#"))
comments++;
reader.close();
return comments;
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
private int getCommentsAmount(File file) throws IOException {
if (!file.exists())
return 0;
int comments = 0;
String currentLine;
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
while ((currentLine = reader.readLine()) != null)
if (currentLine.startsWith("#"))
comments++;
return comments;
} catch (IOException e) {
throw e;
} finally {
if (reader != null)
reader.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.