text
stringlengths 478
483k
|
---|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*chroma_image,
*image,
*resize_image;
InterlaceType
interlace;
MagickBooleanType
status;
register const PixelPacket
*chroma_pixels;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
ssize_t
count,
horizontal_factor,
vertical_factor,
y;
size_t
length,
quantum;
unsigned char
*scanline;
/*
Allocate image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
quantum=(size_t) (image->depth <= 8 ? 1 : 2);
interlace=image_info->interlace;
horizontal_factor=2;
vertical_factor=2;
if (image_info->sampling_factor != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(image_info->sampling_factor,&geometry_info);
horizontal_factor=(ssize_t) geometry_info.rho;
vertical_factor=(ssize_t) geometry_info.sigma;
if ((flags & SigmaValue) == 0)
vertical_factor=horizontal_factor;
if ((horizontal_factor != 1) && (horizontal_factor != 2) &&
(vertical_factor != 1) && (vertical_factor != 2))
ThrowReaderException(CorruptImageError,"UnexpectedSamplingFactor");
}
if ((interlace == UndefinedInterlace) ||
((interlace == NoInterlace) && (vertical_factor == 2)))
{
interlace=NoInterlace; /* CCIR 4:2:2 */
if (vertical_factor == 2)
interlace=PlaneInterlace; /* CCIR 4:1:1 */
}
if (interlace != PartitionInterlace)
{
/*
Open image file.
*/
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
/*
Allocate memory for a scanline.
*/
if (interlace == NoInterlace)
scanline=(unsigned char *) AcquireQuantumMemory((size_t) 2UL*
image->columns+2UL,quantum*sizeof(*scanline));
else
scanline=(unsigned char *) AcquireQuantumMemory(image->columns,
quantum*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=MagickTrue;
do
{
chroma_image=CloneImage(image,(image->columns+horizontal_factor-1)/
horizontal_factor,(image->rows+vertical_factor-1)/vertical_factor,
MagickTrue,exception);
if (chroma_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert raster image to pixel packets.
*/
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
break;
if (interlace == PartitionInterlace)
{
AppendImageFormat("Y",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*chroma_pixels;
if (interlace == NoInterlace)
{
if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL))
{
length=2*quantum*image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
}
p=scanline;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
chroma_pixels=QueueAuthenticPixels(chroma_image,0,y,
chroma_image->columns,1,exception);
if (chroma_pixels == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=2)
{
SetPixelRed(chroma_pixels,0);
if (quantum == 1)
SetPixelGreen(chroma_pixels,ScaleCharToQuantum(*p++));
else
{
SetPixelGreen(chroma_pixels,ScaleShortToQuantum(((*p) << 8) |
*(p+1)));
p+=2;
}
if (quantum == 1)
SetPixelRed(q,ScaleCharToQuantum(*p++));
else
{
SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1)));
p+=2;
}
SetPixelGreen(q,0);
SetPixelBlue(q,0);
q++;
SetPixelGreen(q,0);
SetPixelBlue(q,0);
if (quantum == 1)
SetPixelBlue(chroma_pixels,ScaleCharToQuantum(*p++));
else
{
SetPixelBlue(chroma_pixels,ScaleShortToQuantum(((*p) << 8) |
*(p+1)));
p+=2;
}
if (quantum == 1)
SetPixelRed(q,ScaleCharToQuantum(*p++));
else
{
SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1)));
p+=2;
}
chroma_pixels++;
q++;
}
}
else
{
if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL))
{
length=quantum*image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
}
p=scanline;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (quantum == 1)
SetPixelRed(q,ScaleCharToQuantum(*p++));
else
{
SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1)));
p+=2;
}
SetPixelGreen(q,0);
SetPixelBlue(q,0);
q++;
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (interlace == NoInterlace)
if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (interlace == PartitionInterlace)
{
(void) CloseBlob(image);
AppendImageFormat("U",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if (interlace != NoInterlace)
{
for (y=0; y < (ssize_t) chroma_image->rows; y++)
{
length=quantum*chroma_image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
p=scanline;
q=QueueAuthenticPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) chroma_image->columns; x++)
{
SetPixelRed(q,0);
if (quantum == 1)
SetPixelGreen(q,ScaleCharToQuantum(*p++));
else
{
SetPixelGreen(q,ScaleShortToQuantum(((*p) << 8) | *(p+1)));
p+=2;
}
SetPixelBlue(q,0);
q++;
}
if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)
break;
}
if (interlace == PartitionInterlace)
{
(void) CloseBlob(image);
AppendImageFormat("V",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
}
for (y=0; y < (ssize_t) chroma_image->rows; y++)
{
length=quantum*chroma_image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
p=scanline;
q=GetAuthenticPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) chroma_image->columns; x++)
{
if (quantum == 1)
SetPixelBlue(q,ScaleCharToQuantum(*p++));
else
{
SetPixelBlue(q,ScaleShortToQuantum(((*p) << 8) | *(p+1)));
p+=2;
}
q++;
}
if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)
break;
}
}
/*
Scale image.
*/
resize_image=ResizeImage(chroma_image,image->columns,image->rows,
TriangleFilter,1.0,exception);
chroma_image=DestroyImage(chroma_image);
if (resize_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
chroma_pixels=GetVirtualPixels(resize_image,0,y,resize_image->columns,1,
&resize_image->exception);
if ((q == (PixelPacket *) NULL) ||
(chroma_pixels == (const PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGreen(q,GetPixelGreen(chroma_pixels));
SetPixelBlue(q,GetPixelBlue(chroma_pixels));
chroma_pixels++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
resize_image=DestroyImage(resize_image);
if (SetImageColorspace(image,YCbCrColorspace) == MagickFalse)
break;
if (interlace == PartitionInterlace)
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (interlace == NoInterlace)
count=ReadBlob(image,(size_t) (2*quantum*image->columns),scanline);
else
count=ReadBlob(image,(size_t) quantum*image->columns,scanline);
if (count != 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (count != 0);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
InheritException(exception,&image->exception);
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickBooleanType WritePSDImage(const ImageInfo *image_info,
Image *image)
{
char
layer_name[MaxTextExtent];
const char
*property;
const StringInfo
*icc_profile,
*info;
Image
*base_image,
*next_image;
MagickBooleanType
status;
MagickOffsetType
*layer_size_offsets,
size_offset;
PSDInfo
psd_info;
register ssize_t
i;
size_t
layer_count,
layer_index,
length,
name_length,
num_channels,
packet_size,
rounded_size,
size;
StringInfo
*bim_profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->matte != MagickFalse)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
/* When the image has a color profile it won't be converted to gray scale */
if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) &&
(SetImageGray(image,&image->exception) != MagickFalse))
num_channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorMatteType) && (image->storage_class == PseudoClass))
num_channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass);
if (image->colorspace != CMYKColorspace)
num_channels=(image->matte != MagickFalse ? 4UL : 3UL);
else
num_channels=(image->matte != MagickFalse ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsGrayImage(image,&image->exception) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsMonochromeImage(image,&image->exception) &&
(image->depth == 1) ? MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsGrayImage(image,&image->exception) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
base_image=GetNextImageInList(image);
if (base_image == (Image *)NULL)
base_image=image;
size=0;
size_offset=TellBlob(image);
SetPSDSize(&psd_info,image,0);
SetPSDSize(&psd_info,image,0);
layer_count=0;
for (next_image=base_image; next_image != NULL; )
{
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (image->matte != MagickFalse)
size+=WriteBlobMSBShort(image,-(unsigned short) layer_count);
else
size+=WriteBlobMSBShort(image,(unsigned short) layer_count);
layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(
(size_t) layer_count,sizeof(MagickOffsetType));
if (layer_size_offsets == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
layer_index=0;
for (next_image=base_image; next_image != NULL; )
{
Image
*mask;
unsigned char
default_color;
unsigned short
channels,
total_channels;
mask=(Image *) NULL;
property=GetImageArtifact(next_image,"psd:opacity-mask");
default_color=0;
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
&image->exception);
default_color=strlen(property) == 9 ? 255 : 0;
}
size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
next_image->rows));
size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
next_image->columns));
channels=1U;
if ((next_image->storage_class != PseudoClass) &&
(IsGrayImage(next_image,&next_image->exception) == MagickFalse))
channels=next_image->colorspace == CMYKColorspace ? 4U : 3U;
total_channels=channels;
if (next_image->matte != MagickFalse)
total_channels++;
if (mask != (Image *) NULL)
total_channels++;
size+=WriteBlobMSBShort(image,total_channels);
layer_size_offsets[layer_index++]=TellBlob(image);
for (i=0; i < (ssize_t) channels; i++)
size+=WriteChannelSize(&psd_info,image,(signed short) i);
if (next_image->matte != MagickFalse)
size+=WriteChannelSize(&psd_info,image,-1);
if (mask != (Image *) NULL)
size+=WriteChannelSize(&psd_info,image,-2);
size+=WriteBlob(image,4,(const unsigned char *) "8BIM");
size+=WriteBlob(image,4,(const unsigned char *)
CompositeOperatorToPSDBlendMode(next_image->compose));
property=GetImageArtifact(next_image,"psd:layer.opacity");
if (property != (const char *) NULL)
{
Quantum
opacity;
opacity=(Quantum) StringToInteger(property);
size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));
(void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,
&image->exception);
}
else
size+=WriteBlobByte(image,255);
size+=WriteBlobByte(image,0);
size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
size+=WriteBlobByte(image,0);
info=GetAdditionalInformation(image_info,next_image);
property=(const char *) GetImageProperty(next_image,"label");
if (property == (const char *) NULL)
{
(void) FormatLocaleString(layer_name,MaxTextExtent,"L%.20g",
(double) layer_index);
property=layer_name;
}
name_length=strlen(property)+1;
if ((name_length % 4) != 0)
name_length+=(4-(name_length % 4));
if (info != (const StringInfo *) NULL)
name_length+=GetStringInfoLength(info);
name_length+=8;
if (mask != (Image *) NULL)
name_length+=20;
size+=WriteBlobMSBLong(image,(unsigned int) name_length);
if (mask == (Image *) NULL)
size+=WriteBlobMSBLong(image,0);
else
{
if (mask->compose != NoCompositeOp)
(void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(
default_color),MagickTrue,&image->exception);
mask->page.y+=image->page.y;
mask->page.x+=image->page.x;
size+=WriteBlobMSBLong(image,20);
size+=WriteBlobMSBSignedLong(image,mask->page.y);
size+=WriteBlobMSBSignedLong(image,mask->page.x);
size+=WriteBlobMSBSignedLong(image,(const signed int) mask->rows+
mask->page.y);
size+=WriteBlobMSBSignedLong(image,(const signed int) mask->columns+
mask->page.x);
size+=WriteBlobByte(image,default_color);
size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0);
size+=WriteBlobMSBShort(image,0);
}
size+=WriteBlobMSBLong(image,0);
size+=WritePascalString(image,property,4);
if (info != (const StringInfo *) NULL)
size+=WriteBlob(image,GetStringInfoLength(info),
GetStringInfoDatum(info));
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
layer_index=0;
while (next_image != NULL)
{
length=WritePSDChannels(&psd_info,image_info,image,next_image,
layer_size_offsets[layer_index++],MagickTrue);
if (length == 0)
{
status=MagickFalse;
break;
}
size+=length;
next_image=GetNextImageInList(next_image);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
/*
Remove the opacity mask from the registry
*/
next_image=base_image;
while (next_image != (Image *) NULL)
{
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
DeleteImageRegistry(property);
next_image=GetNextImageInList(next_image);
}
/*
Write the total size
*/
size_offset+=WritePSDSize(&psd_info,image,size+
(psd_info.version == 1 ? 8 : 12),size_offset);
if ((size/2) != ((size+1)/2))
rounded_size=size+1;
else
rounded_size=size;
(void) WritePSDSize(&psd_info,image,rounded_size,size_offset);
layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(
layer_size_offsets);
/*
Write composite image.
*/
if (status != MagickFalse)
{
CompressionType
compression;
compression=image->compression;
if (image->compression == ZipCompression)
image->compression=RLECompression;
if (WritePSDChannels(&psd_info,image_info,image,image,0,
MagickFalse) == 0)
status=MagickFalse;
image->compression=compression;
}
(void) CloseBlob(image);
return(status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadIPLImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
/*
Declare variables.
*/
Image *image;
MagickBooleanType status;
register PixelPacket *q;
unsigned char magick[12], *pixels;
ssize_t count;
ssize_t y;
size_t t_count=0;
size_t length;
IPLInfo
ipl_info;
QuantumFormatType
quantum_format;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
extent;
/*
Open Image
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if ( image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent, GetMagickModule(), "%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read IPL image
*/
/*
Determine endianness
If we get back "iiii", we have LSB,"mmmm", MSB
*/
count=ReadBlob(image,4,magick);
if (count != 4)
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
if((LocaleNCompare((char *) magick,"iiii",4) == 0))
image->endian=LSBEndian;
else{
if((LocaleNCompare((char *) magick,"mmmm",4) == 0))
image->endian=MSBEndian;
else{
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
}
}
/* Skip o'er the next 8 bytes (garbage) */
count=ReadBlob(image, 8, magick);
/*
Excellent, now we read the header unimpeded.
*/
count=ReadBlob(image,4,magick);
if((count != 4) || (LocaleNCompare((char *) magick,"data",4) != 0))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
ipl_info.size=ReadBlobLong(image);
ipl_info.width=ReadBlobLong(image);
ipl_info.height=ReadBlobLong(image);
if((ipl_info.width == 0UL) || (ipl_info.height == 0UL))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
ipl_info.colors=ReadBlobLong(image);
if(ipl_info.colors == 3){ SetImageColorspace(image,sRGBColorspace);}
else { image->colorspace = GRAYColorspace; }
ipl_info.z=ReadBlobLong(image);
ipl_info.time=ReadBlobLong(image);
ipl_info.byteType=ReadBlobLong(image);
/* Initialize Quantum Info */
switch (ipl_info.byteType) {
case 0:
ipl_info.depth=8;
quantum_format = UnsignedQuantumFormat;
break;
case 1:
ipl_info.depth=16;
quantum_format = SignedQuantumFormat;
break;
case 2:
ipl_info.depth=16;
quantum_format = UnsignedQuantumFormat;
break;
case 3:
ipl_info.depth=32;
quantum_format = SignedQuantumFormat;
break;
case 4: ipl_info.depth=32;
quantum_format = FloatingPointQuantumFormat;
break;
case 5:
ipl_info.depth=8;
quantum_format = UnsignedQuantumFormat;
break;
case 6:
ipl_info.depth=16;
quantum_format = UnsignedQuantumFormat;
break;
case 10:
ipl_info.depth=64;
quantum_format = FloatingPointQuantumFormat;
break;
default:
ipl_info.depth=16;
quantum_format = UnsignedQuantumFormat;
break;
}
extent=ipl_info.width*ipl_info.height*ipl_info.z*ipl_info.depth/8;
if (extent > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/*
Set number of scenes of image
*/
SetHeaderFromIPL(image, &ipl_info);
/* Thats all we need if we are pinging. */
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
length=image->columns;
quantum_type=GetQuantumType(image,exception);
do
{
SetHeaderFromIPL(image, &ipl_info);
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
printf("Length: %.20g, Memory size: %.20g\n", (double) length,(double)
image->depth);
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,quantum_format);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
if(image->columns != ipl_info.width){
/*
printf("Columns not set correctly! Wanted: %.20g, got: %.20g\n",
(double) ipl_info.width, (double) image->columns);
*/
}
/*
Covert IPL binary to pixel packets
*/
if(ipl_info.colors == 1){
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else{
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RedQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GreenQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
for(y = 0; y < (ssize_t) image->rows; y++){
(void) ReadBlob(image, length*image->depth/8, pixels);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
BlueQuantum,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
SetQuantumImageType(image,quantum_type);
t_count++;
quantum_info = DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if(t_count < ipl_info.z * ipl_info.time){
/*
Proceed to next image.
*/
AcquireNextImage(image_info, image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (t_count < ipl_info.z*ipl_info.time);
CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowPCXException(severity,tag) \
{ \
if (scanline != (unsigned char *) NULL) \
scanline=(unsigned char *) RelinquishMagickMemory(scanline); \
if (pixel_info != (MemoryInfo *) NULL) \
pixel_info=RelinquishVirtualMemory(pixel_info); \
if (page_table != (MagickOffsetType *) NULL) \
page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); \
ThrowReaderException(severity,tag); \
}
Image
*image;
int
bits,
id,
mask;
MagickBooleanType
status;
MagickOffsetType
offset,
*page_table;
MemoryInfo
*pixel_info;
PCXInfo
pcx_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p,
*r;
size_t
one,
pcx_packets;
ssize_t
count,
y;
unsigned char
packet,
pcx_colormap[768],
*pixels,
*scanline;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a PCX file.
*/
page_table=(MagickOffsetType *) NULL;
scanline=(unsigned char *) NULL;
pixel_info=(MemoryInfo *) NULL;
if (LocaleCompare(image_info->magick,"DCX") == 0)
{
size_t
magic;
/*
Read the DCX page table.
*/
magic=ReadBlobLSBLong(image);
if (magic != 987654321)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL,
sizeof(*page_table));
if (page_table == (MagickOffsetType *) NULL)
ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
for (id=0; id < 1024; id++)
{
page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image);
if (page_table[id] == 0)
break;
}
}
if (page_table != (MagickOffsetType *) NULL)
{
offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET);
if (offset < 0)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,1,&pcx_info.identifier);
for (id=1; id < 1024; id++)
{
int
bits_per_pixel;
/*
Verify PCX identifier.
*/
pcx_info.version=(unsigned char) ReadBlobByte(image);
if ((count != 1) || (pcx_info.identifier != 0x0a))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_info.encoding=(unsigned char) ReadBlobByte(image);
bits_per_pixel=ReadBlobByte(image);
if (bits_per_pixel == -1)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel;
pcx_info.left=ReadBlobLSBShort(image);
pcx_info.top=ReadBlobLSBShort(image);
pcx_info.right=ReadBlobLSBShort(image);
pcx_info.bottom=ReadBlobLSBShort(image);
pcx_info.horizontal_resolution=ReadBlobLSBShort(image);
pcx_info.vertical_resolution=ReadBlobLSBShort(image);
/*
Read PCX raster colormap.
*/
image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right-
pcx_info.left)+1UL;
image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom-
pcx_info.top)+1UL;
if ((image->columns == 0) || (image->rows == 0) ||
((pcx_info.bits_per_pixel != 1) && (pcx_info.bits_per_pixel != 2) &&
(pcx_info.bits_per_pixel != 4) && (pcx_info.bits_per_pixel != 8)))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
image->depth=pcx_info.bits_per_pixel;
image->units=PixelsPerInchResolution;
image->x_resolution=(double) pcx_info.horizontal_resolution;
image->y_resolution=(double) pcx_info.vertical_resolution;
image->colors=16;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
ThrowPCXException(image->exception.severity,image->exception.reason);
(void) SetImageBackgroundColor(image);
(void) memset(pcx_colormap,0,sizeof(pcx_colormap));
count=ReadBlob(image,3*image->colors,pcx_colormap);
if (count != (ssize_t) (3*image->colors))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_info.reserved=(unsigned char) ReadBlobByte(image);
pcx_info.planes=(unsigned char) ReadBlobByte(image);
if (pcx_info.planes > 6)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
if (pcx_info.planes == 0)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
one=1;
if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1))
if ((pcx_info.version == 3) || (pcx_info.version == 5) ||
((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
image->colors=(size_t) MagickMin(one << (1UL*
(pcx_info.bits_per_pixel*pcx_info.planes)),256UL);
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1))
image->storage_class=DirectClass;
p=pcx_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
pcx_info.bytes_per_line=ReadBlobLSBShort(image);
pcx_info.palette_info=ReadBlobLSBShort(image);
pcx_info.horizontal_screensize=ReadBlobLSBShort(image);
pcx_info.vertical_screensize=ReadBlobLSBShort(image);
for (i=0; i < 54; i++)
(void) ReadBlobByte(image);
/*
Read image data.
*/
if (HeapOverflowSanityCheck(image->rows, (size_t) pcx_info.bytes_per_line) != MagickFalse)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line;
if (HeapOverflowSanityCheck(pcx_packets, (size_t) pcx_info.planes) != MagickFalse)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_packets=(size_t) pcx_packets*pcx_info.planes;
if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) >
(pcx_packets*8U))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
if ((MagickSizeType) (pcx_packets/8) > GetBlobSize(image))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns,
pcx_info.bytes_per_line),MagickMax(pcx_info.planes,8)*sizeof(*scanline));
pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels));
if ((scanline == (unsigned char *) NULL) ||
(pixel_info == (MemoryInfo *) NULL))
{
if (scanline != (unsigned char *) NULL)
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) memset(scanline,0,(size_t) MagickMax(image->columns,
pcx_info.bytes_per_line)*MagickMax(pcx_info.planes,8)*sizeof(*scanline));
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) memset(pixels,0,(size_t) pcx_packets*(2*sizeof(*pixels)));
/*
Uncompress image data.
*/
p=pixels;
if (pcx_info.encoding == 0)
while (pcx_packets != 0)
{
packet=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
*p++=packet;
pcx_packets--;
}
else
while (pcx_packets != 0)
{
packet=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
if ((packet & 0xc0) != 0xc0)
{
*p++=packet;
pcx_packets--;
continue;
}
count=(ssize_t) (packet & 0x3f);
packet=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
for ( ; count != 0; count--)
{
*p++=packet;
pcx_packets--;
if (pcx_packets == 0)
break;
}
}
if (image->storage_class == DirectClass)
image->matte=pcx_info.planes > 3 ? MagickTrue : MagickFalse;
else
if ((pcx_info.version == 5) ||
((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
{
/*
Initialize image colormap.
*/
if (image->colors > 256)
ThrowPCXException(CorruptImageError,"ColormapExceeds256Colors");
if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)
{
/*
Monochrome colormap.
*/
image->colormap[0].red=(Quantum) 0;
image->colormap[0].green=(Quantum) 0;
image->colormap[0].blue=(Quantum) 0;
image->colormap[1].red=QuantumRange;
image->colormap[1].green=QuantumRange;
image->colormap[1].blue=QuantumRange;
}
else
if (image->colors > 16)
{
/*
256 color images have their color map at the end of the file.
*/
pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image);
count=ReadBlob(image,3*image->colors,pcx_colormap);
p=pcx_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
}
}
/*
Convert PCX raster image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
r=scanline;
if (image->storage_class == DirectClass)
for (i=0; i < pcx_info.planes; i++)
{
r=scanline+i;
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
switch (i)
{
case 0:
{
*r=(*p++);
break;
}
case 1:
{
*r=(*p++);
break;
}
case 2:
{
*r=(*p++);
break;
}
case 3:
default:
{
*r=(*p++);
break;
}
}
r+=pcx_info.planes;
}
}
else
if (pcx_info.planes > 1)
{
for (x=0; x < (ssize_t) image->columns; x++)
*r++=0;
for (i=0; i < pcx_info.planes; i++)
{
r=scanline;
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
bits=(*p++);
for (mask=0x80; mask != 0; mask>>=1)
{
if (bits & mask)
*r|=1 << i;
r++;
}
}
}
}
else
switch (pcx_info.bits_per_pixel)
{
case 1:
{
register ssize_t
bit;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
*r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--)
*r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
p++;
}
break;
}
case 2:
{
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
*r++=(*p >> 6) & 0x3;
*r++=(*p >> 4) & 0x3;
*r++=(*p >> 2) & 0x3;
*r++=(*p) & 0x3;
p++;
}
if ((image->columns % 4) != 0)
{
for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--)
*r++=(unsigned char) ((*p >> (i*2)) & 0x03);
p++;
}
break;
}
case 4:
{
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
*r++=(*p >> 4) & 0xf;
*r++=(*p) & 0xf;
p++;
}
if ((image->columns % 2) != 0)
*r++=(*p++ >> 4) & 0xf;
break;
}
case 8:
{
(void) memcpy(r,p,image->columns);
break;
}
default:
break;
}
/*
Transfer image scanline.
*/
r=scanline;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x,*r++);
else
{
SetPixelRed(q,ScaleCharToQuantum(*r++));
SetPixelGreen(q,ScaleCharToQuantum(*r++));
SetPixelBlue(q,ScaleCharToQuantum(*r++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*r++));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (image->storage_class == PseudoClass)
(void) SyncImage(image);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (page_table == (MagickOffsetType *) NULL)
break;
if (page_table[id] == 0)
break;
offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET);
if (offset < 0)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,1,&pcx_info.identifier);
if ((count != 0) && (pcx_info.identifier == 0x0a))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
if (page_table != (MagickOffsetType *) NULL)
page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SGI raster header.
*/
(void) memset(&iris_info,0,sizeof(iris_info));
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
if ((iris_info.dimension == 0) || (iris_info.dimension > 3))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
if ((size_t) count != sizeof(iris_info.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
if ((size_t) count != sizeof(iris_info.filler))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->matte=iris_info.depth == 4 ? MagickTrue : MagickFalse;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=(size_t) (iris_info.bytes_per_pixel > 1 ? 65535 : 256);
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status != MagickFalse)
status=ResetImagePixels(image,&image->exception);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) memset(pixels,0,iris_info.columns*iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (count != (bytes_per_pixel*iris_info.columns))
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
if (y < (ssize_t) iris_info.rows)
break;
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info != (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=(ssize_t) ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
{
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
runlength=(size_t *) RelinquishMagickMemory(runlength);
packet_info=RelinquishVirtualMemory(packet_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset,
SEEK_SET);
}
(void) ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (count != runlength[y+z*iris_info.rows])
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
(ssize_t) iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
{
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
runlength=(size_t *) RelinquishMagickMemory(runlength);
packet_info=RelinquishVirtualMemory(packet_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
if (y < (ssize_t) iris_info.rows)
break;
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset,
SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (count != runlength[y+z*iris_info.rows])
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
(ssize_t) iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
{
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
runlength=(size_t *) RelinquishMagickMemory(runlength);
packet_info=RelinquishVirtualMemory(packet_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
if (z < (ssize_t) iris_info.depth)
break;
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))));
SetPixelGreen(q,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))));
SetPixelBlue(q,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))));
p+=8;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p));
q->green=ScaleCharToQuantum(*(p+1));
q->blue=ScaleCharToQuantum(*(p+2));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*(p+3)));
p+=4;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(indexes+x,quantum);
p+=8;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(indexes+x,*p);
p+=4;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MaxTextExtent],
text[MaxTextExtent];
double
x_offset,
y_offset;
Image
*image;
IndexPacket
*indexes;
MagickBooleanType
status;
MagickPixelPacket
pixel;
QuantumAny
range;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) memset(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
x_offset=(-1.0);
y_offset=(-1.0);
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%32s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
if ((max_value == 0) || (max_value > 4294967295U))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status != MagickFalse)
status=ResetImagePixels(image,&image->exception);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->matte=MagickFalse;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->matte=MagickTrue;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->colorspace=(ColorspaceType) type;
(void) memset(&pixel,0,sizeof(pixel));
(void) SetImageBackgroundColor(image);
range=GetQuantumRange(image->depth);
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
index,
opacity,
red;
if (status == MagickFalse)
break;
red=0.0;
green=0.0;
blue=0.0;
index=0.0;
opacity=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
{
status=MagickFalse;
break;
}
switch (image->colorspace)
{
case LinearGRAYColorspace:
case GRAYColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,"%lf,%lf: (%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&opacity);
green=red;
blue=red;
break;
}
(void) sscanf(text,"%lf,%lf: (%lf%*[%,]",&x_offset,&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&index,&opacity);
break;
}
(void) sscanf(text,
"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&index);
break;
}
default:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&opacity);
break;
}
(void) sscanf(text,"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
index*=0.01*range;
opacity*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5),
range);
pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+
0.5),range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->colorspace == CMYKColorspace)
{
indexes=GetAuthenticIndexQueue(image);
SetPixelIndex(indexes,pixel.index);
}
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel.opacity);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
{
status=MagickFalse;
break;
}
}
}
if (status == MagickFalse)
break;
*text='\0';
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define BoundingBox "BoundingBox:"
#define BeginDocument "BeginDocument:"
#define BeginXMPPacket "<?xpacket begin="
#define EndXMPPacket "<?xpacket end="
#define ICCProfile "BeginICCProfile:"
#define CMYKCustomColor "CMYKCustomColor:"
#define CMYKProcessColor "CMYKProcessColor:"
#define DocumentMedia "DocumentMedia:"
#define DocumentCustomColors "DocumentCustomColors:"
#define DocumentProcessColors "DocumentProcessColors:"
#define EndDocument "EndDocument:"
#define HiResBoundingBox "HiResBoundingBox:"
#define ImageData "ImageData:"
#define PageBoundingBox "PageBoundingBox:"
#define LanguageLevel "LanguageLevel:"
#define PageMedia "PageMedia:"
#define Pages "Pages:"
#define PhotoshopProfile "BeginPhotoshop:"
#define PostscriptLevel "!PS-"
#define RenderPostscriptText " Rendering Postscript... "
#define SpotColor "+ "
char
command[MagickPathExtent],
*density,
filename[MagickPathExtent],
geometry[MagickPathExtent],
input_filename[MagickPathExtent],
message[MagickPathExtent],
*options,
postscript_filename[MagickPathExtent];
const char
*option;
const DelegateInfo
*delegate_info;
GeometryInfo
geometry_info;
Image
*image,
*next,
*postscript_image;
ImageInfo
*read_info;
int
c,
file;
MagickBooleanType
cmyk,
fitPage,
skip,
status;
MagickStatusType
flags;
PointInfo
delta,
resolution;
RectangleInfo
page;
register char
*p;
register ssize_t
i;
SegmentInfo
bounds,
hires_bounds;
short int
hex_digits[256];
size_t
length;
ssize_t
count,
priority;
StringInfo
*profile;
unsigned long
columns,
extent,
language_level,
pages,
rows,
scene,
spotcolor;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);
if (status == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
image_info->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize hex values.
*/
(void) memset(hex_digits,0,sizeof(hex_digits));
hex_digits[(int) '0']=0;
hex_digits[(int) '1']=1;
hex_digits[(int) '2']=2;
hex_digits[(int) '3']=3;
hex_digits[(int) '4']=4;
hex_digits[(int) '5']=5;
hex_digits[(int) '6']=6;
hex_digits[(int) '7']=7;
hex_digits[(int) '8']=8;
hex_digits[(int) '9']=9;
hex_digits[(int) 'a']=10;
hex_digits[(int) 'b']=11;
hex_digits[(int) 'c']=12;
hex_digits[(int) 'd']=13;
hex_digits[(int) 'e']=14;
hex_digits[(int) 'f']=15;
hex_digits[(int) 'A']=10;
hex_digits[(int) 'B']=11;
hex_digits[(int) 'C']=12;
hex_digits[(int) 'D']=13;
hex_digits[(int) 'E']=14;
hex_digits[(int) 'F']=15;
/*
Set the page density.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))
{
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
if (image_info->density != (char *) NULL)
{
flags=ParseGeometry(image_info->density,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
(void) ParseAbsoluteGeometry(PSPageGeometry,&page);
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
resolution=image->resolution;
page.width=(size_t) ceil((double) (page.width*resolution.x/delta.x)-0.5);
page.height=(size_t) ceil((double) (page.height*resolution.y/delta.y)-0.5);
/*
Determine page geometry from the Postscript bounding box.
*/
(void) memset(&bounds,0,sizeof(bounds));
(void) memset(command,0,sizeof(command));
cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;
(void) memset(&hires_bounds,0,sizeof(hires_bounds));
columns=0;
rows=0;
priority=0;
rows=0;
extent=0;
spotcolor=0;
language_level=1;
pages=(~0UL);
skip=MagickFalse;
p=command;
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
/*
Note document structuring comments.
*/
*p++=(char) c;
if ((strchr("\n\r%",c) == (char *) NULL) &&
((size_t) (p-command) < (MagickPathExtent-1)))
continue;
*p='\0';
p=command;
/*
Skip %%BeginDocument thru %%EndDocument.
*/
if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0)
skip=MagickTrue;
if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0)
skip=MagickFalse;
if (skip != MagickFalse)
continue;
if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0)
{
(void) SetImageProperty(image,"ps:Level",command+4,exception);
if (GlobExpression(command,"*EPSF-*",MagickTrue) != MagickFalse)
pages=1;
}
if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0)
(void) sscanf(command,LanguageLevel " %lu",&language_level);
if (LocaleNCompare(Pages,command,strlen(Pages)) == 0)
(void) sscanf(command,Pages " %lu",&pages);
if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0)
(void) sscanf(command,ImageData " %lu %lu",&columns,&rows);
/*
Is this a CMYK document?
*/
length=strlen(DocumentProcessColors);
if (LocaleNCompare(DocumentProcessColors,command,length) == 0)
{
if ((GlobExpression(command,"*Cyan*",MagickTrue) != MagickFalse) ||
(GlobExpression(command,"*Magenta*",MagickTrue) != MagickFalse) ||
(GlobExpression(command,"*Yellow*",MagickTrue) != MagickFalse))
cmyk=MagickTrue;
}
if (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0)
cmyk=MagickTrue;
if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0)
cmyk=MagickTrue;
length=strlen(DocumentCustomColors);
if ((LocaleNCompare(DocumentCustomColors,command,length) == 0) ||
(LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) ||
(LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0))
{
char
property[MagickPathExtent],
*value;
register char
*q;
/*
Note spot names.
*/
(void) FormatLocaleString(property,MagickPathExtent,
"ps:SpotColor-%.20g",(double) (spotcolor++));
for (q=command; *q != '\0'; q++)
if (isspace((int) (unsigned char) *q) != 0)
break;
value=ConstantString(q);
(void) SubstituteString(&value,"(","");
(void) SubstituteString(&value,")","");
(void) StripString(value);
if (*value != '\0')
(void) SetImageProperty(image,property,value,exception);
value=DestroyString(value);
continue;
}
if (image_info->page != (char *) NULL)
continue;
/*
Note region defined by bounding box.
*/
count=0;
i=0;
if (LocaleNCompare(BoundingBox,command,strlen(BoundingBox)) == 0)
{
count=(ssize_t) sscanf(command,BoundingBox " %lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
i=2;
}
if (LocaleNCompare(DocumentMedia,command,strlen(DocumentMedia)) == 0)
{
count=(ssize_t) sscanf(command,DocumentMedia " %lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
i=1;
}
if (LocaleNCompare(HiResBoundingBox,command,strlen(HiResBoundingBox)) == 0)
{
count=(ssize_t) sscanf(command,HiResBoundingBox " %lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
i=3;
}
if (LocaleNCompare(PageBoundingBox,command,strlen(PageBoundingBox)) == 0)
{
count=(ssize_t) sscanf(command,PageBoundingBox " %lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
i=1;
}
if (LocaleNCompare(PageMedia,command,strlen(PageMedia)) == 0)
{
count=(ssize_t) sscanf(command,PageMedia " %lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
i=1;
}
if ((count != 4) || (i < (ssize_t) priority))
continue;
if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) ||
(fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1)))
if (i == (ssize_t) priority)
continue;
hires_bounds=bounds;
priority=i;
}
if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) &&
(fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon))
{
/*
Set Postscript render geometry.
*/
(void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+.15g%+.15g",
hires_bounds.x2-hires_bounds.x1,hires_bounds.y2-hires_bounds.y1,
hires_bounds.x1,hires_bounds.y1);
(void) SetImageProperty(image,"ps:HiResBoundingBox",geometry,exception);
page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)*
resolution.x/delta.x)-0.5);
page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)*
resolution.y/delta.y)-0.5);
}
fitPage=MagickFalse;
option=GetImageOption(image_info,"eps:fit-page");
if (option != (char *) NULL)
{
char
*page_geometry;
page_geometry=GetPageGeometry(option);
flags=ParseMetaGeometry(page_geometry,&page.x,&page.y,&page.width,
&page.height);
if (flags == NoValue)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidGeometry","`%s'",option);
image=DestroyImage(image);
return((Image *) NULL);
}
page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x)
-0.5);
page.height=(size_t) ceil((double) (page.height*image->resolution.y/
delta.y) -0.5);
page_geometry=DestroyString(page_geometry);
fitPage=MagickTrue;
}
if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse)
cmyk=MagickFalse;
/*
Create Ghostscript control file.
*/
file=AcquireUniqueFileResource(postscript_filename);
if (file == -1)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image_info->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) CopyMagickString(command,"/setpagedevice {pop} bind 1 index where {"
"dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\n"
"<</UseCIEColor true>>setpagedevice\n",MagickPathExtent);
count=write(file,command,(unsigned int) strlen(command));
if (image_info->page == (char *) NULL)
{
char
translate_geometry[MagickPathExtent];
(void) FormatLocaleString(translate_geometry,MagickPathExtent,
"%g %g translate\n",-bounds.x1,-bounds.y1);
count=write(file,translate_geometry,(unsigned int)
strlen(translate_geometry));
}
file=close(file)-1;
/*
Render Postscript with the Ghostscript delegate.
*/
if (image_info->monochrome != MagickFalse)
delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception);
else
if (cmyk != MagickFalse)
delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception);
else
delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception);
if (delegate_info == (const DelegateInfo *) NULL)
{
(void) RelinquishUniqueFileResource(postscript_filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
density=AcquireString("");
options=AcquireString("");
(void) FormatLocaleString(density,MagickPathExtent,"%gx%g",resolution.x,
resolution.y);
(void) FormatLocaleString(options,MagickPathExtent,"-g%.20gx%.20g ",(double)
page.width,(double) page.height);
read_info=CloneImageInfo(image_info);
*read_info->magick='\0';
if (read_info->number_scenes != 0)
{
char
pages[MagickPathExtent];
(void) FormatLocaleString(pages,MagickPathExtent,"-dFirstPage=%.20g "
"-dLastPage=%.20g ",(double) read_info->scene+1,(double)
(read_info->scene+read_info->number_scenes));
(void) ConcatenateMagickString(options,pages,MagickPathExtent);
read_info->number_scenes=0;
if (read_info->scenes != (char *) NULL)
*read_info->scenes='\0';
}
if (*image_info->magick == 'E')
{
option=GetImageOption(image_info,"eps:use-cropbox");
if ((option == (const char *) NULL) ||
(IsStringTrue(option) != MagickFalse))
(void) ConcatenateMagickString(options,"-dEPSCrop ",MagickPathExtent);
if (fitPage != MagickFalse)
(void) ConcatenateMagickString(options,"-dEPSFitPage ",
MagickPathExtent);
}
(void) CopyMagickString(filename,read_info->filename,MagickPathExtent);
(void) AcquireUniqueFilename(filename);
(void) RelinquishUniqueFileResource(filename);
(void) ConcatenateMagickString(filename,"%d",MagickPathExtent);
(void) FormatLocaleString(command,MagickPathExtent,
GetDelegateCommands(delegate_info),
read_info->antialias != MagickFalse ? 4 : 1,
read_info->antialias != MagickFalse ? 4 : 1,density,options,filename,
postscript_filename,input_filename);
options=DestroyString(options);
density=DestroyString(density);
*message='\0';
status=InvokePostscriptDelegate(read_info->verbose,command,message,exception);
(void) InterpretImageFilename(image_info,image,filename,1,
read_info->filename,exception);
if ((status == MagickFalse) ||
(IsPostscriptRendered(read_info->filename) == MagickFalse))
{
(void) ConcatenateMagickString(command," -c showpage",MagickPathExtent);
status=InvokePostscriptDelegate(read_info->verbose,command,message,
exception);
}
(void) RelinquishUniqueFileResource(postscript_filename);
(void) RelinquishUniqueFileResource(input_filename);
postscript_image=(Image *) NULL;
if (status == MagickFalse)
for (i=1; ; i++)
{
(void) InterpretImageFilename(image_info,image,filename,(int) i,
read_info->filename,exception);
if (IsPostscriptRendered(read_info->filename) == MagickFalse)
break;
(void) RelinquishUniqueFileResource(read_info->filename);
}
else
for (i=1; ; i++)
{
(void) InterpretImageFilename(image_info,image,filename,(int) i,
read_info->filename,exception);
if (IsPostscriptRendered(read_info->filename) == MagickFalse)
break;
read_info->blob=NULL;
read_info->length=0;
next=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(read_info->filename);
if (next == (Image *) NULL)
break;
AppendImageToList(&postscript_image,next);
}
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
if (postscript_image == (Image *) NULL)
{
if (*message != '\0')
(void) ThrowMagickException(exception,GetMagickModule(),
DelegateError,"PostscriptDelegateFailed","`%s'",message);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (LocaleCompare(postscript_image->magick,"BMP") == 0)
{
Image
*cmyk_image;
cmyk_image=ConsolidateCMYKImages(postscript_image,exception);
if (cmyk_image != (Image *) NULL)
{
postscript_image=DestroyImageList(postscript_image);
postscript_image=cmyk_image;
}
}
(void) SeekBlob(image,0,SEEK_SET);
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
/*
Note document structuring comments.
*/
*p++=(char) c;
if ((strchr("\n\r%",c) == (char *) NULL) &&
((size_t) (p-command) < (MagickPathExtent-1)))
continue;
*p='\0';
p=command;
/*
Skip %%BeginDocument thru %%EndDocument.
*/
if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0)
skip=MagickTrue;
if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0)
skip=MagickFalse;
if (skip != MagickFalse)
continue;
if (LocaleNCompare(ICCProfile,command,strlen(ICCProfile)) == 0)
{
unsigned char
*datum;
/*
Read ICC profile.
*/
profile=AcquireStringInfo(MagickPathExtent);
datum=GetStringInfoDatum(profile);
for (i=0; (c=ProfileInteger(image,hex_digits)) != EOF; i++)
{
if (i >= (ssize_t) GetStringInfoLength(profile))
{
SetStringInfoLength(profile,(size_t) i << 1);
datum=GetStringInfoDatum(profile);
}
datum[i]=(unsigned char) c;
}
SetStringInfoLength(profile,(size_t) i+1);
(void) SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
continue;
}
if (LocaleNCompare(PhotoshopProfile,command,strlen(PhotoshopProfile)) == 0)
{
unsigned char
*q;
/*
Read Photoshop profile.
*/
count=(ssize_t) sscanf(command,PhotoshopProfile " %lu",&extent);
if (count != 1)
continue;
length=extent;
if ((MagickSizeType) length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
profile=BlobToStringInfo((const void *) NULL,length);
if (profile != (StringInfo *) NULL)
{
q=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) length; i++)
*q++=(unsigned char) ProfileInteger(image,hex_digits);
(void) SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
}
continue;
}
if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0)
{
/*
Read XMP profile.
*/
p=command;
profile=StringToStringInfo(command);
for (i=(ssize_t) GetStringInfoLength(profile)-1; c != EOF; i++)
{
SetStringInfoLength(profile,(size_t) (i+1));
c=ReadBlobByte(image);
GetStringInfoDatum(profile)[i]=(unsigned char) c;
*p++=(char) c;
if ((strchr("\n\r%",c) == (char *) NULL) &&
((size_t) (p-command) < (MagickPathExtent-1)))
continue;
*p='\0';
p=command;
if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0)
break;
}
SetStringInfoLength(profile,(size_t) i);
(void) SetImageProfile(image,"xmp",profile,exception);
profile=DestroyStringInfo(profile);
continue;
}
}
(void) CloseBlob(image);
if (image_info->number_scenes != 0)
{
Image
*clone_image;
/*
Add place holder images to meet the subimage specification requirement.
*/
for (i=0; i < (ssize_t) image_info->scene; i++)
{
clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception);
if (clone_image != (Image *) NULL)
PrependImageToList(&postscript_image,clone_image);
}
}
do
{
(void) CopyMagickString(postscript_image->filename,filename,
MagickPathExtent);
(void) CopyMagickString(postscript_image->magick,image->magick,
MagickPathExtent);
if (columns != 0)
postscript_image->magick_columns=columns;
if (rows != 0)
postscript_image->magick_rows=rows;
postscript_image->page=page;
(void) CloneImageProfiles(postscript_image,image);
(void) CloneImageProperties(postscript_image,image);
next=SyncNextImageInList(postscript_image);
if (next != (Image *) NULL)
postscript_image=next;
} while (next != (Image *) NULL);
image=DestroyImageList(image);
scene=0;
for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; )
{
next->scene=scene++;
next=GetNextImageInList(next);
}
return(GetFirstImageInList(postscript_image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1601'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowCUTReaderException(severity,tag) \
{ \
if (palette != NULL) \
palette=DestroyImage(palette); \
if (clone_info != NULL) \
clone_info=DestroyImageInfo(clone_info); \
ThrowReaderException(severity,tag); \
}
Image *image,*palette;
ImageInfo *clone_info;
MagickBooleanType status;
MagickOffsetType
offset;
size_t EncodedByte;
unsigned char RunCount,RunValue,RunCountMasked;
CUTHeader Header;
CUTPalHeader PalHeader;
ssize_t depth;
ssize_t i,j;
ssize_t ldblk;
unsigned char *BImgBuff=NULL,*ptrB;
register Quantum *q;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read CUT image.
*/
palette=NULL;
clone_info=NULL;
Header.Width=ReadBlobLSBShort(image);
Header.Height=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0)
CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
/*---This code checks first line of image---*/
EncodedByte=ReadBlobLSBShort(image);
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
ldblk=0;
while((int) RunCountMasked!=0) /*end of line?*/
{
i=1;
if((int) RunCount<0x80) i=(ssize_t) RunCountMasked;
offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET);
if (offset < 0)
ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/
EncodedByte-=i+1;
ldblk+=(ssize_t) RunCountMasked;
RunCount=(unsigned char) ReadBlobByte(image);
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/
RunCountMasked=RunCount & 0x7F;
}
if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/
i=0; /*guess a number of bit planes*/
if(ldblk==(int) Header.Width) i=8;
if(2*ldblk==(int) Header.Width) i=4;
if(8*ldblk==(int) Header.Width) i=1;
if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/
depth=i;
image->columns=Header.Width;
image->rows=Header.Height;
image->depth=8;
image->colors=(size_t) (GetQuantumRange(1UL*i)+1);
if (image_info->ping != MagickFalse) goto Finish;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/* ----- Do something with palette ----- */
if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette;
i=(ssize_t) strlen(clone_info->filename);
j=i;
while(--i>0)
{
if(clone_info->filename[i]=='.')
{
break;
}
if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' ||
clone_info->filename[i]==':' )
{
i=j;
break;
}
}
(void) CopyMagickString(clone_info->filename+i,".PAL",(size_t)
(MagickPathExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
(void) CopyMagickString(clone_info->filename+i,".pal",(size_t)
(MagickPathExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info->filename[i]='\0';
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info=DestroyImageInfo(clone_info);
clone_info=NULL;
goto NoPalette;
}
}
}
if( (palette=AcquireImage(clone_info,exception))==NULL ) goto NoPalette;
status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ErasePalette:
palette=DestroyImage(palette);
palette=NULL;
goto NoPalette;
}
if(palette!=NULL)
{
(void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId);
if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette;
PalHeader.Version=ReadBlobLSBShort(palette);
PalHeader.Size=ReadBlobLSBShort(palette);
PalHeader.FileType=(char) ReadBlobByte(palette);
PalHeader.SubType=(char) ReadBlobByte(palette);
PalHeader.BoardID=ReadBlobLSBShort(palette);
PalHeader.GraphicsMode=ReadBlobLSBShort(palette);
PalHeader.MaxIndex=ReadBlobLSBShort(palette);
PalHeader.MaxRed=ReadBlobLSBShort(palette);
PalHeader.MaxGreen=ReadBlobLSBShort(palette);
PalHeader.MaxBlue=ReadBlobLSBShort(palette);
(void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId);
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
if(PalHeader.MaxIndex<1) goto ErasePalette;
image->colors=PalHeader.MaxIndex+1;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) goto NoMemory;
if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/
if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange;
if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange;
for(i=0;i<=(int) PalHeader.MaxIndex;i++)
{ /*this may be wrong- I don't know why is palette such strange*/
j=(ssize_t) TellBlob(palette);
if((j % 512)>512-6)
{
j=((j / 512)+1)*512;
offset=SeekBlob(palette,j,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxRed)
{
image->colormap[i].red=ClampToQuantum(((double)
image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/
PalHeader.MaxRed);
}
image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxGreen)
{
image->colormap[i].green=ClampToQuantum
(((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen);
}
image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxBlue)
{
image->colormap[i].blue=ClampToQuantum
(((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue);
}
}
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
NoPalette:
if(palette==NULL)
{
image->colors=256;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
{
NoMemory:
ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t)image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
}
/* ----- Load RLE compressed raster ----- */
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/
if(BImgBuff==NULL) goto NoMemory;
offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);
if (offset < 0)
{
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < (int) Header.Height; i++)
{
EncodedByte=ReadBlobLSBShort(image);
ptrB=BImgBuff;
j=ldblk;
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
while ((int) RunCountMasked != 0)
{
if((ssize_t) RunCountMasked>j)
{ /*Wrong Data*/
RunCountMasked=(unsigned char) j;
if(j==0)
{
break;
}
}
if((int) RunCount>0x80)
{
RunValue=(unsigned char) ReadBlobByte(image);
(void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked);
}
else {
(void) ReadBlob(image,(size_t) RunCountMasked,ptrB);
}
ptrB+=(int) RunCountMasked;
j-=(int) RunCountMasked;
if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
}
InsertRow(image,depth,BImgBuff,i,exception);
}
(void) SyncImage(image,exception);
/*detect monochrome image*/
if(palette==NULL)
{ /*attempt to detect binary (black&white) images*/
if ((image->storage_class == PseudoClass) &&
(SetImageGray(image,exception) != MagickFalse))
{
if(GetCutColors(image,exception)==2)
{
for (i=0; i < (ssize_t)image->colors; i++)
{
register Quantum
sample;
sample=ScaleCharToQuantum((unsigned char) i);
if(image->colormap[i].red!=sample) goto Finish;
if(image->colormap[i].green!=sample) goto Finish;
if(image->colormap[i].blue!=sample) goto Finish;
}
image->colormap[1].red=image->colormap[1].green=
image->colormap[1].blue=QuantumRange;
for (i=0; i < (ssize_t)image->rows; i++)
{
q=QueueAuthenticPixels(image,0,i,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (j=0; j < (ssize_t)image->columns; j++)
{
if (GetPixelRed(image,q) == ScaleCharToQuantum(1))
{
SetPixelRed(image,QuantumRange,q);
SetPixelGreen(image,QuantumRange,q);
SetPixelBlue(image,QuantumRange,q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish;
}
}
}
}
Finish:
if (BImgBuff != NULL)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-125', 'CWE-908'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1599'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset,
const int whence,void *user_data)
{
PhotoshopProfile
*profile;
profile=(PhotoshopProfile *) user_data;
switch (whence)
{
case SEEK_SET:
default:
{
if (offset < 0)
return(-1);
profile->offset=offset;
break;
}
case SEEK_CUR:
{
if ((profile->offset+offset) < 0)
return(-1);
profile->offset+=offset;
break;
}
case SEEK_END:
{
if (((MagickOffsetType) profile->length+offset) < 0)
return(-1);
profile->offset=profile->length+offset;
break;
}
}
return(profile->offset);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1602'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: g_vfs_daemon_init (GVfsDaemon *daemon)
{
GError *error;
gint max_threads = 1; /* TODO: handle max threads */
daemon->thread_pool = g_thread_pool_new (job_handler_callback,
daemon,
max_threads,
FALSE, NULL);
/* TODO: verify thread_pool != NULL in a nicer way */
g_assert (daemon->thread_pool != NULL);
g_mutex_init (&daemon->lock);
daemon->mount_counter = 0;
daemon->jobs = NULL;
daemon->registered_paths =
g_hash_table_new_full (g_str_hash, g_str_equal,
g_free, (GDestroyNotify)registered_path_free);
/* This is where we store active client connections so when a new filter is registered,
* we re-register them on all active connections */
daemon->client_connections =
g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, NULL);
daemon->conn = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
g_assert (daemon->conn != NULL);
daemon->daemon_skeleton = gvfs_dbus_daemon_skeleton_new ();
g_signal_connect (daemon->daemon_skeleton, "handle-get-connection", G_CALLBACK (handle_get_connection), daemon);
g_signal_connect (daemon->daemon_skeleton, "handle-cancel", G_CALLBACK (handle_cancel), daemon);
g_signal_connect (daemon->daemon_skeleton, "handle-list-monitor-implementations", G_CALLBACK (handle_list_monitor_implementations), daemon);
error = NULL;
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (daemon->daemon_skeleton),
daemon->conn,
G_VFS_DBUS_DAEMON_PATH,
&error))
{
g_warning ("Error exporting daemon interface: %s (%s, %d)\n",
error->message, g_quark_to_string (error->domain), error->code);
g_error_free (error);
}
daemon->mountable_skeleton = gvfs_dbus_mountable_skeleton_new ();
g_signal_connect (daemon->mountable_skeleton, "handle-mount", G_CALLBACK (daemon_handle_mount), daemon);
error = NULL;
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (daemon->mountable_skeleton),
daemon->conn,
G_VFS_DBUS_MOUNTABLE_PATH,
&error))
{
g_warning ("Error exporting mountable interface: %s (%s, %d)\n",
error->message, g_quark_to_string (error->domain), error->code);
g_error_free (error);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-276'], 'message': 'gvfsdaemon: Check that the connecting client is the same user
Otherwise, an attacker who learns the abstract socket address from
netstat(8) or similar could connect to it and issue D-Bus method
calls.
Signed-off-by: Simon McVittie <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: uint64_t hllCount(struct hllhdr *hdr, int *invalid) {
double m = HLL_REGISTERS;
double E;
int j;
int reghisto[HLL_Q+2] = {0};
/* Compute register histogram */
if (hdr->encoding == HLL_DENSE) {
hllDenseRegHisto(hdr->registers,reghisto);
} else if (hdr->encoding == HLL_SPARSE) {
hllSparseRegHisto(hdr->registers,
sdslen((sds)hdr)-HLL_HDR_SIZE,invalid,reghisto);
} else if (hdr->encoding == HLL_RAW) {
hllRawRegHisto(hdr->registers,reghisto);
} else {
serverPanic("Unknown HyperLogLog encoding in hllCount()");
}
/* Estimate cardinality form register histogram. See:
* "New cardinality estimation algorithms for HyperLogLog sketches"
* Otmar Ertl, arXiv:1702.01284 */
double z = m * hllTau((m-reghisto[HLL_Q+1])/(double)m);
for (j = HLL_Q; j >= 1; --j) {
z += reghisto[j];
z *= 0.5;
}
z += m * hllSigma(reghisto[0]/(double)m);
E = llroundl(HLL_ALPHA_INF*m*m/z);
return (uint64_t) E;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'HyperLogLog: enlarge reghisto variable for safety.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport MagickBooleanType AnnotateImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
char
*p,
primitive[MagickPathExtent],
*text,
**textlist;
DrawInfo
*annotate,
*annotate_info;
GeometryInfo
geometry_info;
MagickBooleanType
status;
PointInfo
offset;
RectangleInfo
geometry;
register ssize_t
i;
TypeMetric
metrics;
size_t
height,
number_lines;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->text == (char *) NULL)
return(MagickFalse);
if (*draw_info->text == '\0')
return(MagickTrue);
annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info);
text=annotate->text;
annotate->text=(char *) NULL;
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
number_lines=1;
for (p=text; *p != '\0'; p++)
if (*p == '\n')
number_lines++;
textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist));
if (textlist == (char **) NULL)
{
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
return(MagickFalse);
}
p=text;
for (i=0; i < number_lines; i++)
{
char
*q;
textlist[i]=p;
for (q=p; *q != '\0'; q++)
if ((*q == '\r') || (*q == '\n'))
break;
if (*q == '\r')
{
*q='\0';
q++;
}
*q='\0';
p=q+1;
}
textlist[i]=(char *) NULL;
SetGeometry(image,&geometry);
SetGeometryInfo(&geometry_info);
if (annotate_info->geometry != (char *) NULL)
{
(void) ParsePageGeometry(image,annotate_info->geometry,&geometry,
exception);
(void) ParseGeometry(annotate_info->geometry,&geometry_info);
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
return(MagickFalse);
}
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
(void) memset(&metrics,0,sizeof(metrics));
for (i=0; textlist[i] != (char *) NULL; i++)
{
if (*textlist[i] == '\0')
continue;
/*
Position text relative to image.
*/
annotate_info->affine.tx=geometry_info.xi-image->page.x;
annotate_info->affine.ty=geometry_info.psi-image->page.y;
(void) CloneString(&annotate->text,textlist[i]);
if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity))
(void) GetTypeMetrics(image,annotate,&metrics,exception);
height=(ssize_t) (metrics.ascent-metrics.descent+
draw_info->interline_spacing+0.5);
switch (annotate->gravity)
{
case UndefinedGravity:
default:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case NorthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent;
break;
}
case NorthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width/2.0;
break;
}
case NorthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+annotate_info->affine.ry*
(metrics.ascent+metrics.descent)-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width;
break;
}
case WestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case CenterGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
break;
}
case EastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+
annotate_info->affine.ry*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case SouthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height-annotate_info->affine.ry*
(number_lines-1.0)*height;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0-
annotate_info->affine.ry*(number_lines-1.0)*height/2.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width-
annotate_info->affine.ry*(number_lines-1.0)*height-1.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
}
switch (annotate->align)
{
case LeftAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case CenterAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0;
break;
}
case RightAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width;
break;
}
default:
break;
}
if (draw_info->undercolor.alpha != TransparentAlpha)
{
DrawInfo
*undercolor_info;
/*
Text box.
*/
undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL);
undercolor_info->fill=draw_info->undercolor;
undercolor_info->affine=draw_info->affine;
undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent;
undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent;
(void) FormatLocaleString(primitive,MagickPathExtent,
"rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height);
(void) CloneString(&undercolor_info->primitive,primitive);
(void) DrawImage(image,undercolor_info,exception);
(void) DestroyDrawInfo(undercolor_info);
}
annotate_info->affine.tx=offset.x;
annotate_info->affine.ty=offset.y;
(void) FormatLocaleString(primitive,MagickPathExtent,"stroke-width %g "
"line 0,0 %g,0",metrics.underline_thickness,metrics.width);
if (annotate->decorate == OverlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+
metrics.descent-metrics.underline_position));
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
else
if (annotate->decorate == UnderlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*
metrics.underline_position);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
/*
Annotate image with text.
*/
status=RenderType(image,annotate,&offset,&metrics,exception);
if (status == MagickFalse)
break;
if (annotate->decorate == LineThroughDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(height+
metrics.underline_position+metrics.descent)/2.0);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
}
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
return(status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1588'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(images,complex_images,images->rows,1L)
#endif
for (y=0; y < (ssize_t) images->rows; y++)
{
register const PixelPacket
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register PixelPacket
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const PixelPacket *) NULL) ||
(Ai == (const PixelPacket *) NULL) ||
(Br == (const PixelPacket *) NULL) ||
(Bi == (const PixelPacket *) NULL) ||
(Cr == (PixelPacket *) NULL) || (Ci == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) images->columns; x++)
{
switch (op)
{
case AddComplexOperator:
{
Cr->red=Ar->red+Br->red;
Ci->red=Ai->red+Bi->red;
Cr->green=Ar->green+Br->green;
Ci->green=Ai->green+Bi->green;
Cr->blue=Ar->blue+Br->blue;
Ci->blue=Ai->blue+Bi->blue;
if (images->matte != MagickFalse)
{
Cr->opacity=Ar->opacity+Br->opacity;
Ci->opacity=Ai->opacity+Bi->opacity;
}
break;
}
case ConjugateComplexOperator:
default:
{
Cr->red=Ar->red;
Ci->red=(-Bi->red);
Cr->green=Ar->green;
Ci->green=(-Bi->green);
Cr->blue=Ar->blue;
Ci->blue=(-Bi->blue);
if (images->matte != MagickFalse)
{
Cr->opacity=Ar->opacity;
Ci->opacity=(-Bi->opacity);
}
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal(Br->red*Br->red+Bi->red*Bi->red+snr);
Cr->red=gamma*(Ar->red*Br->red+Ai->red*Bi->red);
Ci->red=gamma*(Ai->red*Br->red-Ar->red*Bi->red);
gamma=PerceptibleReciprocal(Br->green*Br->green+Bi->green*Bi->green+
snr);
Cr->green=gamma*(Ar->green*Br->green+Ai->green*Bi->green);
Ci->green=gamma*(Ai->green*Br->green-Ar->green*Bi->green);
gamma=PerceptibleReciprocal(Br->blue*Br->blue+Bi->blue*Bi->blue+snr);
Cr->blue=gamma*(Ar->blue*Br->blue+Ai->blue*Bi->blue);
Ci->blue=gamma*(Ai->blue*Br->blue-Ar->blue*Bi->blue);
if (images->matte != MagickFalse)
{
gamma=PerceptibleReciprocal(Br->opacity*Br->opacity+Bi->opacity*
Bi->opacity+snr);
Cr->opacity=gamma*(Ar->opacity*Br->opacity+Ai->opacity*
Bi->opacity);
Ci->opacity=gamma*(Ai->opacity*Br->opacity-Ar->opacity*
Bi->opacity);
}
break;
}
case MagnitudePhaseComplexOperator:
{
Cr->red=sqrt(Ar->red*Ar->red+Ai->red*Ai->red);
Ci->red=atan2(Ai->red,Ar->red)/(2.0*MagickPI)+0.5;
Cr->green=sqrt(Ar->green*Ar->green+Ai->green*Ai->green);
Ci->green=atan2(Ai->green,Ar->green)/(2.0*MagickPI)+0.5;
Cr->blue=sqrt(Ar->blue*Ar->blue+Ai->blue*Ai->blue);
Ci->blue=atan2(Ai->blue,Ar->blue)/(2.0*MagickPI)+0.5;
if (images->matte != MagickFalse)
{
Cr->opacity=sqrt(Ar->opacity*Ar->opacity+Ai->opacity*Ai->opacity);
Ci->opacity=atan2(Ai->opacity,Ar->opacity)/(2.0*MagickPI)+0.5;
}
break;
}
case MultiplyComplexOperator:
{
Cr->red=QuantumScale*(Ar->red*Br->red-Ai->red*Bi->red);
Ci->red=QuantumScale*(Ai->red*Br->red+Ar->red*Bi->red);
Cr->green=QuantumScale*(Ar->green*Br->green-Ai->green*Bi->green);
Ci->green=QuantumScale*(Ai->green*Br->green+Ar->green*Bi->green);
Cr->blue=QuantumScale*(Ar->blue*Br->blue-Ai->blue*Bi->blue);
Ci->blue=QuantumScale*(Ai->blue*Br->blue+Ar->blue*Bi->blue);
if (images->matte != MagickFalse)
{
Cr->opacity=QuantumScale*(Ar->opacity*Br->opacity-Ai->opacity*
Bi->opacity);
Ci->opacity=QuantumScale*(Ai->opacity*Br->opacity+Ar->opacity*
Bi->opacity);
}
break;
}
case RealImaginaryComplexOperator:
{
Cr->red=Ar->red*cos(2.0*MagickPI*(Ai->red-0.5));
Ci->red=Ar->red*sin(2.0*MagickPI*(Ai->red-0.5));
Cr->green=Ar->green*cos(2.0*MagickPI*(Ai->green-0.5));
Ci->green=Ar->green*sin(2.0*MagickPI*(Ai->green-0.5));
Cr->blue=Ar->blue*cos(2.0*MagickPI*(Ai->blue-0.5));
Ci->blue=Ar->blue*sin(2.0*MagickPI*(Ai->blue-0.5));
if (images->matte != MagickFalse)
{
Cr->opacity=Ar->opacity*cos(2.0*MagickPI*(Ai->opacity-0.5));
Ci->opacity=Ar->opacity*sin(2.0*MagickPI*(Ai->opacity-0.5));
}
break;
}
case SubtractComplexOperator:
{
Cr->red=Ar->red-Br->red;
Ci->red=Ai->red-Bi->red;
Cr->green=Ar->green-Br->green;
Ci->green=Ai->green-Bi->green;
Cr->blue=Ar->blue-Br->blue;
Ci->blue=Ai->blue-Bi->blue;
if (images->matte != MagickFalse)
{
Cr->opacity=Ar->opacity-Br->opacity;
Ci->opacity=Ai->opacity-Bi->opacity;
}
break;
}
}
Ar++;
Ai++;
Br++;
Bi++;
Cr++;
Ci++;
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1588'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static unsigned long get_seg_limit(struct pt_regs *regs, int seg_reg_idx)
{
struct desc_struct *desc;
unsigned long limit;
short sel;
sel = get_segment_selector(regs, seg_reg_idx);
if (sel < 0)
return 0;
if (user_64bit_mode(regs) || v8086_mode(regs))
return -1L;
if (!sel)
return 0;
desc = get_desc(sel);
if (!desc)
return 0;
/*
* If the granularity bit is set, the limit is given in multiples
* of 4096. This also means that the 12 least significant bits are
* not tested when checking the segment limits. In practice,
* this means that the segment ends in (limit << 12) + 0xfff.
*/
limit = get_desc_limit(desc);
if (desc->g)
limit = (limit << 12) + 0xfff;
return limit;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'x86/insn-eval: Fix use-after-free access to LDT entry
get_desc() computes a pointer into the LDT while holding a lock that
protects the LDT from being freed, but then drops the lock and returns the
(now potentially dangling) pointer to its caller.
Fix it by giving the caller a copy of the LDT entry instead.
Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor")
Cc: [email protected]
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int insn_get_code_seg_params(struct pt_regs *regs)
{
struct desc_struct *desc;
short sel;
if (v8086_mode(regs))
/* Address and operand size are both 16-bit. */
return INSN_CODE_SEG_PARAMS(2, 2);
sel = get_segment_selector(regs, INAT_SEG_REG_CS);
if (sel < 0)
return sel;
desc = get_desc(sel);
if (!desc)
return -EINVAL;
/*
* The most significant byte of the Type field of the segment descriptor
* determines whether a segment contains data or code. If this is a data
* segment, return error.
*/
if (!(desc->type & BIT(3)))
return -EINVAL;
switch ((desc->l << 1) | desc->d) {
case 0: /*
* Legacy mode. CS.L=0, CS.D=0. Address and operand size are
* both 16-bit.
*/
return INSN_CODE_SEG_PARAMS(2, 2);
case 1: /*
* Legacy mode. CS.L=0, CS.D=1. Address and operand size are
* both 32-bit.
*/
return INSN_CODE_SEG_PARAMS(4, 4);
case 2: /*
* IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit;
* operand size is 32-bit.
*/
return INSN_CODE_SEG_PARAMS(4, 8);
case 3: /* Invalid setting. CS.L=1, CS.D=1 */
/* fall through */
default:
return -EINVAL;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'x86/insn-eval: Fix use-after-free access to LDT entry
get_desc() computes a pointer into the LDT while holding a lock that
protects the LDT from being freed, but then drops the lock and returns the
(now potentially dangling) pointer to its caller.
Fix it by giving the caller a copy of the LDT entry instead.
Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor")
Cc: [email protected]
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int extract_or_test_files(__G) /* return PK-type error code */
__GDEF
{
unsigned i, j;
zoff_t cd_bufstart;
uch *cd_inptr;
int cd_incnt;
ulg filnum=0L, blknum=0L;
int reached_end;
#ifndef SFX
int no_endsig_found;
#endif
int error, error_in_archive=PK_COOL;
int *fn_matched=NULL, *xn_matched=NULL;
zucn_t members_processed;
ulg num_skipped=0L, num_bad_pwd=0L;
zoff_t old_extra_bytes = 0L;
#ifdef SET_DIR_ATTRIB
unsigned num_dirs=0;
direntry *dirlist=(direntry *)NULL, **sorted_dirlist=(direntry **)NULL;
#endif
/*
* First, two general initializations are applied. These have been moved
* here from process_zipfiles() because they are only needed for accessing
* and/or extracting the data content of the zip archive.
*/
/* a) initialize the CRC table pointer (once) */
if (CRC_32_TAB == NULL) {
if ((CRC_32_TAB = get_crc_table()) == NULL) {
return PK_MEM;
}
}
#if (!defined(SFX) || defined(SFX_EXDIR))
/* b) check out if specified extraction root directory exists */
if (uO.exdir != (char *)NULL && G.extract_flag) {
G.create_dirs = !uO.fflag;
if ((error = checkdir(__G__ uO.exdir, ROOT)) > MPN_INF_SKIP) {
/* out of memory, or file in way */
return (error == MPN_NOMEM ? PK_MEM : PK_ERR);
}
}
#endif /* !SFX || SFX_EXDIR */
/*---------------------------------------------------------------------------
The basic idea of this function is as follows. Since the central di-
rectory lies at the end of the zipfile and the member files lie at the
beginning or middle or wherever, it is not very desirable to simply
read a central directory entry, jump to the member and extract it, and
then jump back to the central directory. In the case of a large zipfile
this would lead to a whole lot of disk-grinding, especially if each mem-
ber file is small. Instead, we read from the central directory the per-
tinent information for a block of files, then go extract/test the whole
block. Thus this routine contains two small(er) loops within a very
large outer loop: the first of the small ones reads a block of files
from the central directory; the second extracts or tests each file; and
the outer one loops over blocks. There's some file-pointer positioning
stuff in between, but that's about it. Btw, it's because of this jump-
ing around that we can afford to be lenient if an error occurs in one of
the member files: we should still be able to go find the other members,
since we know the offset of each from the beginning of the zipfile.
---------------------------------------------------------------------------*/
G.pInfo = G.info;
#if CRYPT
G.newzip = TRUE;
#endif
#ifndef SFX
G.reported_backslash = FALSE;
#endif
/* malloc space for check on unmatched filespecs (OK if one or both NULL) */
if (G.filespecs > 0 &&
(fn_matched=(int *)malloc(G.filespecs*sizeof(int))) != (int *)NULL)
for (i = 0; i < G.filespecs; ++i)
fn_matched[i] = FALSE;
if (G.xfilespecs > 0 &&
(xn_matched=(int *)malloc(G.xfilespecs*sizeof(int))) != (int *)NULL)
for (i = 0; i < G.xfilespecs; ++i)
xn_matched[i] = FALSE;
/*---------------------------------------------------------------------------
Begin main loop over blocks of member files. We know the entire central
directory is on this disk: we would not have any of this information un-
less the end-of-central-directory record was on this disk, and we would
not have gotten to this routine unless this is also the disk on which
the central directory starts. In practice, this had better be the ONLY
disk in the archive, but we'll add multi-disk support soon.
---------------------------------------------------------------------------*/
members_processed = 0;
#ifndef SFX
no_endsig_found = FALSE;
#endif
reached_end = FALSE;
while (!reached_end) {
j = 0;
#ifdef AMIGA
memzero(G.filenotes, DIR_BLKSIZ * sizeof(char *));
#endif
/*
* Loop through files in central directory, storing offsets, file
* attributes, case-conversion and text-conversion flags until block
* size is reached.
*/
while ((j < DIR_BLKSIZ)) {
G.pInfo = &G.info[j];
if (readbuf(__G__ G.sig, 4) == 0) {
error_in_archive = PK_EOF;
reached_end = TRUE; /* ...so no more left to do */
break;
}
if (memcmp(G.sig, central_hdr_sig, 4)) { /* is it a new entry? */
/* no new central directory entry
* -> is the number of processed entries compatible with the
* number of entries as stored in the end_central record?
*/
if ((members_processed
& (G.ecrec.have_ecr64 ? MASK_ZUCN64 : MASK_ZUCN16))
== G.ecrec.total_entries_central_dir) {
#ifndef SFX
/* yes, so look if we ARE back at the end_central record
*/
no_endsig_found =
( (memcmp(G.sig,
(G.ecrec.have_ecr64 ?
end_central64_sig : end_central_sig),
4) != 0)
&& (!G.ecrec.is_zip64_archive)
&& (memcmp(G.sig, end_central_sig, 4) != 0)
);
#endif /* !SFX */
} else {
/* no; we have found an error in the central directory
* -> report it and stop searching for more Zip entries
*/
Info(slide, 0x401, ((char *)slide,
LoadFarString(CentSigMsg), j + blknum*DIR_BLKSIZ + 1));
Info(slide, 0x401, ((char *)slide,
LoadFarString(ReportMsg)));
error_in_archive = PK_BADERR;
}
reached_end = TRUE; /* ...so no more left to do */
break;
}
/* process_cdir_file_hdr() sets pInfo->hostnum, pInfo->lcflag */
if ((error = process_cdir_file_hdr(__G)) != PK_COOL) {
error_in_archive = error; /* only PK_EOF defined */
reached_end = TRUE; /* ...so no more left to do */
break;
}
if ((error = do_string(__G__ G.crec.filename_length, DS_FN)) !=
PK_COOL)
{
if (error > error_in_archive)
error_in_archive = error;
if (error > PK_WARN) { /* fatal: no more left to do */
Info(slide, 0x401, ((char *)slide,
LoadFarString(FilNamMsg),
FnFilter1(G.filename), "central"));
reached_end = TRUE;
break;
}
}
if ((error = do_string(__G__ G.crec.extra_field_length,
EXTRA_FIELD)) != 0)
{
if (error > error_in_archive)
error_in_archive = error;
if (error > PK_WARN) { /* fatal */
Info(slide, 0x401, ((char *)slide,
LoadFarString(ExtFieldMsg),
FnFilter1(G.filename), "central"));
reached_end = TRUE;
break;
}
}
#ifdef AMIGA
G.filenote_slot = j;
if ((error = do_string(__G__ G.crec.file_comment_length,
uO.N_flag ? FILENOTE : SKIP)) != PK_COOL)
#else
if ((error = do_string(__G__ G.crec.file_comment_length, SKIP))
!= PK_COOL)
#endif
{
if (error > error_in_archive)
error_in_archive = error;
if (error > PK_WARN) { /* fatal */
Info(slide, 0x421, ((char *)slide,
LoadFarString(BadFileCommLength),
FnFilter1(G.filename)));
reached_end = TRUE;
break;
}
}
if (G.process_all_files) {
if (store_info(__G))
++j; /* file is OK; info[] stored; continue with next */
else
++num_skipped;
} else {
int do_this_file;
if (G.filespecs == 0)
do_this_file = TRUE;
else { /* check if this entry matches an `include' argument */
do_this_file = FALSE;
for (i = 0; i < G.filespecs; i++)
if (match(G.filename, G.pfnames[i], uO.C_flag WISEP)) {
do_this_file = TRUE; /* ^-- ignore case or not? */
if (fn_matched)
fn_matched[i] = TRUE;
break; /* found match, so stop looping */
}
}
if (do_this_file) { /* check if this is an excluded file */
for (i = 0; i < G.xfilespecs; i++)
if (match(G.filename, G.pxnames[i], uO.C_flag WISEP)) {
do_this_file = FALSE; /* ^-- ignore case or not? */
if (xn_matched)
xn_matched[i] = TRUE;
break;
}
}
if (do_this_file) {
if (store_info(__G))
++j; /* file is OK */
else
++num_skipped; /* unsupp. compression or encryption */
}
} /* end if (process_all_files) */
members_processed++;
} /* end while-loop (adding files to current block) */
/* save position in central directory so can come back later */
cd_bufstart = G.cur_zipfile_bufstart;
cd_inptr = G.inptr;
cd_incnt = G.incnt;
/*-----------------------------------------------------------------------
Second loop: process files in current block, extracting or testing
each one.
-----------------------------------------------------------------------*/
error = extract_or_test_entrylist(__G__ j,
&filnum, &num_bad_pwd, &old_extra_bytes,
#ifdef SET_DIR_ATTRIB
&num_dirs, &dirlist,
#endif
error_in_archive);
if (error != PK_COOL) {
if (error > error_in_archive)
error_in_archive = error;
/* ...and keep going (unless disk full or user break) */
if (G.disk_full > 1 || error_in_archive == IZ_CTRLC) {
/* clear reached_end to signal premature stop ... */
reached_end = FALSE;
/* ... and cancel scanning the central directory */
break;
}
}
/*
* Jump back to where we were in the central directory, then go and do
* the next batch of files.
*/
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, cd_bufstart, SEEK_SET);
G.cur_zipfile_bufstart = zftello(G.zipfd);
#else /* !USE_STRM_INPUT */
G.cur_zipfile_bufstart =
zlseek(G.zipfd, cd_bufstart, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
read(G.zipfd, (char *)G.inbuf, INBUFSIZ); /* been here before... */
G.inptr = cd_inptr;
G.incnt = cd_incnt;
++blknum;
#ifdef TEST
printf("\ncd_bufstart = %ld (%.8lXh)\n", cd_bufstart, cd_bufstart);
printf("cur_zipfile_bufstart = %ld (%.8lXh)\n", cur_zipfile_bufstart,
cur_zipfile_bufstart);
printf("inptr-inbuf = %d\n", G.inptr-G.inbuf);
printf("incnt = %d\n\n", G.incnt);
#endif
} /* end while-loop (blocks of files in central directory) */
/*---------------------------------------------------------------------------
Process the list of deferred symlink extractions and finish up
the symbolic links.
---------------------------------------------------------------------------*/
#ifdef SYMLINKS
if (G.slink_last != NULL) {
if (QCOND2)
Info(slide, 0, ((char *)slide, LoadFarString(SymLnkDeferred)));
while (G.slink_head != NULL) {
set_deferred_symlink(__G__ G.slink_head);
/* remove the processed entry from the chain and free its memory */
G.slink_last = G.slink_head;
G.slink_head = G.slink_last->next;
free(G.slink_last);
}
G.slink_last = NULL;
}
#endif /* SYMLINKS */
/*---------------------------------------------------------------------------
Go back through saved list of directories, sort and set times/perms/UIDs
and GIDs from the deepest level on up.
---------------------------------------------------------------------------*/
#ifdef SET_DIR_ATTRIB
if (num_dirs > 0) {
sorted_dirlist = (direntry **)malloc(num_dirs*sizeof(direntry *));
if (sorted_dirlist == (direntry **)NULL) {
Info(slide, 0x401, ((char *)slide,
LoadFarString(DirlistSortNoMem)));
while (dirlist != (direntry *)NULL) {
direntry *d = dirlist;
dirlist = dirlist->next;
free(d);
}
} else {
ulg ndirs_fail = 0;
if (num_dirs == 1)
sorted_dirlist[0] = dirlist;
else {
for (i = 0; i < num_dirs; ++i) {
sorted_dirlist[i] = dirlist;
dirlist = dirlist->next;
}
qsort((char *)sorted_dirlist, num_dirs, sizeof(direntry *),
dircomp);
}
Trace((stderr, "setting directory times/perms/attributes\n"));
for (i = 0; i < num_dirs; ++i) {
direntry *d = sorted_dirlist[i];
Trace((stderr, "dir = %s\n", d->fn));
if ((error = set_direc_attribs(__G__ d)) != PK_OK) {
ndirs_fail++;
Info(slide, 0x201, ((char *)slide,
LoadFarString(DirlistSetAttrFailed), d->fn));
if (!error_in_archive)
error_in_archive = error;
}
free(d);
}
free(sorted_dirlist);
if (!uO.tflag && QCOND2) {
if (ndirs_fail > 0)
Info(slide, 0, ((char *)slide,
LoadFarString(DirlistFailAttrSum), ndirs_fail));
}
}
}
#endif /* SET_DIR_ATTRIB */
/*---------------------------------------------------------------------------
Check for unmatched filespecs on command line and print warning if any
found. Free allocated memory. (But suppress check when central dir
scan was interrupted prematurely.)
---------------------------------------------------------------------------*/
if (fn_matched) {
if (reached_end) for (i = 0; i < G.filespecs; ++i)
if (!fn_matched[i]) {
#ifdef DLL
if (!G.redirect_data && !G.redirect_text)
Info(slide, 0x401, ((char *)slide,
LoadFarString(FilenameNotMatched), G.pfnames[i]));
else
setFileNotFound(__G);
#else
Info(slide, 1, ((char *)slide,
LoadFarString(FilenameNotMatched), G.pfnames[i]));
#endif
if (error_in_archive <= PK_WARN)
error_in_archive = PK_FIND; /* some files not found */
}
free((zvoid *)fn_matched);
}
if (xn_matched) {
if (reached_end) for (i = 0; i < G.xfilespecs; ++i)
if (!xn_matched[i])
Info(slide, 0x401, ((char *)slide,
LoadFarString(ExclFilenameNotMatched), G.pxnames[i]));
free((zvoid *)xn_matched);
}
/*---------------------------------------------------------------------------
Now, all locally allocated memory has been released. When the central
directory processing has been interrupted prematurely, it is safe to
return immediately. All completeness checks and summary messages are
skipped in this case.
---------------------------------------------------------------------------*/
if (!reached_end)
return error_in_archive;
/*---------------------------------------------------------------------------
Double-check that we're back at the end-of-central-directory record, and
print quick summary of results, if we were just testing the archive. We
send the summary to stdout so that people doing the testing in the back-
ground and redirecting to a file can just do a "tail" on the output file.
---------------------------------------------------------------------------*/
#ifndef SFX
if (no_endsig_found) { /* just to make sure */
Info(slide, 0x401, ((char *)slide, LoadFarString(EndSigMsg)));
Info(slide, 0x401, ((char *)slide, LoadFarString(ReportMsg)));
if (!error_in_archive) /* don't overwrite stronger error */
error_in_archive = PK_WARN;
}
#endif /* !SFX */
if (uO.tflag) {
ulg num = filnum - num_bad_pwd;
if (uO.qflag < 2) { /* GRR 930710: was (uO.qflag == 1) */
if (error_in_archive)
Info(slide, 0, ((char *)slide, LoadFarString(ErrorInArchive),
(error_in_archive == PK_WARN)? "warning-" : "", G.zipfn));
else if (num == 0L)
Info(slide, 0, ((char *)slide, LoadFarString(ZeroFilesTested),
G.zipfn));
else if (G.process_all_files && (num_skipped+num_bad_pwd == 0L))
Info(slide, 0, ((char *)slide, LoadFarString(NoErrInCompData),
G.zipfn));
else
Info(slide, 0, ((char *)slide, LoadFarString(NoErrInTestedFiles)
, G.zipfn, num, (num==1L)? "":"s"));
if (num_skipped > 0L)
Info(slide, 0, ((char *)slide, LoadFarString(FilesSkipped),
num_skipped, (num_skipped==1L)? "":"s"));
#if CRYPT
if (num_bad_pwd > 0L)
Info(slide, 0, ((char *)slide, LoadFarString(FilesSkipBadPasswd)
, num_bad_pwd, (num_bad_pwd==1L)? "":"s"));
#endif /* CRYPT */
}
}
/* give warning if files not tested or extracted (first condition can still
* happen if zipfile is empty and no files specified on command line) */
if ((filnum == 0) && error_in_archive <= PK_WARN) {
if (num_skipped > 0L)
error_in_archive = IZ_UNSUP; /* unsupport. compression/encryption */
else
error_in_archive = PK_FIND; /* no files found at all */
}
#if CRYPT
else if ((filnum == num_bad_pwd) && error_in_archive <= PK_WARN)
error_in_archive = IZ_BADPWD; /* bad passwd => all files skipped */
#endif
else if ((num_skipped > 0L) && error_in_archive <= PK_WARN)
error_in_archive = IZ_UNSUP; /* was PK_WARN; Jean-loup complained */
#if CRYPT
else if ((num_bad_pwd > 0L) && !error_in_archive)
error_in_archive = PK_WARN;
#endif
return error_in_archive;
} /* end function extract_or_test_files() */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400'], 'message': 'Detect and reject a zip bomb using overlapped entries.
This detects an invalid zip file that has at least one entry that
overlaps with another entry or with the central directory to the
end of the file. A Fifield zip bomb uses overlapped local entries
to vastly increase the potential inflation ratio. Such an invalid
zip file is rejected.
See https://www.bamsoftware.com/hacks/zipbomb/ for David Fifield's
analysis, construction, and examples of such zip bombs.
The detection maintains a list of covered spans of the zip files
so far, where the central directory to the end of the file and any
bytes preceding the first entry at zip file offset zero are
considered covered initially. Then as each entry is decompressed
or tested, it is considered covered. When a new entry is about to
be processed, its initial offset is checked to see if it is
contained by a covered span. If so, the zip file is rejected as
invalid.
This commit depends on a preceding commit: "Fix bug in
undefer_input() that misplaced the input state."'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: Uz_Globs *globalsCtor()
{
#ifdef REENTRANT
Uz_Globs *pG = (Uz_Globs *)malloc(sizeof(Uz_Globs));
if (!pG)
return (Uz_Globs *)NULL;
#endif /* REENTRANT */
/* for REENTRANT version, G is defined as (*pG) */
memzero(&G, sizeof(Uz_Globs));
#ifndef FUNZIP
#ifdef CMS_MVS
uO.aflag=1;
uO.C_flag=1;
#endif
#ifdef TANDEM
uO.aflag=1; /* default to '-a' auto create Text Files as type 101 */
#endif
#ifdef VMS
# if (!defined(NO_TIMESTAMPS))
uO.D_flag=1; /* default to '-D', no restoration of dir timestamps */
# endif
#endif
uO.lflag=(-1);
G.wildzipfn = "";
G.pfnames = (char **)fnames;
G.pxnames = (char **)&fnames[1];
G.pInfo = G.info;
G.sol = TRUE; /* at start of line */
G.message = UzpMessagePrnt;
G.input = UzpInput; /* not used by anyone at the moment... */
#if defined(WINDLL) || defined(MACOS)
G.mpause = NULL; /* has scrollbars: no need for pausing */
#else
G.mpause = UzpMorePause;
#endif
G.decr_passwd = UzpPassword;
#endif /* !FUNZIP */
#if (!defined(DOS_FLX_H68_NLM_OS2_W32) && !defined(AMIGA) && !defined(RISCOS))
#if (!defined(MACOS) && !defined(ATARI) && !defined(VMS))
G.echofd = -1;
#endif /* !(MACOS || ATARI || VMS) */
#endif /* !(DOS_FLX_H68_NLM_OS2_W32 || AMIGA || RISCOS) */
#ifdef SYSTEM_SPECIFIC_CTOR
SYSTEM_SPECIFIC_CTOR(__G);
#endif
#ifdef REENTRANT
#ifdef USETHREADID
registerGlobalPointer(__G);
#else
GG = &G;
#endif /* ?USETHREADID */
#endif /* REENTRANT */
return &G;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400'], 'message': 'Detect and reject a zip bomb using overlapped entries.
This detects an invalid zip file that has at least one entry that
overlaps with another entry or with the central directory to the
end of the file. A Fifield zip bomb uses overlapped local entries
to vastly increase the potential inflation ratio. Such an invalid
zip file is rejected.
See https://www.bamsoftware.com/hacks/zipbomb/ for David Fifield's
analysis, construction, and examples of such zip bombs.
The detection maintains a list of covered spans of the zip files
so far, where the central directory to the end of the file and any
bytes preceding the first entry at zip file offset zero are
considered covered initially. Then as each entry is decompressed
or tested, it is considered covered. When a new entry is about to
be processed, its initial offset is checked to see if it is
contained by a covered span. If so, the zip file is rejected as
invalid.
This commit depends on a preceding commit: "Fix bug in
undefer_input() that misplaced the input state."'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int do_seekable(__G__ lastchance) /* return PK-type error code */
__GDEF
int lastchance;
{
#ifndef SFX
/* static int no_ecrec = FALSE; SKM: moved to globals.h */
int maybe_exe=FALSE;
int too_weird_to_continue=FALSE;
#ifdef TIMESTAMP
time_t uxstamp;
ulg nmember = 0L;
#endif
#endif
int error=0, error_in_archive;
/*---------------------------------------------------------------------------
Open the zipfile for reading in BINARY mode to prevent CR/LF translation,
which would corrupt the bit streams.
---------------------------------------------------------------------------*/
if (SSTAT(G.zipfn, &G.statbuf) ||
#ifdef THEOS
(error = S_ISLIB(G.statbuf.st_mode)) != 0 ||
#endif
(error = S_ISDIR(G.statbuf.st_mode)) != 0)
{
#ifndef SFX
if (lastchance && (uO.qflag < 3)) {
#if defined(UNIX) || defined(QDOS)
if (G.no_ecrec)
Info(slide, 1, ((char *)slide,
LoadFarString(CannotFindZipfileDirMsg),
LoadFarStringSmall((uO.zipinfo_mode ? Zipnfo : Unzip)),
G.wildzipfn, uO.zipinfo_mode? " " : "", G.wildzipfn,
G.zipfn));
else
Info(slide, 1, ((char *)slide,
LoadFarString(CannotFindEitherZipfile),
LoadFarStringSmall((uO.zipinfo_mode ? Zipnfo : Unzip)),
G.wildzipfn, G.wildzipfn, G.zipfn));
#else /* !(UNIX || QDOS) */
if (G.no_ecrec)
Info(slide, 0x401, ((char *)slide,
LoadFarString(CannotFindZipfileDirMsg),
LoadFarStringSmall((uO.zipinfo_mode ? Zipnfo : Unzip)),
G.wildzipfn, uO.zipinfo_mode? " " : "", G.zipfn));
else
#ifdef VMS
Info(slide, 0x401, ((char *)slide,
LoadFarString(CannotFindEitherZipfile),
LoadFarStringSmall((uO.zipinfo_mode ? Zipnfo : Unzip)),
G.wildzipfn,
(*G.zipfn ? G.zipfn : vms_msg_text())));
#else /* !VMS */
Info(slide, 0x401, ((char *)slide,
LoadFarString(CannotFindEitherZipfile),
LoadFarStringSmall((uO.zipinfo_mode ? Zipnfo : Unzip)),
G.wildzipfn, G.zipfn));
#endif /* ?VMS */
#endif /* ?(UNIX || QDOS) */
}
#endif /* !SFX */
return error? IZ_DIR : PK_NOZIP;
}
G.ziplen = G.statbuf.st_size;
#ifndef SFX
#if defined(UNIX) || defined(DOS_OS2_W32) || defined(THEOS)
if (G.statbuf.st_mode & S_IEXEC) /* no extension on Unix exes: might */
maybe_exe = TRUE; /* find unzip, not unzip.zip; etc. */
#endif
#endif /* !SFX */
#ifdef VMS
if (check_format(__G)) /* check for variable-length format */
return PK_ERR;
#endif
if (open_input_file(__G)) /* this should never happen, given */
return PK_NOZIP; /* the stat() test above, but... */
#ifdef DO_SAFECHECK_2GB
/* Need more care: Do not trust the size returned by stat() but
determine it by reading beyond the end of the file. */
G.ziplen = file_size(G.zipfd);
if (G.ziplen == EOF) {
Info(slide, 0x401, ((char *)slide, LoadFarString(ZipfileTooBig)));
/*
printf(
" We need a better error message for: 64-bit file, 32-bit program.\n");
*/
CLOSE_INFILE();
return IZ_ERRBF;
}
#endif /* DO_SAFECHECK_2GB */
/*---------------------------------------------------------------------------
Find and process the end-of-central-directory header. UnZip need only
check last 65557 bytes of zipfile: comment may be up to 65535, end-of-
central-directory record is 18 bytes, and signature itself is 4 bytes;
add some to allow for appended garbage. Since ZipInfo is often used as
a debugging tool, search the whole zipfile if zipinfo_mode is true.
---------------------------------------------------------------------------*/
G.cur_zipfile_bufstart = 0;
G.inptr = G.inbuf;
#if ((!defined(WINDLL) && !defined(SFX)) || !defined(NO_ZIPINFO))
# if (!defined(WINDLL) && !defined(SFX))
if ( (!uO.zipinfo_mode && !uO.qflag
# ifdef TIMESTAMP
&& !uO.T_flag
# endif
)
# ifndef NO_ZIPINFO
|| (uO.zipinfo_mode && uO.hflag)
# endif
)
# else /* not (!WINDLL && !SFX) ==> !NO_ZIPINFO !! */
if (uO.zipinfo_mode && uO.hflag)
# endif /* if..else..: (!WINDLL && !SFX) */
# ifdef WIN32 /* Win32 console may require codepage conversion for G.zipfn */
Info(slide, 0, ((char *)slide, LoadFarString(LogInitline),
FnFilter1(G.zipfn)));
# else
Info(slide, 0, ((char *)slide, LoadFarString(LogInitline), G.zipfn));
# endif
#endif /* (!WINDLL && !SFX) || !NO_ZIPINFO */
if ( (error_in_archive = find_ecrec(__G__
#ifndef NO_ZIPINFO
uO.zipinfo_mode ? G.ziplen :
#endif
MIN(G.ziplen, 66000L)))
> PK_WARN )
{
CLOSE_INFILE();
#ifdef SFX
++lastchance; /* avoid picky compiler warnings */
return error_in_archive;
#else
if (maybe_exe)
Info(slide, 0x401, ((char *)slide, LoadFarString(MaybeExe),
G.zipfn));
if (lastchance)
return error_in_archive;
else {
G.no_ecrec = TRUE; /* assume we found wrong file: e.g., */
return PK_NOZIP; /* unzip instead of unzip.zip */
}
#endif /* ?SFX */
}
if ((uO.zflag > 0) && !uO.zipinfo_mode) { /* unzip: zflag = comment ONLY */
CLOSE_INFILE();
return error_in_archive;
}
/*---------------------------------------------------------------------------
Test the end-of-central-directory info for incompatibilities (multi-disk
archives) or inconsistencies (missing or extra bytes in zipfile).
---------------------------------------------------------------------------*/
#ifdef NO_MULTIPART
error = !uO.zipinfo_mode && (G.ecrec.number_this_disk == 1) &&
(G.ecrec.num_disk_start_cdir == 1);
#else
error = !uO.zipinfo_mode && (G.ecrec.number_this_disk != 0);
#endif
#ifndef SFX
if (uO.zipinfo_mode &&
G.ecrec.number_this_disk != G.ecrec.num_disk_start_cdir)
{
if (G.ecrec.number_this_disk > G.ecrec.num_disk_start_cdir) {
Info(slide, 0x401, ((char *)slide,
LoadFarString(CentDirNotInZipMsg), G.zipfn,
(ulg)G.ecrec.number_this_disk,
(ulg)G.ecrec.num_disk_start_cdir));
error_in_archive = PK_FIND;
too_weird_to_continue = TRUE;
} else {
Info(slide, 0x401, ((char *)slide,
LoadFarString(EndCentDirBogus), G.zipfn,
(ulg)G.ecrec.number_this_disk,
(ulg)G.ecrec.num_disk_start_cdir));
error_in_archive = PK_WARN;
}
#ifdef NO_MULTIPART /* concatenation of multiple parts works in some cases */
} else if (!uO.zipinfo_mode && !error && G.ecrec.number_this_disk != 0) {
Info(slide, 0x401, ((char *)slide, LoadFarString(NoMultiDiskArcSupport),
G.zipfn));
error_in_archive = PK_FIND;
too_weird_to_continue = TRUE;
#endif
}
if (!too_weird_to_continue) { /* (relatively) normal zipfile: go for it */
if (error) {
Info(slide, 0x401, ((char *)slide, LoadFarString(MaybePakBug),
G.zipfn));
error_in_archive = PK_WARN;
}
#endif /* !SFX */
if ((G.extra_bytes = G.real_ecrec_offset-G.expect_ecrec_offset) <
(zoff_t)0)
{
Info(slide, 0x401, ((char *)slide, LoadFarString(MissingBytes),
G.zipfn, FmZofft((-G.extra_bytes), NULL, NULL)));
error_in_archive = PK_ERR;
} else if (G.extra_bytes > 0) {
if ((G.ecrec.offset_start_central_directory == 0) &&
(G.ecrec.size_central_directory != 0)) /* zip 1.5 -go bug */
{
Info(slide, 0x401, ((char *)slide,
LoadFarString(NullCentDirOffset), G.zipfn));
G.ecrec.offset_start_central_directory = G.extra_bytes;
G.extra_bytes = 0;
error_in_archive = PK_ERR;
}
#ifndef SFX
else {
Info(slide, 0x401, ((char *)slide,
LoadFarString(ExtraBytesAtStart), G.zipfn,
FmZofft(G.extra_bytes, NULL, NULL),
(G.extra_bytes == 1)? "":"s"));
error_in_archive = PK_WARN;
}
#endif /* !SFX */
}
/*-----------------------------------------------------------------------
Check for empty zipfile and exit now if so.
-----------------------------------------------------------------------*/
if (G.expect_ecrec_offset==0L && G.ecrec.size_central_directory==0) {
if (uO.zipinfo_mode)
Info(slide, 0, ((char *)slide, "%sEmpty zipfile.\n",
uO.lflag>9? "\n " : ""));
else
Info(slide, 0x401, ((char *)slide, LoadFarString(ZipfileEmpty),
G.zipfn));
CLOSE_INFILE();
return (error_in_archive > PK_WARN)? error_in_archive : PK_WARN;
}
/*-----------------------------------------------------------------------
Compensate for missing or extra bytes, and seek to where the start
of central directory should be. If header not found, uncompensate
and try again (necessary for at least some Atari archives created
with STZip, as well as archives created by J.H. Holm's ZIPSPLIT 1.1).
-----------------------------------------------------------------------*/
error = seek_zipf(__G__ G.ecrec.offset_start_central_directory);
if (error == PK_BADERR) {
CLOSE_INFILE();
return PK_BADERR;
}
#ifdef OLD_SEEK_TEST
if (error != PK_OK || readbuf(__G__ G.sig, 4) == 0) {
CLOSE_INFILE();
return PK_ERR; /* file may be locked, or possibly disk error(?) */
}
if (memcmp(G.sig, central_hdr_sig, 4))
#else
if ((error != PK_OK) || (readbuf(__G__ G.sig, 4) == 0) ||
memcmp(G.sig, central_hdr_sig, 4))
#endif
{
#ifndef SFX
zoff_t tmp = G.extra_bytes;
#endif
G.extra_bytes = 0;
error = seek_zipf(__G__ G.ecrec.offset_start_central_directory);
if ((error != PK_OK) || (readbuf(__G__ G.sig, 4) == 0) ||
memcmp(G.sig, central_hdr_sig, 4))
{
if (error != PK_BADERR)
Info(slide, 0x401, ((char *)slide,
LoadFarString(CentDirStartNotFound), G.zipfn,
LoadFarStringSmall(ReportMsg)));
CLOSE_INFILE();
return (error != PK_OK ? error : PK_BADERR);
}
#ifndef SFX
Info(slide, 0x401, ((char *)slide, LoadFarString(CentDirTooLong),
G.zipfn, FmZofft((-tmp), NULL, NULL)));
#endif
error_in_archive = PK_ERR;
}
/*-----------------------------------------------------------------------
Seek to the start of the central directory one last time, since we
have just read the first entry's signature bytes; then list, extract
or test member files as instructed, and close the zipfile.
-----------------------------------------------------------------------*/
error = seek_zipf(__G__ G.ecrec.offset_start_central_directory);
if (error != PK_OK) {
CLOSE_INFILE();
return error;
}
Trace((stderr, "about to extract/list files (error = %d)\n",
error_in_archive));
#ifdef DLL
/* G.fValidate is used only to look at an archive to see if
it appears to be a valid archive. There is no interest
in what the archive contains, nor in validating that the
entries in the archive are in good condition. This is
currently used only in the Windows DLLs for purposes of
checking archives within an archive to determine whether
or not to display the inner archives.
*/
if (!G.fValidate)
#endif
{
#ifndef NO_ZIPINFO
if (uO.zipinfo_mode)
error = zipinfo(__G); /* ZIPINFO 'EM */
else
#endif
#ifndef SFX
#ifdef TIMESTAMP
if (uO.T_flag)
error = get_time_stamp(__G__ &uxstamp, &nmember);
else
#endif
if (uO.vflag && !uO.tflag && !uO.cflag)
error = list_files(__G); /* LIST 'EM */
else
#endif /* !SFX */
error = extract_or_test_files(__G); /* EXTRACT OR TEST 'EM */
Trace((stderr, "done with extract/list files (error = %d)\n",
error));
}
if (error > error_in_archive) /* don't overwrite stronger error */
error_in_archive = error; /* with (for example) a warning */
#ifndef SFX
} /* end if (!too_weird_to_continue) */
#endif
CLOSE_INFILE();
#ifdef TIMESTAMP
if (uO.T_flag && !uO.zipinfo_mode && (nmember > 0L)) {
# ifdef WIN32
if (stamp_file(__G__ G.zipfn, uxstamp)) { /* TIME-STAMP 'EM */
# else
if (stamp_file(G.zipfn, uxstamp)) { /* TIME-STAMP 'EM */
# endif
if (uO.qflag < 3)
Info(slide, 0x201, ((char *)slide,
LoadFarString(ZipTimeStampFailed), G.zipfn));
if (error_in_archive < PK_WARN)
error_in_archive = PK_WARN;
} else {
if (!uO.qflag)
Info(slide, 0, ((char *)slide,
LoadFarString(ZipTimeStampSuccess), G.zipfn));
}
}
#endif
return error_in_archive;
} /* end function do_seekable() */
#ifdef DO_SAFECHECK_2GB
/************************/
/* Function file_size() */
/************************/
/* File size determination which does not mislead for large files in a
small-file program. Probably should be somewhere else.
The file has to be opened previously
*/
#ifdef USE_STRM_INPUT
static zoff_t file_size(file)
FILE *file;
{
int sts;
size_t siz;
#else /* !USE_STRM_INPUT */
static zoff_t file_size(fh)
int fh;
{
int siz;
#endif /* ?USE_STRM_INPUT */
zoff_t ofs;
char waste[4];
#ifdef USE_STRM_INPUT
/* Seek to actual EOF. */
sts = zfseeko(file, 0, SEEK_END);
if (sts != 0) {
/* fseeko() failed. (Unlikely.) */
ofs = EOF;
} else {
/* Get apparent offset at EOF. */
ofs = zftello(file);
if (ofs < 0) {
/* Offset negative (overflow). File too big. */
ofs = EOF;
} else {
/* Seek to apparent EOF offset.
Won't be at actual EOF if offset was truncated.
*/
sts = zfseeko(file, ofs, SEEK_SET);
if (sts != 0) {
/* fseeko() failed. (Unlikely.) */
ofs = EOF;
} else {
/* Read a byte at apparent EOF. Should set EOF flag. */
siz = fread(waste, 1, 1, file);
if (feof(file) == 0) {
/* Not at EOF, but should be. File too big. */
ofs = EOF;
}
}
}
}
#else /* !USE_STRM_INPUT */
/* Seek to actual EOF. */
ofs = zlseek(fh, 0, SEEK_END);
if (ofs == (zoff_t) -1) {
/* zlseek() failed. (Unlikely.) */
ofs = EOF;
} else if (ofs < 0) {
/* Offset negative (overflow). File too big. */
ofs = EOF;
} else {
/* Seek to apparent EOF offset.
Won't be at actual EOF if offset was truncated.
*/
ofs = zlseek(fh, ofs, SEEK_SET);
if (ofs == (zoff_t) -1) {
/* zlseek() failed. (Unlikely.) */
ofs = EOF;
} else {
/* Read a byte at apparent EOF. Should set EOF flag. */
siz = read(fh, waste, 1);
if (siz != 0) {
/* Not at EOF, but should be. File too big. */
ofs = EOF;
}
}
}
#endif /* ?USE_STRM_INPUT */
return ofs;
} /* end function file_size() */
#endif /* DO_SAFECHECK_2GB */
/***********************/
/* Function rec_find() */
/***********************/
static int rec_find(__G__ searchlen, signature, rec_size)
/* return 0 when rec found, 1 when not found, 2 in case of read error */
__GDEF
zoff_t searchlen;
char* signature;
int rec_size;
{
int i, numblks, found=FALSE;
zoff_t tail_len;
/*---------------------------------------------------------------------------
Zipfile is longer than INBUFSIZ: may need to loop. Start with short
block at end of zipfile (if not TOO short).
---------------------------------------------------------------------------*/
if ((tail_len = G.ziplen % INBUFSIZ) > rec_size) {
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, G.ziplen-tail_len, SEEK_SET);
G.cur_zipfile_bufstart = zftello(G.zipfd);
#else /* !USE_STRM_INPUT */
G.cur_zipfile_bufstart = zlseek(G.zipfd, G.ziplen-tail_len, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd, (char *)G.inbuf,
(unsigned int)tail_len)) != (int)tail_len)
return 2; /* it's expedient... */
/* 'P' must be at least (rec_size+4) bytes from end of zipfile */
for (G.inptr = G.inbuf+(int)tail_len-(rec_size+4);
G.inptr >= G.inbuf;
--G.inptr) {
if ( (*G.inptr == (uch)0x50) && /* ASCII 'P' */
!memcmp((char *)G.inptr, signature, 4) ) {
G.incnt -= (int)(G.inptr - G.inbuf);
found = TRUE;
break;
}
}
/* sig may span block boundary: */
memcpy((char *)G.hold, (char *)G.inbuf, 3);
} else
G.cur_zipfile_bufstart = G.ziplen - tail_len;
/*-----------------------------------------------------------------------
Loop through blocks of zipfile data, starting at the end and going
toward the beginning. In general, need not check whole zipfile for
signature, but may want to do so if testing.
-----------------------------------------------------------------------*/
numblks = (int)((searchlen - tail_len + (INBUFSIZ-1)) / INBUFSIZ);
/* ==amount= ==done== ==rounding== =blksiz= */
for (i = 1; !found && (i <= numblks); ++i) {
G.cur_zipfile_bufstart -= INBUFSIZ;
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, G.cur_zipfile_bufstart, SEEK_SET);
#else /* !USE_STRM_INPUT */
zlseek(G.zipfd, G.cur_zipfile_bufstart, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd,(char *)G.inbuf,INBUFSIZ))
!= INBUFSIZ)
return 2; /* read error is fatal failure */
for (G.inptr = G.inbuf+INBUFSIZ-1; G.inptr >= G.inbuf; --G.inptr)
if ( (*G.inptr == (uch)0x50) && /* ASCII 'P' */
!memcmp((char *)G.inptr, signature, 4) ) {
G.incnt -= (int)(G.inptr - G.inbuf);
found = TRUE;
break;
}
/* sig may span block boundary: */
memcpy((char *)G.hold, (char *)G.inbuf, 3);
}
return (found ? 0 : 1);
} /* end function rec_find() */
#if 0
/********************************/
/* Function check_ecrec_zip64() */
/********************************/
static int check_ecrec_zip64(__G)
__GDEF
{
return G.ecrec.offset_start_central_directory == 0xFFFFFFFFL
|| G.ecrec.size_central_directory == 0xFFFFFFFFL
|| G.ecrec.total_entries_central_dir == 0xFFFF
|| G.ecrec.num_entries_centrl_dir_ths_disk == 0xFFFF
|| G.ecrec.num_disk_start_cdir == 0xFFFF
|| G.ecrec.number_this_disk == 0xFFFF;
} /* end function check_ecrec_zip64() */
#endif /* never */
/***************************/
/* Function find_ecrec64() */
/***************************/
static int find_ecrec64(__G__ searchlen) /* return PK-class error */
__GDEF
zoff_t searchlen;
{
ec_byte_rec64 byterec; /* buf for ecrec64 */
ec_byte_loc64 byterecL; /* buf for ecrec64 locator */
zoff_t ecloc64_start_offset; /* start offset of ecrec64 locator */
zusz_t ecrec64_start_offset; /* start offset of ecrec64 */
zuvl_t ecrec64_start_disk; /* start disk of ecrec64 */
zuvl_t ecloc64_total_disks; /* total disks */
zuvl_t ecrec64_disk_cdstart; /* disk number of central dir start */
zucn_t ecrec64_this_entries; /* entries on disk with ecrec64 */
zucn_t ecrec64_tot_entries; /* total number of entries */
zusz_t ecrec64_cdirsize; /* length of central dir */
zusz_t ecrec64_offs_cdstart; /* offset of central dir start */
/* First, find the ecrec64 locator. By definition, this must be before
ecrec with nothing in between. We back up the size of the ecrec64
locator and check. */
ecloc64_start_offset = G.real_ecrec_offset - (ECLOC64_SIZE+4);
if (ecloc64_start_offset < 0)
/* Seeking would go past beginning, so probably empty archive */
return PK_COOL;
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, ecloc64_start_offset, SEEK_SET);
G.cur_zipfile_bufstart = zftello(G.zipfd);
#else /* !USE_STRM_INPUT */
G.cur_zipfile_bufstart = zlseek(G.zipfd, ecloc64_start_offset, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd, (char *)byterecL, ECLOC64_SIZE+4))
!= (ECLOC64_SIZE+4)) {
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchErr)));
return PK_ERR;
}
if (memcmp((char *)byterecL, end_centloc64_sig, 4) ) {
/* not found */
return PK_COOL;
}
/* Read the locator. */
ecrec64_start_disk = (zuvl_t)makelong(&byterecL[NUM_DISK_START_EOCDR64]);
ecrec64_start_offset = (zusz_t)makeint64(&byterecL[OFFSET_START_EOCDR64]);
ecloc64_total_disks = (zuvl_t)makelong(&byterecL[NUM_THIS_DISK_LOC64]);
/* Check for consistency */
#ifdef TEST
fprintf(stdout,"\nnumber of disks (ECR) %u, (ECLOC64) %lu\n",
G.ecrec.number_this_disk, ecloc64_total_disks); fflush(stdout);
#endif
if ((G.ecrec.number_this_disk != 0xFFFF) &&
(G.ecrec.number_this_disk != ecloc64_total_disks - 1)) {
/* Note: For some unknown reason, the developers at PKWARE decided to
store the "zip64 total disks" value as a counter starting from 1,
whereas all other "split/span volume" related fields use 0-based
volume numbers. Sigh... */
/* When the total number of disks as found in the traditional ecrec
is not 0xFFFF, the disk numbers in ecrec and ecloc64 must match.
When this is not the case, the found ecrec64 locator cannot be valid.
-> This is not a Zip64 archive.
*/
Trace((stderr,
"\ninvalid ECLOC64, differing disk# (ECR %u, ECL64 %lu)\n",
G.ecrec.number_this_disk, ecloc64_total_disks - 1));
return PK_COOL;
}
/* If found locator, look for ecrec64 where the locator says it is. */
/* For now assume that ecrec64 is on the same disk as ecloc64 and ecrec,
which is usually the case and is how Zip writes it. To do this right,
however, we should allow the ecrec64 to be on another disk since
the AppNote allows it and the ecrec64 can be large, especially if
Version 2 is used (AppNote uses 8 bytes for the size of this record). */
/* FIX BELOW IF ADD SUPPORT FOR MULTIPLE DISKS */
if (ecrec64_start_offset > (zusz_t)ecloc64_start_offset) {
/* ecrec64 has to be before ecrec64 locator */
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchErr)));
return PK_ERR;
}
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, ecrec64_start_offset, SEEK_SET);
G.cur_zipfile_bufstart = zftello(G.zipfd);
#else /* !USE_STRM_INPUT */
G.cur_zipfile_bufstart = zlseek(G.zipfd, ecrec64_start_offset, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd, (char *)byterec, ECREC64_SIZE+4))
!= (ECREC64_SIZE+4)) {
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchErr)));
return PK_ERR;
}
if (memcmp((char *)byterec, end_central64_sig, 4) ) {
/* Zip64 EOCD Record not found */
/* Since we already have seen the Zip64 EOCD Locator, it's
possible we got here because there are bytes prepended
to the archive, like the sfx prefix. */
/* Make a guess as to where the Zip64 EOCD Record might be */
ecrec64_start_offset = ecloc64_start_offset - ECREC64_SIZE - 4;
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, ecrec64_start_offset, SEEK_SET);
G.cur_zipfile_bufstart = zftello(G.zipfd);
#else /* !USE_STRM_INPUT */
G.cur_zipfile_bufstart = zlseek(G.zipfd, ecrec64_start_offset, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd, (char *)byterec, ECREC64_SIZE+4))
!= (ECREC64_SIZE+4)) {
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchErr)));
return PK_ERR;
}
if (memcmp((char *)byterec, end_central64_sig, 4) ) {
/* Zip64 EOCD Record not found */
/* Probably something not so easy to handle so exit */
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchErr)));
return PK_ERR;
}
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchOff)));
}
/* Check consistency of found ecrec64 with ecloc64 (and ecrec): */
if ( (zuvl_t)makelong(&byterec[NUMBER_THIS_DSK_REC64])
!= ecrec64_start_disk )
/* found ecrec64 does not match ecloc64 info -> no Zip64 archive */
return PK_COOL;
/* Read all relevant ecrec64 fields and compare them to the corresponding
ecrec fields unless those are set to "all-ones".
*/
ecrec64_disk_cdstart =
(zuvl_t)makelong(&byterec[NUM_DISK_START_CEN_DIR64]);
if ( (G.ecrec.num_disk_start_cdir != 0xFFFF) &&
(G.ecrec.num_disk_start_cdir != ecrec64_disk_cdstart) )
return PK_COOL;
ecrec64_this_entries
= makeint64(&byterec[NUM_ENTRIES_CEN_DIR_THS_DISK64]);
if ( (G.ecrec.num_entries_centrl_dir_ths_disk != 0xFFFF) &&
(G.ecrec.num_entries_centrl_dir_ths_disk != ecrec64_this_entries) )
return PK_COOL;
ecrec64_tot_entries
= makeint64(&byterec[TOTAL_ENTRIES_CENTRAL_DIR64]);
if ( (G.ecrec.total_entries_central_dir != 0xFFFF) &&
(G.ecrec.total_entries_central_dir != ecrec64_tot_entries) )
return PK_COOL;
ecrec64_cdirsize
= makeint64(&byterec[SIZE_CENTRAL_DIRECTORY64]);
if ( (G.ecrec.size_central_directory != 0xFFFFFFFFL) &&
(G.ecrec.size_central_directory != ecrec64_cdirsize) )
return PK_COOL;
ecrec64_offs_cdstart
= makeint64(&byterec[OFFSET_START_CENTRAL_DIRECT64]);
if ( (G.ecrec.offset_start_central_directory != 0xFFFFFFFFL) &&
(G.ecrec.offset_start_central_directory != ecrec64_offs_cdstart) )
return PK_COOL;
/* Now, we are (almost) sure that we have a Zip64 archive. */
G.ecrec.have_ecr64 = 1;
/* Update the "end-of-central-dir offset" for later checks. */
G.real_ecrec_offset = ecrec64_start_offset;
/* Update all ecdir_rec data that are flagged to be invalid
in Zip64 mode. Set the ecrec64-mandatory flag when such a
case is found. */
if (G.ecrec.number_this_disk == 0xFFFF) {
G.ecrec.number_this_disk = ecrec64_start_disk;
if (ecrec64_start_disk != 0xFFFF) G.ecrec.is_zip64_archive = TRUE;
}
if (G.ecrec.num_disk_start_cdir == 0xFFFF) {
G.ecrec.num_disk_start_cdir = ecrec64_disk_cdstart;
if (ecrec64_disk_cdstart != 0xFFFF) G.ecrec.is_zip64_archive = TRUE;
}
if (G.ecrec.num_entries_centrl_dir_ths_disk == 0xFFFF) {
G.ecrec.num_entries_centrl_dir_ths_disk = ecrec64_this_entries;
if (ecrec64_this_entries != 0xFFFF) G.ecrec.is_zip64_archive = TRUE;
}
if (G.ecrec.total_entries_central_dir == 0xFFFF) {
G.ecrec.total_entries_central_dir = ecrec64_tot_entries;
if (ecrec64_tot_entries != 0xFFFF) G.ecrec.is_zip64_archive = TRUE;
}
if (G.ecrec.size_central_directory == 0xFFFFFFFFL) {
G.ecrec.size_central_directory = ecrec64_cdirsize;
if (ecrec64_cdirsize != 0xFFFFFFFF) G.ecrec.is_zip64_archive = TRUE;
}
if (G.ecrec.offset_start_central_directory == 0xFFFFFFFFL) {
G.ecrec.offset_start_central_directory = ecrec64_offs_cdstart;
if (ecrec64_offs_cdstart != 0xFFFFFFFF) G.ecrec.is_zip64_archive = TRUE;
}
return PK_COOL;
} /* end function find_ecrec64() */
/*************************/
/* Function find_ecrec() */
/*************************/
static int find_ecrec(__G__ searchlen) /* return PK-class error */
__GDEF
zoff_t searchlen;
{
int found = FALSE;
int error_in_archive;
int result;
ec_byte_rec byterec;
/*---------------------------------------------------------------------------
Treat case of short zipfile separately.
---------------------------------------------------------------------------*/
if (G.ziplen <= INBUFSIZ) {
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, 0L, SEEK_SET);
#else /* !USE_STRM_INPUT */
zlseek(G.zipfd, 0L, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd,(char *)G.inbuf,(unsigned int)G.ziplen))
== (int)G.ziplen)
/* 'P' must be at least (ECREC_SIZE+4) bytes from end of zipfile */
for (G.inptr = G.inbuf+(int)G.ziplen-(ECREC_SIZE+4);
G.inptr >= G.inbuf;
--G.inptr) {
if ( (*G.inptr == (uch)0x50) && /* ASCII 'P' */
!memcmp((char *)G.inptr, end_central_sig, 4)) {
G.incnt -= (int)(G.inptr - G.inbuf);
found = TRUE;
break;
}
}
/*---------------------------------------------------------------------------
Zipfile is longer than INBUFSIZ:
MB - this next block of code moved to rec_find so that same code can be
used to look for zip64 ec record. No need to include code above since
a zip64 ec record will only be looked for if it is a BIG file.
---------------------------------------------------------------------------*/
} else {
found =
(rec_find(__G__ searchlen, end_central_sig, ECREC_SIZE) == 0
? TRUE : FALSE);
} /* end if (ziplen > INBUFSIZ) */
/*---------------------------------------------------------------------------
Searched through whole region where signature should be without finding
it. Print informational message and die a horrible death.
---------------------------------------------------------------------------*/
if (!found) {
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(CentDirEndSigNotFound)));
return PK_ERR; /* failed */
}
/*---------------------------------------------------------------------------
Found the signature, so get the end-central data before returning. Do
any necessary machine-type conversions (byte ordering, structure padding
compensation) by reading data into character array and copying to struct.
---------------------------------------------------------------------------*/
G.real_ecrec_offset = G.cur_zipfile_bufstart + (G.inptr-G.inbuf);
#ifdef TEST
printf("\n found end-of-central-dir signature at offset %s (%sh)\n",
FmZofft(G.real_ecrec_offset, NULL, NULL),
FmZofft(G.real_ecrec_offset, FZOFFT_HEX_DOT_WID, "X"));
printf(" from beginning of file; offset %d (%.4Xh) within block\n",
G.inptr-G.inbuf, G.inptr-G.inbuf);
#endif
if (readbuf(__G__ (char *)byterec, ECREC_SIZE+4) == 0)
return PK_EOF;
G.ecrec.number_this_disk =
makeword(&byterec[NUMBER_THIS_DISK]);
G.ecrec.num_disk_start_cdir =
makeword(&byterec[NUM_DISK_WITH_START_CEN_DIR]);
G.ecrec.num_entries_centrl_dir_ths_disk =
makeword(&byterec[NUM_ENTRIES_CEN_DIR_THS_DISK]);
G.ecrec.total_entries_central_dir =
makeword(&byterec[TOTAL_ENTRIES_CENTRAL_DIR]);
G.ecrec.size_central_directory =
makelong(&byterec[SIZE_CENTRAL_DIRECTORY]);
G.ecrec.offset_start_central_directory =
makelong(&byterec[OFFSET_START_CENTRAL_DIRECTORY]);
G.ecrec.zipfile_comment_length =
makeword(&byterec[ZIPFILE_COMMENT_LENGTH]);
/* Now, we have to read the archive comment, BEFORE the file pointer
is moved away backwards to seek for a Zip64 ECLOC64 structure.
*/
if ( (error_in_archive = process_zip_cmmnt(__G)) > PK_WARN )
return error_in_archive;
/* Next: Check for existence of Zip64 end-of-cent-dir locator
ECLOC64. This structure must reside on the same volume as the
classic ECREC, at exactly (ECLOC64_SIZE+4) bytes in front
of the ECREC.
The ECLOC64 structure directs to the longer ECREC64 structure
A ECREC64 will ALWAYS exist for a proper Zip64 archive, as
the "Version Needed To Extract" field is required to be set
to 4.5 or higher whenever any Zip64 features are used anywhere
in the archive, so just check for that to see if this is a
Zip64 archive.
*/
result = find_ecrec64(__G__ searchlen+76);
/* 76 bytes for zip64ec & zip64 locator */
if (result != PK_COOL) {
if (error_in_archive < result)
error_in_archive = result;
return error_in_archive;
}
G.expect_ecrec_offset = G.ecrec.offset_start_central_directory +
G.ecrec.size_central_directory;
#ifndef NO_ZIPINFO
if (uO.zipinfo_mode) {
/* In ZipInfo mode, additional info about the data found in the
end-of-central-directory areas is printed out.
*/
zi_end_central(__G);
}
#endif
return error_in_archive;
} /* end function find_ecrec() */
/********************************/
/* Function process_zip_cmmnt() */
/********************************/
static int process_zip_cmmnt(__G) /* return PK-type error code */
__GDEF
{
int error = PK_COOL;
/*---------------------------------------------------------------------------
Get the zipfile comment (up to 64KB long), if any, and print it out.
---------------------------------------------------------------------------*/
#ifdef WINDLL
/* for comment button: */
if ((!G.fValidate) && (G.lpUserFunctions != NULL))
G.lpUserFunctions->cchComment = G.ecrec.zipfile_comment_length;
#endif /* WINDLL */
#ifndef NO_ZIPINFO
/* ZipInfo, verbose format */
if (uO.zipinfo_mode && uO.lflag > 9) {
/*-------------------------------------------------------------------
Get the zipfile comment, if any, and print it out.
(Comment may be up to 64KB long. May the fleas of a thousand
camels infest the arm-pits of anyone who actually takes advantage
of this fact.)
-------------------------------------------------------------------*/
if (!G.ecrec.zipfile_comment_length)
Info(slide, 0, ((char *)slide, LoadFarString(NoZipfileComment)));
else {
Info(slide, 0, ((char *)slide, LoadFarString(ZipfileCommentDesc),
G.ecrec.zipfile_comment_length));
Info(slide, 0, ((char *)slide, LoadFarString(ZipfileCommBegin)));
if (do_string(__G__ G.ecrec.zipfile_comment_length, DISPLAY))
error = PK_WARN;
Info(slide, 0, ((char *)slide, LoadFarString(ZipfileCommEnd)));
if (error)
Info(slide, 0, ((char *)slide,
LoadFarString(ZipfileCommTrunc2)));
} /* endif (comment exists) */
/* ZipInfo, non-verbose mode: print zipfile comment only if requested */
} else if (G.ecrec.zipfile_comment_length &&
(uO.zflag > 0) && uO.zipinfo_mode) {
if (do_string(__G__ G.ecrec.zipfile_comment_length, DISPLAY)) {
Info(slide, 0x401, ((char *)slide,
LoadFarString(ZipfileCommTrunc1)));
error = PK_WARN;
}
} else
#endif /* !NO_ZIPINFO */
if ( G.ecrec.zipfile_comment_length &&
(uO.zflag > 0
#ifndef WINDLL
|| (uO.zflag == 0
# ifndef NO_ZIPINFO
&& !uO.zipinfo_mode
# endif
# ifdef TIMESTAMP
&& !uO.T_flag
# endif
&& !uO.qflag)
#endif /* !WINDLL */
) )
{
if (do_string(__G__ G.ecrec.zipfile_comment_length,
#if (defined(SFX) && defined(CHEAP_SFX_AUTORUN))
# ifndef NO_ZIPINFO
(oU.zipinfo_mode ? DISPLAY : CHECK_AUTORUN)
# else
CHECK_AUTORUN
# endif
#else
DISPLAY
#endif
))
{
Info(slide, 0x401, ((char *)slide,
LoadFarString(ZipfileCommTrunc1)));
error = PK_WARN;
}
}
#if (defined(SFX) && defined(CHEAP_SFX_AUTORUN))
else if (G.ecrec.zipfile_comment_length) {
if (do_string(__G__ G.ecrec.zipfile_comment_length, CHECK_AUTORUN_Q))
{
Info(slide, 0x401, ((char *)slide,
LoadFarString(ZipfileCommTrunc1)));
error = PK_WARN;
}
}
#endif
return error;
} /* end function process_zip_cmmnt() */
/************************************/
/* Function process_cdir_file_hdr() */
/************************************/
int process_cdir_file_hdr(__G) /* return PK-type error code */
__GDEF
{
int error;
/*---------------------------------------------------------------------------
Get central directory info, save host and method numbers, and set flag
for lowercase conversion of filename, depending on the OS from which the
file is coming.
---------------------------------------------------------------------------*/
if ((error = get_cdir_ent(__G)) != 0)
return error;
G.pInfo->hostver = G.crec.version_made_by[0];
G.pInfo->hostnum = MIN(G.crec.version_made_by[1], NUM_HOSTS);
/* extnum = MIN(crec.version_needed_to_extract[1], NUM_HOSTS); */
G.pInfo->lcflag = 0;
if (uO.L_flag == 1) /* name conversion for monocase systems */
switch (G.pInfo->hostnum) {
case FS_FAT_: /* PKZIP and zip -k store in uppercase */
case CPM_: /* like MS-DOS, right? */
case VM_CMS_: /* all caps? */
case MVS_: /* all caps? */
case TANDEM_:
case TOPS20_:
case VMS_: /* our Zip uses lowercase, but ASi's doesn't */
/* case Z_SYSTEM_: ? */
/* case QDOS_: ? */
G.pInfo->lcflag = 1; /* convert filename to lowercase */
break;
default: /* AMIGA_, FS_HPFS_, FS_NTFS_, MAC_, UNIX_, ATARI_, */
break; /* FS_VFAT_, ATHEOS_, BEOS_ (Z_SYSTEM_), THEOS_: */
/* no conversion */
}
else if (uO.L_flag > 1) /* let -LL force lower case for all names */
G.pInfo->lcflag = 1;
/* do Amigas (AMIGA_) also have volume labels? */
if (IS_VOLID(G.crec.external_file_attributes) &&
(G.pInfo->hostnum == FS_FAT_ || G.pInfo->hostnum == FS_HPFS_ ||
G.pInfo->hostnum == FS_NTFS_ || G.pInfo->hostnum == ATARI_))
{
G.pInfo->vollabel = TRUE;
G.pInfo->lcflag = 0; /* preserve case of volume labels */
} else
G.pInfo->vollabel = FALSE;
/* this flag is needed to detect archives made by "PKZIP for Unix" when
deciding which kind of codepage conversion has to be applied to
strings (see do_string() function in fileio.c) */
G.pInfo->HasUxAtt = (G.crec.external_file_attributes & 0xffff0000L) != 0L;
#ifdef UNICODE_SUPPORT
/* remember the state of GPB11 (General Purpuse Bit 11) which indicates
that the standard path and comment are UTF-8. */
G.pInfo->GPFIsUTF8
= (G.crec.general_purpose_bit_flag & (1 << 11)) == (1 << 11);
#endif
return PK_COOL;
} /* end function process_cdir_file_hdr() */
/***************************/
/* Function get_cdir_ent() */
/***************************/
static int get_cdir_ent(__G) /* return PK-type error code */
__GDEF
{
cdir_byte_hdr byterec;
/*---------------------------------------------------------------------------
Read the next central directory entry and do any necessary machine-type
conversions (byte ordering, structure padding compensation--do so by
copying the data from the array into which it was read (byterec) to the
usable struct (crec)).
---------------------------------------------------------------------------*/
if (readbuf(__G__ (char *)byterec, CREC_SIZE) == 0)
return PK_EOF;
G.crec.version_made_by[0] = byterec[C_VERSION_MADE_BY_0];
G.crec.version_made_by[1] = byterec[C_VERSION_MADE_BY_1];
G.crec.version_needed_to_extract[0] =
byterec[C_VERSION_NEEDED_TO_EXTRACT_0];
G.crec.version_needed_to_extract[1] =
byterec[C_VERSION_NEEDED_TO_EXTRACT_1];
G.crec.general_purpose_bit_flag =
makeword(&byterec[C_GENERAL_PURPOSE_BIT_FLAG]);
G.crec.compression_method =
makeword(&byterec[C_COMPRESSION_METHOD]);
G.crec.last_mod_dos_datetime =
makelong(&byterec[C_LAST_MOD_DOS_DATETIME]);
G.crec.crc32 =
makelong(&byterec[C_CRC32]);
G.crec.csize =
makelong(&byterec[C_COMPRESSED_SIZE]);
G.crec.ucsize =
makelong(&byterec[C_UNCOMPRESSED_SIZE]);
G.crec.filename_length =
makeword(&byterec[C_FILENAME_LENGTH]);
G.crec.extra_field_length =
makeword(&byterec[C_EXTRA_FIELD_LENGTH]);
G.crec.file_comment_length =
makeword(&byterec[C_FILE_COMMENT_LENGTH]);
G.crec.disk_number_start =
makeword(&byterec[C_DISK_NUMBER_START]);
G.crec.internal_file_attributes =
makeword(&byterec[C_INTERNAL_FILE_ATTRIBUTES]);
G.crec.external_file_attributes =
makelong(&byterec[C_EXTERNAL_FILE_ATTRIBUTES]); /* LONG, not word! */
G.crec.relative_offset_local_header =
makelong(&byterec[C_RELATIVE_OFFSET_LOCAL_HEADER]);
return PK_COOL;
} /* end function get_cdir_ent() */
/*************************************/
/* Function process_local_file_hdr() */
/*************************************/
int process_local_file_hdr(__G) /* return PK-type error code */
__GDEF
{
local_byte_hdr byterec;
/*---------------------------------------------------------------------------
Read the next local file header and do any necessary machine-type con-
versions (byte ordering, structure padding compensation--do so by copy-
ing the data from the array into which it was read (byterec) to the
usable struct (lrec)).
---------------------------------------------------------------------------*/
if (readbuf(__G__ (char *)byterec, LREC_SIZE) == 0)
return PK_EOF;
G.lrec.version_needed_to_extract[0] =
byterec[L_VERSION_NEEDED_TO_EXTRACT_0];
G.lrec.version_needed_to_extract[1] =
byterec[L_VERSION_NEEDED_TO_EXTRACT_1];
G.lrec.general_purpose_bit_flag =
makeword(&byterec[L_GENERAL_PURPOSE_BIT_FLAG]);
G.lrec.compression_method = makeword(&byterec[L_COMPRESSION_METHOD]);
G.lrec.last_mod_dos_datetime = makelong(&byterec[L_LAST_MOD_DOS_DATETIME]);
G.lrec.crc32 = makelong(&byterec[L_CRC32]);
G.lrec.csize = makelong(&byterec[L_COMPRESSED_SIZE]);
G.lrec.ucsize = makelong(&byterec[L_UNCOMPRESSED_SIZE]);
G.lrec.filename_length = makeword(&byterec[L_FILENAME_LENGTH]);
G.lrec.extra_field_length = makeword(&byterec[L_EXTRA_FIELD_LENGTH]);
if ((G.lrec.general_purpose_bit_flag & 8) != 0) {
/* can't trust local header, use central directory: */
G.lrec.crc32 = G.pInfo->crc;
G.lrec.csize = G.pInfo->compr_size;
G.lrec.ucsize = G.pInfo->uncompr_size;
}
G.csize = G.lrec.csize;
return PK_COOL;
} /* end function process_local_file_hdr() */
/*******************************/
/* Function getZip64Data() */
/*******************************/
int getZip64Data(__G__ ef_buf, ef_len)
__GDEF
ZCONST uch *ef_buf; /* buffer containing extra field */
unsigned ef_len; /* total length of extra field */
{
unsigned eb_id;
unsigned eb_len;
/*---------------------------------------------------------------------------
This function scans the extra field for zip64 information, ie 8-byte
versions of compressed file size, uncompressed file size, relative offset
and a 4-byte version of disk start number.
Sets both local header and central header fields. Not terribly clever,
but it means that this procedure is only called in one place.
---------------------------------------------------------------------------*/
if (ef_len == 0 || ef_buf == NULL)
return PK_COOL;
Trace((stderr,"\ngetZip64Data: scanning extra field of length %u\n",
ef_len));
while (ef_len >= EB_HEADSIZE) {
eb_id = makeword(EB_ID + ef_buf);
eb_len = makeword(EB_LEN + ef_buf);
if (eb_len > (ef_len - EB_HEADSIZE)) {
/* discovered some extra field inconsistency! */
Trace((stderr,
"getZip64Data: block length %u > rest ef_size %u\n", eb_len,
ef_len - EB_HEADSIZE));
break;
}
if (eb_id == EF_PKSZ64) {
int offset = EB_HEADSIZE;
if (G.crec.ucsize == 0xffffffff || G.lrec.ucsize == 0xffffffff){
G.lrec.ucsize = G.crec.ucsize = makeint64(offset + ef_buf);
offset += sizeof(G.crec.ucsize);
}
if (G.crec.csize == 0xffffffff || G.lrec.csize == 0xffffffff){
G.csize = G.lrec.csize = G.crec.csize = makeint64(offset + ef_buf);
offset += sizeof(G.crec.csize);
}
if (G.crec.relative_offset_local_header == 0xffffffff){
G.crec.relative_offset_local_header = makeint64(offset + ef_buf);
offset += sizeof(G.crec.relative_offset_local_header);
}
if (G.crec.disk_number_start == 0xffff){
G.crec.disk_number_start = (zuvl_t)makelong(offset + ef_buf);
offset += sizeof(G.crec.disk_number_start);
}
}
/* Skip this extra field block */
ef_buf += (eb_len + EB_HEADSIZE);
ef_len -= (eb_len + EB_HEADSIZE);
}
return PK_COOL;
} /* end function getZip64Data() */
#ifdef UNICODE_SUPPORT
/*******************************/
/* Function getUnicodeData() */
/*******************************/
int getUnicodeData(__G__ ef_buf, ef_len)
__GDEF
ZCONST uch *ef_buf; /* buffer containing extra field */
unsigned ef_len; /* total length of extra field */
{
unsigned eb_id;
unsigned eb_len;
/*---------------------------------------------------------------------------
This function scans the extra field for Unicode information, ie UTF-8
path extra fields.
On return, G.unipath_filename =
NULL, if no Unicode path extra field or error
"", if the standard path is UTF-8 (free when done)
null-terminated UTF-8 path (free when done)
Return PK_COOL if no error.
---------------------------------------------------------------------------*/
G.unipath_filename = NULL;
if (ef_len == 0 || ef_buf == NULL)
return PK_COOL;
Trace((stderr,"\ngetUnicodeData: scanning extra field of length %u\n",
ef_len));
while (ef_len >= EB_HEADSIZE) {
eb_id = makeword(EB_ID + ef_buf);
eb_len = makeword(EB_LEN + ef_buf);
if (eb_len > (ef_len - EB_HEADSIZE)) {
/* discovered some extra field inconsistency! */
Trace((stderr,
"getUnicodeData: block length %u > rest ef_size %u\n", eb_len,
ef_len - EB_HEADSIZE));
break;
}
if (eb_id == EF_UNIPATH) {
int offset = EB_HEADSIZE;
ush ULen = eb_len - 5;
ulg chksum = CRCVAL_INITIAL;
/* version */
G.unipath_version = (uch) *(offset + ef_buf);
offset += 1;
if (G.unipath_version > 1) {
/* can do only version 1 */
Info(slide, 0x401, ((char *)slide,
LoadFarString(UnicodeVersionError)));
return PK_ERR;
}
/* filename CRC */
G.unipath_checksum = makelong(offset + ef_buf);
offset += 4;
/*
* Compute 32-bit crc
*/
chksum = crc32(chksum, (uch *)(G.filename_full),
strlen(G.filename_full));
/* If the checksums's don't match then likely filename has been
* modified and the Unicode Path is no longer valid.
*/
if (chksum != G.unipath_checksum) {
Info(slide, 0x401, ((char *)slide,
LoadFarString(UnicodeMismatchError)));
if (G.unicode_mismatch == 1) {
/* warn and continue */
} else if (G.unicode_mismatch == 2) {
/* ignore and continue */
} else if (G.unicode_mismatch == 0) {
}
return PK_ERR;
}
/* UTF-8 Path */
if ((G.unipath_filename = malloc(ULen + 1)) == NULL) {
return PK_ERR;
}
if (ULen == 0) {
/* standard path is UTF-8 so use that */
G.unipath_filename[0] = '\0';
} else {
/* UTF-8 path */
strncpy(G.unipath_filename,
(ZCONST char *)(offset + ef_buf), ULen);
G.unipath_filename[ULen] = '\0';
}
}
/* Skip this extra field block */
ef_buf += (eb_len + EB_HEADSIZE);
ef_len -= (eb_len + EB_HEADSIZE);
}
return PK_COOL;
} /* end function getUnicodeData() */
#ifdef UNICODE_WCHAR
/*---------------------------------------------
* Unicode conversion functions
*
* Based on functions provided by Paul Kienitz
*
*---------------------------------------------
*/
/*
NOTES APPLICABLE TO ALL STRING FUNCTIONS:
All of the x_to_y functions take parameters for an output buffer and
its available length, and return an int. The value returned is the
length of the string that the input produces, which may be larger than
the provided buffer length. If the returned value is less than the
buffer length, then the contents of the buffer will be null-terminated;
otherwise, it will not be terminated and may be invalid, possibly
stopping in the middle of a multibyte sequence.
In all cases you may pass NULL as the buffer and/or 0 as the length, if
you just want to learn how much space the string is going to require.
The functions will return -1 if the input is invalid UTF-8 or cannot be
encoded as UTF-8.
*/
static int utf8_char_bytes OF((ZCONST char *utf8));
static ulg ucs4_char_from_utf8 OF((ZCONST char **utf8));
static int utf8_to_ucs4_string OF((ZCONST char *utf8, ulg *ucs4buf,
int buflen));
/* utility functions for managing UTF-8 and UCS-4 strings */
/* utf8_char_bytes
*
* Returns the number of bytes used by the first character in a UTF-8
* string, or -1 if the UTF-8 is invalid or null.
*/
static int utf8_char_bytes(utf8)
ZCONST char *utf8;
{
int t, r;
unsigned lead;
if (!utf8)
return -1; /* no input */
lead = (unsigned char) *utf8;
if (lead < 0x80)
r = 1; /* an ascii-7 character */
else if (lead < 0xC0)
return -1; /* error: trailing byte without lead byte */
else if (lead < 0xE0)
r = 2; /* an 11 bit character */
else if (lead < 0xF0)
r = 3; /* a 16 bit character */
else if (lead < 0xF8)
r = 4; /* a 21 bit character (the most currently used) */
else if (lead < 0xFC)
r = 5; /* a 26 bit character (shouldn't happen) */
else if (lead < 0xFE)
r = 6; /* a 31 bit character (shouldn't happen) */
else
return -1; /* error: invalid lead byte */
for (t = 1; t < r; t++)
if ((unsigned char) utf8[t] < 0x80 || (unsigned char) utf8[t] >= 0xC0)
return -1; /* error: not enough valid trailing bytes */
return r;
}
/* ucs4_char_from_utf8
*
* Given a reference to a pointer into a UTF-8 string, returns the next
* UCS-4 character and advances the pointer to the next character sequence.
* Returns ~0 (= -1 in twos-complement notation) and does not advance the
* pointer when input is ill-formed.
*/
static ulg ucs4_char_from_utf8(utf8)
ZCONST char **utf8;
{
ulg ret;
int t, bytes;
if (!utf8)
return ~0L; /* no input */
bytes = utf8_char_bytes(*utf8);
if (bytes <= 0)
return ~0L; /* invalid input */
if (bytes == 1)
ret = **utf8; /* ascii-7 */
else
ret = **utf8 & (0x7F >> bytes); /* lead byte of a multibyte sequence */
(*utf8)++;
for (t = 1; t < bytes; t++) /* consume trailing bytes */
ret = (ret << 6) | (*((*utf8)++) & 0x3F);
return (zwchar) ret;
}
#if 0 /* currently unused */
/* utf8_from_ucs4_char - Convert UCS char to UTF-8
*
* Returns the number of bytes put into utf8buf to represent ch, from 1 to 6,
* or -1 if ch is too large to represent. utf8buf must have room for 6 bytes.
*/
static int utf8_from_ucs4_char(utf8buf, ch)
char *utf8buf;
ulg ch;
{
int trailing = 0;
int leadmask = 0x80;
int leadbits = 0x3F;
int tch = ch;
int ret;
if (ch > 0x7FFFFFFFL)
return -1; /* UTF-8 can represent 31 bits */
if (ch < 0x7F)
{
*utf8buf++ = (char) ch; /* ascii-7 */
return 1;
}
do {
trailing++;
leadmask = (leadmask >> 1) | 0x80;
leadbits >>= 1;
tch >>= 6;
} while (tch & ~leadbits);
ret = trailing + 1;
/* produce lead byte */
*utf8buf++ = (char) (leadmask | (ch >> (6 * trailing)));
while (--trailing >= 0)
/* produce trailing bytes */
*utf8buf++ = (char) (0x80 | ((ch >> (6 * trailing)) & 0x3F));
return ret;
}
#endif /* unused */
/*===================================================================*/
/* utf8_to_ucs4_string - convert UTF-8 string to UCS string
*
* Return UCS count. Now returns int so can return -1.
*/
static int utf8_to_ucs4_string(utf8, ucs4buf, buflen)
ZCONST char *utf8;
ulg *ucs4buf;
int buflen;
{
int count = 0;
for (;;)
{
ulg ch = ucs4_char_from_utf8(&utf8);
if (ch == ~0L)
return -1;
else
{
if (ucs4buf && count < buflen)
ucs4buf[count] = ch;
if (ch == 0)
return count;
count++;
}
}
}
#if 0 /* currently unused */
/* ucs4_string_to_utf8
*
*
*/
static int ucs4_string_to_utf8(ucs4, utf8buf, buflen)
ZCONST ulg *ucs4;
char *utf8buf;
int buflen;
{
char mb[6];
int count = 0;
if (!ucs4)
return -1;
for (;;)
{
int mbl = utf8_from_ucs4_char(mb, *ucs4++);
int c;
if (mbl <= 0)
return -1;
/* We could optimize this a bit by passing utf8buf + count */
/* directly to utf8_from_ucs4_char when buflen >= count + 6... */
c = buflen - count;
if (mbl < c)
c = mbl;
if (utf8buf && count < buflen)
strncpy(utf8buf + count, mb, c);
if (mbl == 1 && !mb[0])
return count; /* terminating nul */
count += mbl;
}
}
/* utf8_chars
*
* Wrapper: counts the actual unicode characters in a UTF-8 string.
*/
static int utf8_chars(utf8)
ZCONST char *utf8;
{
return utf8_to_ucs4_string(utf8, NULL, 0);
}
#endif /* unused */
/* --------------------------------------------------- */
/* Unicode Support
*
* These functions common for all Unicode ports.
*
* These functions should allocate and return strings that can be
* freed with free().
*
* 8/27/05 EG
*
* Use zwchar for wide char which is unsigned long
* in zip.h and 32 bits. This avoids problems with
* different sizes of wchar_t.
*/
#if 0 /* currently unused */
/* is_ascii_string
* Checks if a string is all ascii
*/
int is_ascii_string(mbstring)
ZCONST char *mbstring;
{
char *p;
uch c;
for (p = mbstring; c = (uch)*p; p++) {
if (c > 0x7F) {
return 0;
}
}
return 1;
}
/* local to UTF-8 */
char *local_to_utf8_string(local_string)
ZCONST char *local_string;
{
return wide_to_utf8_string(local_to_wide_string(local_string));
}
# endif /* unused */
/* wide_to_escape_string
provides a string that represents a wide char not in local char set
An initial try at an algorithm. Suggestions welcome.
According to the standard, Unicode character points are restricted to
the number range from 0 to 0x10FFFF, respective 21 bits.
For a hexadecimal notation, 2 octets are sufficient for the mostly
used characters from the "Basic Multilingual Plane", all other
Unicode characters can be represented by 3 octets (= 6 hex digits).
The Unicode standard suggests to write Unicode character points
as 4 resp. 6 hex digits, preprended by "U+".
(e.g.: U+10FFFF for the highest character point, or U+0030 for the ASCII
digit "0")
However, for the purpose of escaping non-ASCII chars in an ASCII character
stream, the "U" is not a very good escape initializer. Therefore, we
use the following convention within our Info-ZIP code:
If not an ASCII char probably need 2 bytes at least. So if
a 2-byte wide encode it as 4 hex digits with a leading #U. If
needs 3 bytes then prefix the string with #L. So
#U1234
is a 2-byte wide character with bytes 0x12 and 0x34 while
#L123456
is a 3-byte wide character with bytes 0x12, 0x34, 0x56.
On Windows, wide that need two wide characters need to be converted
to a single number.
*/
/* set this to the max bytes an escape can be */
#define MAX_ESCAPE_BYTES 8
char *wide_to_escape_string(wide_char)
zwchar wide_char;
{
int i;
zwchar w = wide_char;
uch b[sizeof(zwchar)];
char d[3];
char e[11];
int len;
char *r;
/* fill byte array with zeros */
memzero(b, sizeof(zwchar));
/* get bytes in right to left order */
for (len = 0; w; len++) {
b[len] = (char)(w % 0x100);
w /= 0x100;
}
strcpy(e, "#");
/* either 2 bytes or 3 bytes */
if (len <= 2) {
len = 2;
strcat(e, "U");
} else {
strcat(e, "L");
}
for (i = len - 1; i >= 0; i--) {
sprintf(d, "%02x", b[i]);
strcat(e, d);
}
if ((r = malloc(strlen(e) + 1)) == NULL) {
return NULL;
}
strcpy(r, e);
return r;
}
#if 0 /* currently unused */
/* returns the wide character represented by the escape string */
zwchar escape_string_to_wide(escape_string)
ZCONST char *escape_string;
{
int i;
zwchar w;
char c;
int len;
ZCONST char *e = escape_string;
if (e == NULL) {
return 0;
}
if (e[0] != '#') {
/* no leading # */
return 0;
}
len = strlen(e);
/* either #U1234 or #L123456 format */
if (len != 6 && len != 8) {
return 0;
}
w = 0;
if (e[1] == 'L') {
if (len != 8) {
return 0;
}
/* 3 bytes */
for (i = 2; i < 8; i++) {
c = e[i];
if (c < '0' || c > '9') {
return 0;
}
w = w * 0x10 + (zwchar)(c - '0');
}
} else if (e[1] == 'U') {
/* 2 bytes */
for (i = 2; i < 6; i++) {
c = e[i];
if (c < '0' || c > '9') {
return 0;
}
w = w * 0x10 + (zwchar)(c - '0');
}
}
return w;
}
#endif /* unused */
#ifndef WIN32 /* WIN32 supplies a special variant of this function */
/* convert wide character string to multi-byte character string */
char *wide_to_local_string(wide_string, escape_all)
ZCONST zwchar *wide_string;
int escape_all;
{
int i;
wchar_t wc;
int b;
int state_dependent;
int wsize = 0;
int max_bytes = MB_CUR_MAX;
char buf[9];
char *buffer = NULL;
char *local_string = NULL;
for (wsize = 0; wide_string[wsize]; wsize++) ;
if (max_bytes < MAX_ESCAPE_BYTES)
max_bytes = MAX_ESCAPE_BYTES;
if ((buffer = (char *)malloc(wsize * max_bytes + 1)) == NULL) {
return NULL;
}
/* convert it */
buffer[0] = '\0';
/* set initial state if state-dependent encoding */
wc = (wchar_t)'a';
b = wctomb(NULL, wc);
if (b == 0)
state_dependent = 0;
else
state_dependent = 1;
for (i = 0; i < wsize; i++) {
if (sizeof(wchar_t) < 4 && wide_string[i] > 0xFFFF) {
/* wchar_t probably 2 bytes */
/* could do surrogates if state_dependent and wctomb can do */
wc = zwchar_to_wchar_t_default_char;
} else {
wc = (wchar_t)wide_string[i];
}
b = wctomb(buf, wc);
if (escape_all) {
if (b == 1 && (uch)buf[0] <= 0x7f) {
/* ASCII */
strncat(buffer, buf, b);
} else {
/* use escape for wide character */
char *escape_string = wide_to_escape_string(wide_string[i]);
strcat(buffer, escape_string);
free(escape_string);
}
} else if (b > 0) {
/* multi-byte char */
strncat(buffer, buf, b);
} else {
/* no MB for this wide */
/* use escape for wide character */
char *escape_string = wide_to_escape_string(wide_string[i]);
strcat(buffer, escape_string);
free(escape_string);
}
}
if ((local_string = (char *)malloc(strlen(buffer) + 1)) != NULL) {
strcpy(local_string, buffer);
}
free(buffer);
return local_string;
}
#endif /* !WIN32 */
#if 0 /* currently unused */
/* convert local string to display character set string */
char *local_to_display_string(local_string)
ZCONST char *local_string;
{
char *display_string;
/* For Windows, OEM string should never be bigger than ANSI string, says
CharToOem description.
For all other ports, just make a copy of local_string.
*/
if ((display_string = (char *)malloc(strlen(local_string) + 1)) == NULL) {
return NULL;
}
strcpy(display_string, local_string);
#ifdef EBCDIC
{
char *ebc;
if ((ebc = malloc(strlen(display_string) + 1)) == NULL) {
return NULL;
}
strtoebc(ebc, display_string);
free(display_string);
display_string = ebc;
}
#endif
return display_string;
}
#endif /* unused */
/* UTF-8 to local */
char *utf8_to_local_string(utf8_string, escape_all)
ZCONST char *utf8_string;
int escape_all;
{
zwchar *wide = utf8_to_wide_string(utf8_string);
char *loc = wide_to_local_string(wide, escape_all);
free(wide);
return loc;
}
#if 0 /* currently unused */
/* convert multi-byte character string to wide character string */
zwchar *local_to_wide_string(local_string)
ZCONST char *local_string;
{
int wsize;
wchar_t *wc_string;
zwchar *wide_string;
/* for now try to convert as string - fails if a bad char in string */
wsize = mbstowcs(NULL, local_string, strlen(local_string) + 1);
if (wsize == (size_t)-1) {
/* could not convert */
return NULL;
}
/* convert it */
if ((wc_string = (wchar_t *)malloc((wsize + 1) * sizeof(wchar_t))) == NULL) {
return NULL;
}
wsize = mbstowcs(wc_string, local_string, strlen(local_string) + 1);
wc_string[wsize] = (wchar_t) 0;
/* in case wchar_t is not zwchar */
if ((wide_string = (zwchar *)malloc((wsize + 1) * sizeof(zwchar))) == NULL) {
return NULL;
}
for (wsize = 0; wide_string[wsize] = (zwchar)wc_string[wsize]; wsize++) ;
wide_string[wsize] = (zwchar) 0;
free(wc_string);
return wide_string;
}
/* convert wide string to UTF-8 */
char *wide_to_utf8_string(wide_string)
ZCONST zwchar *wide_string;
{
int mbcount;
char *utf8_string;
/* get size of utf8 string */
mbcount = ucs4_string_to_utf8(wide_string, NULL, 0);
if (mbcount == -1)
return NULL;
if ((utf8_string = (char *) malloc(mbcount + 1)) == NULL) {
return NULL;
}
mbcount = ucs4_string_to_utf8(wide_string, utf8_string, mbcount + 1);
if (mbcount == -1)
return NULL;
return utf8_string;
}
#endif /* unused */
/* convert UTF-8 string to wide string */
zwchar *utf8_to_wide_string(utf8_string)
ZCONST char *utf8_string;
{
int wcount;
zwchar *wide_string;
wcount = utf8_to_ucs4_string(utf8_string, NULL, 0);
if (wcount == -1)
return NULL;
if ((wide_string = (zwchar *) malloc((wcount + 1) * sizeof(zwchar)))
== NULL) {
return NULL;
}
wcount = utf8_to_ucs4_string(utf8_string, wide_string, wcount + 1);
return wide_string;
}
#endif /* UNICODE_WCHAR */
#endif /* UNICODE_SUPPORT */
#ifdef USE_EF_UT_TIME
#ifdef IZ_HAVE_UXUIDGID
static int read_ux3_value(dbuf, uidgid_sz, p_uidgid)
ZCONST uch *dbuf; /* buffer a uid or gid value */
unsigned uidgid_sz; /* size of uid/gid value */
ulg *p_uidgid; /* return storage: uid or gid value */
{
zusz_t uidgid64;
switch (uidgid_sz) {
case 2:
*p_uidgid = (ulg)makeword(dbuf);
break;
case 4:
*p_uidgid = (ulg)makelong(dbuf);
break;
case 8:
uidgid64 = makeint64(dbuf);
#ifndef LARGE_FILE_SUPPORT
if (uidgid64 == (zusz_t)0xffffffffL)
return FALSE;
#endif
*p_uidgid = (ulg)uidgid64;
if ((zusz_t)(*p_uidgid) != uidgid64)
return FALSE;
break;
}
return TRUE;
}
#endif /* IZ_HAVE_UXUIDGID */
/*******************************/
/* Function ef_scan_for_izux() */
/*******************************/
unsigned ef_scan_for_izux(ef_buf, ef_len, ef_is_c, dos_mdatetime,
z_utim, z_uidgid)
ZCONST uch *ef_buf; /* buffer containing extra field */
unsigned ef_len; /* total length of extra field */
int ef_is_c; /* flag indicating "is central extra field" */
ulg dos_mdatetime; /* last_mod_file_date_time in DOS format */
iztimes *z_utim; /* return storage: atime, mtime, ctime */
ulg *z_uidgid; /* return storage: uid and gid */
{
unsigned flags = 0;
unsigned eb_id;
unsigned eb_len;
int have_new_type_eb = 0;
long i_time; /* buffer for Unix style 32-bit integer time value */
#ifdef TIME_T_TYPE_DOUBLE
int ut_in_archive_sgn = 0;
#else
int ut_zip_unzip_compatible = FALSE;
#endif
/*---------------------------------------------------------------------------
This function scans the extra field for EF_TIME, EF_IZUNIX2, EF_IZUNIX, or
EF_PKUNIX blocks containing Unix-style time_t (GMT) values for the entry's
access, creation, and modification time.
If a valid block is found, the time stamps are copied to the iztimes
structure (provided the z_utim pointer is not NULL).
If a IZUNIX2 block is found or the IZUNIX block contains UID/GID fields,
and the z_uidgid array pointer is valid (!= NULL), the owner info is
transfered as well.
The presence of an EF_TIME or EF_IZUNIX2 block results in ignoring all
data from probably present obsolete EF_IZUNIX blocks.
If multiple blocks of the same type are found, only the information from
the last block is used.
The return value is a combination of the EF_TIME Flags field with an
additional flag bit indicating the presence of valid UID/GID info,
or 0 in case of failure.
---------------------------------------------------------------------------*/
if (ef_len == 0 || ef_buf == NULL || (z_utim == 0 && z_uidgid == NULL))
return 0;
TTrace((stderr,"\nef_scan_for_izux: scanning extra field of length %u\n",
ef_len));
while (ef_len >= EB_HEADSIZE) {
eb_id = makeword(EB_ID + ef_buf);
eb_len = makeword(EB_LEN + ef_buf);
if (eb_len > (ef_len - EB_HEADSIZE)) {
/* discovered some extra field inconsistency! */
TTrace((stderr,
"ef_scan_for_izux: block length %u > rest ef_size %u\n", eb_len,
ef_len - EB_HEADSIZE));
break;
}
switch (eb_id) {
case EF_TIME:
flags &= ~0x0ff; /* ignore previous IZUNIX or EF_TIME fields */
have_new_type_eb = 1;
if ( eb_len >= EB_UT_MINLEN && z_utim != NULL) {
unsigned eb_idx = EB_UT_TIME1;
TTrace((stderr,"ef_scan_for_izux: found TIME extra field\n"));
flags |= (ef_buf[EB_HEADSIZE+EB_UT_FLAGS] & 0x0ff);
if ((flags & EB_UT_FL_MTIME)) {
if ((eb_idx+4) <= eb_len) {
i_time = (long)makelong((EB_HEADSIZE+eb_idx) + ef_buf);
eb_idx += 4;
TTrace((stderr," UT e.f. modification time = %ld\n",
i_time));
#ifdef TIME_T_TYPE_DOUBLE
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
if (dos_mdatetime == DOSTIME_MINIMUM) {
ut_in_archive_sgn = -1;
z_utim->mtime =
(time_t)((long)i_time | (~(long)0x7fffffffL));
} else if (dos_mdatetime >= DOSTIME_2038_01_18) {
ut_in_archive_sgn = 1;
z_utim->mtime =
(time_t)((ulg)i_time & (ulg)0xffffffffL);
} else {
ut_in_archive_sgn = 0;
/* cannot determine sign of mtime;
without modtime: ignore complete UT field */
flags &= ~0x0ff; /* no time_t times available */
TTrace((stderr,
" UT modtime range error; ignore e.f.!\n"));
break; /* stop scanning this field */
}
} else {
/* cannot determine, safe assumption is FALSE */
ut_in_archive_sgn = 0;
z_utim->mtime = (time_t)i_time;
}
#else /* !TIME_T_TYPE_DOUBLE */
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
ut_zip_unzip_compatible =
((time_t)0x80000000L < (time_t)0L)
? (dos_mdatetime == DOSTIME_MINIMUM)
: (dos_mdatetime >= DOSTIME_2038_01_18);
if (!ut_zip_unzip_compatible) {
/* UnZip interprets mtime differently than Zip;
without modtime: ignore complete UT field */
flags &= ~0x0ff; /* no time_t times available */
TTrace((stderr,
" UT modtime range error; ignore e.f.!\n"));
break; /* stop scanning this field */
}
} else {
/* cannot determine, safe assumption is FALSE */
ut_zip_unzip_compatible = FALSE;
}
z_utim->mtime = (time_t)i_time;
#endif /* ?TIME_T_TYPE_DOUBLE */
} else {
flags &= ~EB_UT_FL_MTIME;
TTrace((stderr," UT e.f. truncated; no modtime\n"));
}
}
if (ef_is_c) {
break; /* central version of TIME field ends here */
}
if (flags & EB_UT_FL_ATIME) {
if ((eb_idx+4) <= eb_len) {
i_time = (long)makelong((EB_HEADSIZE+eb_idx) + ef_buf);
eb_idx += 4;
TTrace((stderr," UT e.f. access time = %ld\n",
i_time));
#ifdef TIME_T_TYPE_DOUBLE
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
if (ut_in_archive_sgn == -1)
z_utim->atime =
(time_t)((long)i_time | (~(long)0x7fffffffL));
} else if (ut_in_archive_sgn == 1) {
z_utim->atime =
(time_t)((ulg)i_time & (ulg)0xffffffffL);
} else {
/* sign of 32-bit time is unknown -> ignore it */
flags &= ~EB_UT_FL_ATIME;
TTrace((stderr,
" UT access time range error: skip time!\n"));
}
} else {
z_utim->atime = (time_t)i_time;
}
#else /* !TIME_T_TYPE_DOUBLE */
if (((ulg)(i_time) & (ulg)(0x80000000L)) &&
!ut_zip_unzip_compatible) {
flags &= ~EB_UT_FL_ATIME;
TTrace((stderr,
" UT access time range error: skip time!\n"));
} else {
z_utim->atime = (time_t)i_time;
}
#endif /* ?TIME_T_TYPE_DOUBLE */
} else {
flags &= ~EB_UT_FL_ATIME;
}
}
if (flags & EB_UT_FL_CTIME) {
if ((eb_idx+4) <= eb_len) {
i_time = (long)makelong((EB_HEADSIZE+eb_idx) + ef_buf);
TTrace((stderr," UT e.f. creation time = %ld\n",
i_time));
#ifdef TIME_T_TYPE_DOUBLE
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
if (ut_in_archive_sgn == -1)
z_utim->ctime =
(time_t)((long)i_time | (~(long)0x7fffffffL));
} else if (ut_in_archive_sgn == 1) {
z_utim->ctime =
(time_t)((ulg)i_time & (ulg)0xffffffffL);
} else {
/* sign of 32-bit time is unknown -> ignore it */
flags &= ~EB_UT_FL_CTIME;
TTrace((stderr,
" UT creation time range error: skip time!\n"));
}
} else {
z_utim->ctime = (time_t)i_time;
}
#else /* !TIME_T_TYPE_DOUBLE */
if (((ulg)(i_time) & (ulg)(0x80000000L)) &&
!ut_zip_unzip_compatible) {
flags &= ~EB_UT_FL_CTIME;
TTrace((stderr,
" UT creation time range error: skip time!\n"));
} else {
z_utim->ctime = (time_t)i_time;
}
#endif /* ?TIME_T_TYPE_DOUBLE */
} else {
flags &= ~EB_UT_FL_CTIME;
}
}
}
break;
case EF_IZUNIX2:
if (have_new_type_eb == 0) {
flags &= ~0x0ff; /* ignore any previous IZUNIX field */
have_new_type_eb = 1;
}
#ifdef IZ_HAVE_UXUIDGID
if (have_new_type_eb > 1)
break; /* IZUNIX3 overrides IZUNIX2 e.f. block ! */
if (eb_len == EB_UX2_MINLEN && z_uidgid != NULL) {
z_uidgid[0] = (ulg)makeword((EB_HEADSIZE+EB_UX2_UID) + ef_buf);
z_uidgid[1] = (ulg)makeword((EB_HEADSIZE+EB_UX2_GID) + ef_buf);
flags |= EB_UX2_VALID; /* signal success */
}
#endif
break;
case EF_IZUNIX3:
/* new 3rd generation Unix ef */
have_new_type_eb = 2;
/*
Version 1 byte version of this extra field, currently 1
UIDSize 1 byte Size of UID field
UID Variable UID for this entry
GIDSize 1 byte Size of GID field
GID Variable GID for this entry
*/
#ifdef IZ_HAVE_UXUIDGID
if (eb_len >= EB_UX3_MINLEN
&& z_uidgid != NULL
&& (*((EB_HEADSIZE + 0) + ef_buf) == 1)
/* only know about version 1 */
{
uch uid_size;
uch gid_size;
uid_size = *((EB_HEADSIZE + 1) + ef_buf);
gid_size = *((EB_HEADSIZE + uid_size + 2) + ef_buf);
flags &= ~0x0ff; /* ignore any previous UNIX field */
if ( read_ux3_value((EB_HEADSIZE + 2) + ef_buf,
uid_size, z_uidgid[0])
&&
read_ux3_value((EB_HEADSIZE + uid_size + 3) + ef_buf,
gid_size, z_uidgid[1]) )
{
flags |= EB_UX2_VALID; /* signal success */
}
}
#endif /* IZ_HAVE_UXUIDGID */
break;
case EF_IZUNIX:
case EF_PKUNIX: /* PKUNIX e.f. layout is identical to IZUNIX */
if (eb_len >= EB_UX_MINLEN) {
TTrace((stderr,"ef_scan_for_izux: found %s extra field\n",
(eb_id == EF_IZUNIX ? "IZUNIX" : "PKUNIX")));
if (have_new_type_eb > 0) {
break; /* Ignore IZUNIX extra field block ! */
}
if (z_utim != NULL) {
flags |= (EB_UT_FL_MTIME | EB_UT_FL_ATIME);
i_time = (long)makelong((EB_HEADSIZE+EB_UX_MTIME)+ef_buf);
TTrace((stderr," Unix EF modtime = %ld\n", i_time));
#ifdef TIME_T_TYPE_DOUBLE
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
if (dos_mdatetime == DOSTIME_MINIMUM) {
ut_in_archive_sgn = -1;
z_utim->mtime =
(time_t)((long)i_time | (~(long)0x7fffffffL));
} else if (dos_mdatetime >= DOSTIME_2038_01_18) {
ut_in_archive_sgn = 1;
z_utim->mtime =
(time_t)((ulg)i_time & (ulg)0xffffffffL);
} else {
ut_in_archive_sgn = 0;
/* cannot determine sign of mtime;
without modtime: ignore complete UT field */
flags &= ~0x0ff; /* no time_t times available */
TTrace((stderr,
" UX modtime range error: ignore e.f.!\n"));
}
} else {
/* cannot determine, safe assumption is FALSE */
ut_in_archive_sgn = 0;
z_utim->mtime = (time_t)i_time;
}
#else /* !TIME_T_TYPE_DOUBLE */
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
ut_zip_unzip_compatible =
((time_t)0x80000000L < (time_t)0L)
? (dos_mdatetime == DOSTIME_MINIMUM)
: (dos_mdatetime >= DOSTIME_2038_01_18);
if (!ut_zip_unzip_compatible) {
/* UnZip interpretes mtime differently than Zip;
without modtime: ignore complete UT field */
flags &= ~0x0ff; /* no time_t times available */
TTrace((stderr,
" UX modtime range error: ignore e.f.!\n"));
}
} else {
/* cannot determine, safe assumption is FALSE */
ut_zip_unzip_compatible = FALSE;
}
z_utim->mtime = (time_t)i_time;
#endif /* ?TIME_T_TYPE_DOUBLE */
i_time = (long)makelong((EB_HEADSIZE+EB_UX_ATIME)+ef_buf);
TTrace((stderr," Unix EF actime = %ld\n", i_time));
#ifdef TIME_T_TYPE_DOUBLE
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
if (ut_in_archive_sgn == -1)
z_utim->atime =
(time_t)((long)i_time | (~(long)0x7fffffffL));
} else if (ut_in_archive_sgn == 1) {
z_utim->atime =
(time_t)((ulg)i_time & (ulg)0xffffffffL);
} else if (flags & 0x0ff) {
/* sign of 32-bit time is unknown -> ignore it */
flags &= ~EB_UT_FL_ATIME;
TTrace((stderr,
" UX access time range error: skip time!\n"));
}
} else {
z_utim->atime = (time_t)i_time;
}
#else /* !TIME_T_TYPE_DOUBLE */
if (((ulg)(i_time) & (ulg)(0x80000000L)) &&
!ut_zip_unzip_compatible && (flags & 0x0ff)) {
/* atime not in range of UnZip's time_t */
flags &= ~EB_UT_FL_ATIME;
TTrace((stderr,
" UX access time range error: skip time!\n"));
} else {
z_utim->atime = (time_t)i_time;
}
#endif /* ?TIME_T_TYPE_DOUBLE */
}
#ifdef IZ_HAVE_UXUIDGID
if (eb_len >= EB_UX_FULLSIZE && z_uidgid != NULL) {
z_uidgid[0] = makeword((EB_HEADSIZE+EB_UX_UID) + ef_buf);
z_uidgid[1] = makeword((EB_HEADSIZE+EB_UX_GID) + ef_buf);
flags |= EB_UX2_VALID;
}
#endif /* IZ_HAVE_UXUIDGID */
}
break;
default:
break;
}
/* Skip this extra field block */
ef_buf += (eb_len + EB_HEADSIZE);
ef_len -= (eb_len + EB_HEADSIZE);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400'], 'message': 'Detect and reject a zip bomb using overlapped entries.
This detects an invalid zip file that has at least one entry that
overlaps with another entry or with the central directory to the
end of the file. A Fifield zip bomb uses overlapped local entries
to vastly increase the potential inflation ratio. Such an invalid
zip file is rejected.
See https://www.bamsoftware.com/hacks/zipbomb/ for David Fifield's
analysis, construction, and examples of such zip bombs.
The detection maintains a list of covered spans of the zip files
so far, where the central directory to the end of the file and any
bytes preceding the first entry at zip file offset zero are
considered covered initially. Then as each entry is decompressed
or tested, it is considered covered. When a new entry is about to
be processed, its initial offset is checked to see if it is
contained by a covered span. If so, the zip file is rejected as
invalid.
This commit depends on a preceding commit: "Fix bug in
undefer_input() that misplaced the input state."'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int do_seekable(__G__ lastchance) /* return PK-type error code */
__GDEF
int lastchance;
{
#ifndef SFX
/* static int no_ecrec = FALSE; SKM: moved to globals.h */
int maybe_exe=FALSE;
int too_weird_to_continue=FALSE;
#ifdef TIMESTAMP
time_t uxstamp;
ulg nmember = 0L;
#endif
#endif
int error=0, error_in_archive;
/*---------------------------------------------------------------------------
Open the zipfile for reading in BINARY mode to prevent CR/LF translation,
which would corrupt the bit streams.
---------------------------------------------------------------------------*/
if (SSTAT(G.zipfn, &G.statbuf) ||
#ifdef THEOS
(error = S_ISLIB(G.statbuf.st_mode)) != 0 ||
#endif
(error = S_ISDIR(G.statbuf.st_mode)) != 0)
{
#ifndef SFX
if (lastchance && (uO.qflag < 3)) {
#if defined(UNIX) || defined(QDOS)
if (G.no_ecrec)
Info(slide, 1, ((char *)slide,
LoadFarString(CannotFindZipfileDirMsg),
LoadFarStringSmall((uO.zipinfo_mode ? Zipnfo : Unzip)),
G.wildzipfn, uO.zipinfo_mode? " " : "", G.wildzipfn,
G.zipfn));
else
Info(slide, 1, ((char *)slide,
LoadFarString(CannotFindEitherZipfile),
LoadFarStringSmall((uO.zipinfo_mode ? Zipnfo : Unzip)),
G.wildzipfn, G.wildzipfn, G.zipfn));
#else /* !(UNIX || QDOS) */
if (G.no_ecrec)
Info(slide, 0x401, ((char *)slide,
LoadFarString(CannotFindZipfileDirMsg),
LoadFarStringSmall((uO.zipinfo_mode ? Zipnfo : Unzip)),
G.wildzipfn, uO.zipinfo_mode? " " : "", G.zipfn));
else
#ifdef VMS
Info(slide, 0x401, ((char *)slide,
LoadFarString(CannotFindEitherZipfile),
LoadFarStringSmall((uO.zipinfo_mode ? Zipnfo : Unzip)),
G.wildzipfn,
(*G.zipfn ? G.zipfn : vms_msg_text())));
#else /* !VMS */
Info(slide, 0x401, ((char *)slide,
LoadFarString(CannotFindEitherZipfile),
LoadFarStringSmall((uO.zipinfo_mode ? Zipnfo : Unzip)),
G.wildzipfn, G.zipfn));
#endif /* ?VMS */
#endif /* ?(UNIX || QDOS) */
}
#endif /* !SFX */
return error? IZ_DIR : PK_NOZIP;
}
G.ziplen = G.statbuf.st_size;
#ifndef SFX
#if defined(UNIX) || defined(DOS_OS2_W32) || defined(THEOS)
if (G.statbuf.st_mode & S_IEXEC) /* no extension on Unix exes: might */
maybe_exe = TRUE; /* find unzip, not unzip.zip; etc. */
#endif
#endif /* !SFX */
#ifdef VMS
if (check_format(__G)) /* check for variable-length format */
return PK_ERR;
#endif
if (open_input_file(__G)) /* this should never happen, given */
return PK_NOZIP; /* the stat() test above, but... */
#ifdef DO_SAFECHECK_2GB
/* Need more care: Do not trust the size returned by stat() but
determine it by reading beyond the end of the file. */
G.ziplen = file_size(G.zipfd);
if (G.ziplen == EOF) {
Info(slide, 0x401, ((char *)slide, LoadFarString(ZipfileTooBig)));
/*
printf(
" We need a better error message for: 64-bit file, 32-bit program.\n");
*/
CLOSE_INFILE();
return IZ_ERRBF;
}
#endif /* DO_SAFECHECK_2GB */
/*---------------------------------------------------------------------------
Find and process the end-of-central-directory header. UnZip need only
check last 65557 bytes of zipfile: comment may be up to 65535, end-of-
central-directory record is 18 bytes, and signature itself is 4 bytes;
add some to allow for appended garbage. Since ZipInfo is often used as
a debugging tool, search the whole zipfile if zipinfo_mode is true.
---------------------------------------------------------------------------*/
G.cur_zipfile_bufstart = 0;
G.inptr = G.inbuf;
#if ((!defined(WINDLL) && !defined(SFX)) || !defined(NO_ZIPINFO))
# if (!defined(WINDLL) && !defined(SFX))
if ( (!uO.zipinfo_mode && !uO.qflag
# ifdef TIMESTAMP
&& !uO.T_flag
# endif
)
# ifndef NO_ZIPINFO
|| (uO.zipinfo_mode && uO.hflag)
# endif
)
# else /* not (!WINDLL && !SFX) ==> !NO_ZIPINFO !! */
if (uO.zipinfo_mode && uO.hflag)
# endif /* if..else..: (!WINDLL && !SFX) */
# ifdef WIN32 /* Win32 console may require codepage conversion for G.zipfn */
Info(slide, 0, ((char *)slide, LoadFarString(LogInitline),
FnFilter1(G.zipfn)));
# else
Info(slide, 0, ((char *)slide, LoadFarString(LogInitline), G.zipfn));
# endif
#endif /* (!WINDLL && !SFX) || !NO_ZIPINFO */
if ( (error_in_archive = find_ecrec(__G__
#ifndef NO_ZIPINFO
uO.zipinfo_mode ? G.ziplen :
#endif
MIN(G.ziplen, 66000L)))
> PK_WARN )
{
CLOSE_INFILE();
#ifdef SFX
++lastchance; /* avoid picky compiler warnings */
return error_in_archive;
#else
if (maybe_exe)
Info(slide, 0x401, ((char *)slide, LoadFarString(MaybeExe),
G.zipfn));
if (lastchance)
return error_in_archive;
else {
G.no_ecrec = TRUE; /* assume we found wrong file: e.g., */
return PK_NOZIP; /* unzip instead of unzip.zip */
}
#endif /* ?SFX */
}
if ((uO.zflag > 0) && !uO.zipinfo_mode) { /* unzip: zflag = comment ONLY */
CLOSE_INFILE();
return error_in_archive;
}
/*---------------------------------------------------------------------------
Test the end-of-central-directory info for incompatibilities (multi-disk
archives) or inconsistencies (missing or extra bytes in zipfile).
---------------------------------------------------------------------------*/
#ifdef NO_MULTIPART
error = !uO.zipinfo_mode && (G.ecrec.number_this_disk == 1) &&
(G.ecrec.num_disk_start_cdir == 1);
#else
error = !uO.zipinfo_mode && (G.ecrec.number_this_disk != 0);
#endif
#ifndef SFX
if (uO.zipinfo_mode &&
G.ecrec.number_this_disk != G.ecrec.num_disk_start_cdir)
{
if (G.ecrec.number_this_disk > G.ecrec.num_disk_start_cdir) {
Info(slide, 0x401, ((char *)slide,
LoadFarString(CentDirNotInZipMsg), G.zipfn,
(ulg)G.ecrec.number_this_disk,
(ulg)G.ecrec.num_disk_start_cdir));
error_in_archive = PK_FIND;
too_weird_to_continue = TRUE;
} else {
Info(slide, 0x401, ((char *)slide,
LoadFarString(EndCentDirBogus), G.zipfn,
(ulg)G.ecrec.number_this_disk,
(ulg)G.ecrec.num_disk_start_cdir));
error_in_archive = PK_WARN;
}
#ifdef NO_MULTIPART /* concatenation of multiple parts works in some cases */
} else if (!uO.zipinfo_mode && !error && G.ecrec.number_this_disk != 0) {
Info(slide, 0x401, ((char *)slide, LoadFarString(NoMultiDiskArcSupport),
G.zipfn));
error_in_archive = PK_FIND;
too_weird_to_continue = TRUE;
#endif
}
if (!too_weird_to_continue) { /* (relatively) normal zipfile: go for it */
if (error) {
Info(slide, 0x401, ((char *)slide, LoadFarString(MaybePakBug),
G.zipfn));
error_in_archive = PK_WARN;
}
#endif /* !SFX */
if ((G.extra_bytes = G.real_ecrec_offset-G.expect_ecrec_offset) <
(zoff_t)0)
{
Info(slide, 0x401, ((char *)slide, LoadFarString(MissingBytes),
G.zipfn, FmZofft((-G.extra_bytes), NULL, NULL)));
error_in_archive = PK_ERR;
} else if (G.extra_bytes > 0) {
if ((G.ecrec.offset_start_central_directory == 0) &&
(G.ecrec.size_central_directory != 0)) /* zip 1.5 -go bug */
{
Info(slide, 0x401, ((char *)slide,
LoadFarString(NullCentDirOffset), G.zipfn));
G.ecrec.offset_start_central_directory = G.extra_bytes;
G.extra_bytes = 0;
error_in_archive = PK_ERR;
}
#ifndef SFX
else {
Info(slide, 0x401, ((char *)slide,
LoadFarString(ExtraBytesAtStart), G.zipfn,
FmZofft(G.extra_bytes, NULL, NULL),
(G.extra_bytes == 1)? "":"s"));
error_in_archive = PK_WARN;
}
#endif /* !SFX */
}
/*-----------------------------------------------------------------------
Check for empty zipfile and exit now if so.
-----------------------------------------------------------------------*/
if (G.expect_ecrec_offset==0L && G.ecrec.size_central_directory==0) {
if (uO.zipinfo_mode)
Info(slide, 0, ((char *)slide, "%sEmpty zipfile.\n",
uO.lflag>9? "\n " : ""));
else
Info(slide, 0x401, ((char *)slide, LoadFarString(ZipfileEmpty),
G.zipfn));
CLOSE_INFILE();
return (error_in_archive > PK_WARN)? error_in_archive : PK_WARN;
}
/*-----------------------------------------------------------------------
Compensate for missing or extra bytes, and seek to where the start
of central directory should be. If header not found, uncompensate
and try again (necessary for at least some Atari archives created
with STZip, as well as archives created by J.H. Holm's ZIPSPLIT 1.1).
-----------------------------------------------------------------------*/
error = seek_zipf(__G__ G.ecrec.offset_start_central_directory);
if (error == PK_BADERR) {
CLOSE_INFILE();
return PK_BADERR;
}
#ifdef OLD_SEEK_TEST
if (error != PK_OK || readbuf(__G__ G.sig, 4) == 0) {
CLOSE_INFILE();
return PK_ERR; /* file may be locked, or possibly disk error(?) */
}
if (memcmp(G.sig, central_hdr_sig, 4))
#else
if ((error != PK_OK) || (readbuf(__G__ G.sig, 4) == 0) ||
memcmp(G.sig, central_hdr_sig, 4))
#endif
{
#ifndef SFX
zoff_t tmp = G.extra_bytes;
#endif
G.extra_bytes = 0;
error = seek_zipf(__G__ G.ecrec.offset_start_central_directory);
if ((error != PK_OK) || (readbuf(__G__ G.sig, 4) == 0) ||
memcmp(G.sig, central_hdr_sig, 4))
{
if (error != PK_BADERR)
Info(slide, 0x401, ((char *)slide,
LoadFarString(CentDirStartNotFound), G.zipfn,
LoadFarStringSmall(ReportMsg)));
CLOSE_INFILE();
return (error != PK_OK ? error : PK_BADERR);
}
#ifndef SFX
Info(slide, 0x401, ((char *)slide, LoadFarString(CentDirTooLong),
G.zipfn, FmZofft((-tmp), NULL, NULL)));
#endif
error_in_archive = PK_ERR;
}
/*-----------------------------------------------------------------------
Seek to the start of the central directory one last time, since we
have just read the first entry's signature bytes; then list, extract
or test member files as instructed, and close the zipfile.
-----------------------------------------------------------------------*/
error = seek_zipf(__G__ G.ecrec.offset_start_central_directory);
if (error != PK_OK) {
CLOSE_INFILE();
return error;
}
Trace((stderr, "about to extract/list files (error = %d)\n",
error_in_archive));
#ifdef DLL
/* G.fValidate is used only to look at an archive to see if
it appears to be a valid archive. There is no interest
in what the archive contains, nor in validating that the
entries in the archive are in good condition. This is
currently used only in the Windows DLLs for purposes of
checking archives within an archive to determine whether
or not to display the inner archives.
*/
if (!G.fValidate)
#endif
{
#ifndef NO_ZIPINFO
if (uO.zipinfo_mode)
error = zipinfo(__G); /* ZIPINFO 'EM */
else
#endif
#ifndef SFX
#ifdef TIMESTAMP
if (uO.T_flag)
error = get_time_stamp(__G__ &uxstamp, &nmember);
else
#endif
if (uO.vflag && !uO.tflag && !uO.cflag)
error = list_files(__G); /* LIST 'EM */
else
#endif /* !SFX */
error = extract_or_test_files(__G); /* EXTRACT OR TEST 'EM */
Trace((stderr, "done with extract/list files (error = %d)\n",
error));
}
if (error > error_in_archive) /* don't overwrite stronger error */
error_in_archive = error; /* with (for example) a warning */
#ifndef SFX
} /* end if (!too_weird_to_continue) */
#endif
CLOSE_INFILE();
#ifdef TIMESTAMP
if (uO.T_flag && !uO.zipinfo_mode && (nmember > 0L)) {
# ifdef WIN32
if (stamp_file(__G__ G.zipfn, uxstamp)) { /* TIME-STAMP 'EM */
# else
if (stamp_file(G.zipfn, uxstamp)) { /* TIME-STAMP 'EM */
# endif
if (uO.qflag < 3)
Info(slide, 0x201, ((char *)slide,
LoadFarString(ZipTimeStampFailed), G.zipfn));
if (error_in_archive < PK_WARN)
error_in_archive = PK_WARN;
} else {
if (!uO.qflag)
Info(slide, 0, ((char *)slide,
LoadFarString(ZipTimeStampSuccess), G.zipfn));
}
}
#endif
return error_in_archive;
} /* end function do_seekable() */
#ifdef DO_SAFECHECK_2GB
/************************/
/* Function file_size() */
/************************/
/* File size determination which does not mislead for large files in a
small-file program. Probably should be somewhere else.
The file has to be opened previously
*/
#ifdef USE_STRM_INPUT
static zoff_t file_size(file)
FILE *file;
{
int sts;
size_t siz;
#else /* !USE_STRM_INPUT */
static zoff_t file_size(fh)
int fh;
{
int siz;
#endif /* ?USE_STRM_INPUT */
zoff_t ofs;
char waste[4];
#ifdef USE_STRM_INPUT
/* Seek to actual EOF. */
sts = zfseeko(file, 0, SEEK_END);
if (sts != 0) {
/* fseeko() failed. (Unlikely.) */
ofs = EOF;
} else {
/* Get apparent offset at EOF. */
ofs = zftello(file);
if (ofs < 0) {
/* Offset negative (overflow). File too big. */
ofs = EOF;
} else {
/* Seek to apparent EOF offset.
Won't be at actual EOF if offset was truncated.
*/
sts = zfseeko(file, ofs, SEEK_SET);
if (sts != 0) {
/* fseeko() failed. (Unlikely.) */
ofs = EOF;
} else {
/* Read a byte at apparent EOF. Should set EOF flag. */
siz = fread(waste, 1, 1, file);
if (feof(file) == 0) {
/* Not at EOF, but should be. File too big. */
ofs = EOF;
}
}
}
}
#else /* !USE_STRM_INPUT */
/* Seek to actual EOF. */
ofs = zlseek(fh, 0, SEEK_END);
if (ofs == (zoff_t) -1) {
/* zlseek() failed. (Unlikely.) */
ofs = EOF;
} else if (ofs < 0) {
/* Offset negative (overflow). File too big. */
ofs = EOF;
} else {
/* Seek to apparent EOF offset.
Won't be at actual EOF if offset was truncated.
*/
ofs = zlseek(fh, ofs, SEEK_SET);
if (ofs == (zoff_t) -1) {
/* zlseek() failed. (Unlikely.) */
ofs = EOF;
} else {
/* Read a byte at apparent EOF. Should set EOF flag. */
siz = read(fh, waste, 1);
if (siz != 0) {
/* Not at EOF, but should be. File too big. */
ofs = EOF;
}
}
}
#endif /* ?USE_STRM_INPUT */
return ofs;
} /* end function file_size() */
#endif /* DO_SAFECHECK_2GB */
/***********************/
/* Function rec_find() */
/***********************/
static int rec_find(__G__ searchlen, signature, rec_size)
/* return 0 when rec found, 1 when not found, 2 in case of read error */
__GDEF
zoff_t searchlen;
char* signature;
int rec_size;
{
int i, numblks, found=FALSE;
zoff_t tail_len;
/*---------------------------------------------------------------------------
Zipfile is longer than INBUFSIZ: may need to loop. Start with short
block at end of zipfile (if not TOO short).
---------------------------------------------------------------------------*/
if ((tail_len = G.ziplen % INBUFSIZ) > rec_size) {
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, G.ziplen-tail_len, SEEK_SET);
G.cur_zipfile_bufstart = zftello(G.zipfd);
#else /* !USE_STRM_INPUT */
G.cur_zipfile_bufstart = zlseek(G.zipfd, G.ziplen-tail_len, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd, (char *)G.inbuf,
(unsigned int)tail_len)) != (int)tail_len)
return 2; /* it's expedient... */
/* 'P' must be at least (rec_size+4) bytes from end of zipfile */
for (G.inptr = G.inbuf+(int)tail_len-(rec_size+4);
G.inptr >= G.inbuf;
--G.inptr) {
if ( (*G.inptr == (uch)0x50) && /* ASCII 'P' */
!memcmp((char *)G.inptr, signature, 4) ) {
G.incnt -= (int)(G.inptr - G.inbuf);
found = TRUE;
break;
}
}
/* sig may span block boundary: */
memcpy((char *)G.hold, (char *)G.inbuf, 3);
} else
G.cur_zipfile_bufstart = G.ziplen - tail_len;
/*-----------------------------------------------------------------------
Loop through blocks of zipfile data, starting at the end and going
toward the beginning. In general, need not check whole zipfile for
signature, but may want to do so if testing.
-----------------------------------------------------------------------*/
numblks = (int)((searchlen - tail_len + (INBUFSIZ-1)) / INBUFSIZ);
/* ==amount= ==done== ==rounding== =blksiz= */
for (i = 1; !found && (i <= numblks); ++i) {
G.cur_zipfile_bufstart -= INBUFSIZ;
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, G.cur_zipfile_bufstart, SEEK_SET);
#else /* !USE_STRM_INPUT */
zlseek(G.zipfd, G.cur_zipfile_bufstart, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd,(char *)G.inbuf,INBUFSIZ))
!= INBUFSIZ)
return 2; /* read error is fatal failure */
for (G.inptr = G.inbuf+INBUFSIZ-1; G.inptr >= G.inbuf; --G.inptr)
if ( (*G.inptr == (uch)0x50) && /* ASCII 'P' */
!memcmp((char *)G.inptr, signature, 4) ) {
G.incnt -= (int)(G.inptr - G.inbuf);
found = TRUE;
break;
}
/* sig may span block boundary: */
memcpy((char *)G.hold, (char *)G.inbuf, 3);
}
return (found ? 0 : 1);
} /* end function rec_find() */
#if 0
/********************************/
/* Function check_ecrec_zip64() */
/********************************/
static int check_ecrec_zip64(__G)
__GDEF
{
return G.ecrec.offset_start_central_directory == 0xFFFFFFFFL
|| G.ecrec.size_central_directory == 0xFFFFFFFFL
|| G.ecrec.total_entries_central_dir == 0xFFFF
|| G.ecrec.num_entries_centrl_dir_ths_disk == 0xFFFF
|| G.ecrec.num_disk_start_cdir == 0xFFFF
|| G.ecrec.number_this_disk == 0xFFFF;
} /* end function check_ecrec_zip64() */
#endif /* never */
/***************************/
/* Function find_ecrec64() */
/***************************/
static int find_ecrec64(__G__ searchlen) /* return PK-class error */
__GDEF
zoff_t searchlen;
{
ec_byte_rec64 byterec; /* buf for ecrec64 */
ec_byte_loc64 byterecL; /* buf for ecrec64 locator */
zoff_t ecloc64_start_offset; /* start offset of ecrec64 locator */
zusz_t ecrec64_start_offset; /* start offset of ecrec64 */
zuvl_t ecrec64_start_disk; /* start disk of ecrec64 */
zuvl_t ecloc64_total_disks; /* total disks */
zuvl_t ecrec64_disk_cdstart; /* disk number of central dir start */
zucn_t ecrec64_this_entries; /* entries on disk with ecrec64 */
zucn_t ecrec64_tot_entries; /* total number of entries */
zusz_t ecrec64_cdirsize; /* length of central dir */
zusz_t ecrec64_offs_cdstart; /* offset of central dir start */
/* First, find the ecrec64 locator. By definition, this must be before
ecrec with nothing in between. We back up the size of the ecrec64
locator and check. */
ecloc64_start_offset = G.real_ecrec_offset - (ECLOC64_SIZE+4);
if (ecloc64_start_offset < 0)
/* Seeking would go past beginning, so probably empty archive */
return PK_COOL;
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, ecloc64_start_offset, SEEK_SET);
G.cur_zipfile_bufstart = zftello(G.zipfd);
#else /* !USE_STRM_INPUT */
G.cur_zipfile_bufstart = zlseek(G.zipfd, ecloc64_start_offset, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd, (char *)byterecL, ECLOC64_SIZE+4))
!= (ECLOC64_SIZE+4)) {
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchErr)));
return PK_ERR;
}
if (memcmp((char *)byterecL, end_centloc64_sig, 4) ) {
/* not found */
return PK_COOL;
}
/* Read the locator. */
ecrec64_start_disk = (zuvl_t)makelong(&byterecL[NUM_DISK_START_EOCDR64]);
ecrec64_start_offset = (zusz_t)makeint64(&byterecL[OFFSET_START_EOCDR64]);
ecloc64_total_disks = (zuvl_t)makelong(&byterecL[NUM_THIS_DISK_LOC64]);
/* Check for consistency */
#ifdef TEST
fprintf(stdout,"\nnumber of disks (ECR) %u, (ECLOC64) %lu\n",
G.ecrec.number_this_disk, ecloc64_total_disks); fflush(stdout);
#endif
if ((G.ecrec.number_this_disk != 0xFFFF) &&
(G.ecrec.number_this_disk != ecloc64_total_disks - 1)) {
/* Note: For some unknown reason, the developers at PKWARE decided to
store the "zip64 total disks" value as a counter starting from 1,
whereas all other "split/span volume" related fields use 0-based
volume numbers. Sigh... */
/* When the total number of disks as found in the traditional ecrec
is not 0xFFFF, the disk numbers in ecrec and ecloc64 must match.
When this is not the case, the found ecrec64 locator cannot be valid.
-> This is not a Zip64 archive.
*/
Trace((stderr,
"\ninvalid ECLOC64, differing disk# (ECR %u, ECL64 %lu)\n",
G.ecrec.number_this_disk, ecloc64_total_disks - 1));
return PK_COOL;
}
/* If found locator, look for ecrec64 where the locator says it is. */
/* For now assume that ecrec64 is on the same disk as ecloc64 and ecrec,
which is usually the case and is how Zip writes it. To do this right,
however, we should allow the ecrec64 to be on another disk since
the AppNote allows it and the ecrec64 can be large, especially if
Version 2 is used (AppNote uses 8 bytes for the size of this record). */
/* FIX BELOW IF ADD SUPPORT FOR MULTIPLE DISKS */
if (ecrec64_start_offset > (zusz_t)ecloc64_start_offset) {
/* ecrec64 has to be before ecrec64 locator */
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchErr)));
return PK_ERR;
}
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, ecrec64_start_offset, SEEK_SET);
G.cur_zipfile_bufstart = zftello(G.zipfd);
#else /* !USE_STRM_INPUT */
G.cur_zipfile_bufstart = zlseek(G.zipfd, ecrec64_start_offset, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd, (char *)byterec, ECREC64_SIZE+4))
!= (ECREC64_SIZE+4)) {
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchErr)));
return PK_ERR;
}
if (memcmp((char *)byterec, end_central64_sig, 4) ) {
/* Zip64 EOCD Record not found */
/* Since we already have seen the Zip64 EOCD Locator, it's
possible we got here because there are bytes prepended
to the archive, like the sfx prefix. */
/* Make a guess as to where the Zip64 EOCD Record might be */
ecrec64_start_offset = ecloc64_start_offset - ECREC64_SIZE - 4;
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, ecrec64_start_offset, SEEK_SET);
G.cur_zipfile_bufstart = zftello(G.zipfd);
#else /* !USE_STRM_INPUT */
G.cur_zipfile_bufstart = zlseek(G.zipfd, ecrec64_start_offset, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd, (char *)byterec, ECREC64_SIZE+4))
!= (ECREC64_SIZE+4)) {
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchErr)));
return PK_ERR;
}
if (memcmp((char *)byterec, end_central64_sig, 4) ) {
/* Zip64 EOCD Record not found */
/* Probably something not so easy to handle so exit */
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchErr)));
return PK_ERR;
}
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(Cent64EndSigSearchOff)));
}
/* Check consistency of found ecrec64 with ecloc64 (and ecrec): */
if ( (zuvl_t)makelong(&byterec[NUMBER_THIS_DSK_REC64])
!= ecrec64_start_disk )
/* found ecrec64 does not match ecloc64 info -> no Zip64 archive */
return PK_COOL;
/* Read all relevant ecrec64 fields and compare them to the corresponding
ecrec fields unless those are set to "all-ones".
*/
ecrec64_disk_cdstart =
(zuvl_t)makelong(&byterec[NUM_DISK_START_CEN_DIR64]);
if ( (G.ecrec.num_disk_start_cdir != 0xFFFF) &&
(G.ecrec.num_disk_start_cdir != ecrec64_disk_cdstart) )
return PK_COOL;
ecrec64_this_entries
= makeint64(&byterec[NUM_ENTRIES_CEN_DIR_THS_DISK64]);
if ( (G.ecrec.num_entries_centrl_dir_ths_disk != 0xFFFF) &&
(G.ecrec.num_entries_centrl_dir_ths_disk != ecrec64_this_entries) )
return PK_COOL;
ecrec64_tot_entries
= makeint64(&byterec[TOTAL_ENTRIES_CENTRAL_DIR64]);
if ( (G.ecrec.total_entries_central_dir != 0xFFFF) &&
(G.ecrec.total_entries_central_dir != ecrec64_tot_entries) )
return PK_COOL;
ecrec64_cdirsize
= makeint64(&byterec[SIZE_CENTRAL_DIRECTORY64]);
if ( (G.ecrec.size_central_directory != 0xFFFFFFFFL) &&
(G.ecrec.size_central_directory != ecrec64_cdirsize) )
return PK_COOL;
ecrec64_offs_cdstart
= makeint64(&byterec[OFFSET_START_CENTRAL_DIRECT64]);
if ( (G.ecrec.offset_start_central_directory != 0xFFFFFFFFL) &&
(G.ecrec.offset_start_central_directory != ecrec64_offs_cdstart) )
return PK_COOL;
/* Now, we are (almost) sure that we have a Zip64 archive. */
G.ecrec.have_ecr64 = 1;
/* Update the "end-of-central-dir offset" for later checks. */
G.real_ecrec_offset = ecrec64_start_offset;
/* Update all ecdir_rec data that are flagged to be invalid
in Zip64 mode. Set the ecrec64-mandatory flag when such a
case is found. */
if (G.ecrec.number_this_disk == 0xFFFF) {
G.ecrec.number_this_disk = ecrec64_start_disk;
if (ecrec64_start_disk != 0xFFFF) G.ecrec.is_zip64_archive = TRUE;
}
if (G.ecrec.num_disk_start_cdir == 0xFFFF) {
G.ecrec.num_disk_start_cdir = ecrec64_disk_cdstart;
if (ecrec64_disk_cdstart != 0xFFFF) G.ecrec.is_zip64_archive = TRUE;
}
if (G.ecrec.num_entries_centrl_dir_ths_disk == 0xFFFF) {
G.ecrec.num_entries_centrl_dir_ths_disk = ecrec64_this_entries;
if (ecrec64_this_entries != 0xFFFF) G.ecrec.is_zip64_archive = TRUE;
}
if (G.ecrec.total_entries_central_dir == 0xFFFF) {
G.ecrec.total_entries_central_dir = ecrec64_tot_entries;
if (ecrec64_tot_entries != 0xFFFF) G.ecrec.is_zip64_archive = TRUE;
}
if (G.ecrec.size_central_directory == 0xFFFFFFFFL) {
G.ecrec.size_central_directory = ecrec64_cdirsize;
if (ecrec64_cdirsize != 0xFFFFFFFF) G.ecrec.is_zip64_archive = TRUE;
}
if (G.ecrec.offset_start_central_directory == 0xFFFFFFFFL) {
G.ecrec.offset_start_central_directory = ecrec64_offs_cdstart;
if (ecrec64_offs_cdstart != 0xFFFFFFFF) G.ecrec.is_zip64_archive = TRUE;
}
return PK_COOL;
} /* end function find_ecrec64() */
/*************************/
/* Function find_ecrec() */
/*************************/
static int find_ecrec(__G__ searchlen) /* return PK-class error */
__GDEF
zoff_t searchlen;
{
int found = FALSE;
int error_in_archive;
int result;
ec_byte_rec byterec;
/*---------------------------------------------------------------------------
Treat case of short zipfile separately.
---------------------------------------------------------------------------*/
if (G.ziplen <= INBUFSIZ) {
#ifdef USE_STRM_INPUT
zfseeko(G.zipfd, 0L, SEEK_SET);
#else /* !USE_STRM_INPUT */
zlseek(G.zipfd, 0L, SEEK_SET);
#endif /* ?USE_STRM_INPUT */
if ((G.incnt = read(G.zipfd,(char *)G.inbuf,(unsigned int)G.ziplen))
== (int)G.ziplen)
/* 'P' must be at least (ECREC_SIZE+4) bytes from end of zipfile */
for (G.inptr = G.inbuf+(int)G.ziplen-(ECREC_SIZE+4);
G.inptr >= G.inbuf;
--G.inptr) {
if ( (*G.inptr == (uch)0x50) && /* ASCII 'P' */
!memcmp((char *)G.inptr, end_central_sig, 4)) {
G.incnt -= (int)(G.inptr - G.inbuf);
found = TRUE;
break;
}
}
/*---------------------------------------------------------------------------
Zipfile is longer than INBUFSIZ:
MB - this next block of code moved to rec_find so that same code can be
used to look for zip64 ec record. No need to include code above since
a zip64 ec record will only be looked for if it is a BIG file.
---------------------------------------------------------------------------*/
} else {
found =
(rec_find(__G__ searchlen, end_central_sig, ECREC_SIZE) == 0
? TRUE : FALSE);
} /* end if (ziplen > INBUFSIZ) */
/*---------------------------------------------------------------------------
Searched through whole region where signature should be without finding
it. Print informational message and die a horrible death.
---------------------------------------------------------------------------*/
if (!found) {
if (uO.qflag || uO.zipinfo_mode)
Info(slide, 0x401, ((char *)slide, "[%s]\n", G.zipfn));
Info(slide, 0x401, ((char *)slide,
LoadFarString(CentDirEndSigNotFound)));
return PK_ERR; /* failed */
}
/*---------------------------------------------------------------------------
Found the signature, so get the end-central data before returning. Do
any necessary machine-type conversions (byte ordering, structure padding
compensation) by reading data into character array and copying to struct.
---------------------------------------------------------------------------*/
G.real_ecrec_offset = G.cur_zipfile_bufstart + (G.inptr-G.inbuf);
#ifdef TEST
printf("\n found end-of-central-dir signature at offset %s (%sh)\n",
FmZofft(G.real_ecrec_offset, NULL, NULL),
FmZofft(G.real_ecrec_offset, FZOFFT_HEX_DOT_WID, "X"));
printf(" from beginning of file; offset %d (%.4Xh) within block\n",
G.inptr-G.inbuf, G.inptr-G.inbuf);
#endif
if (readbuf(__G__ (char *)byterec, ECREC_SIZE+4) == 0)
return PK_EOF;
G.ecrec.number_this_disk =
makeword(&byterec[NUMBER_THIS_DISK]);
G.ecrec.num_disk_start_cdir =
makeword(&byterec[NUM_DISK_WITH_START_CEN_DIR]);
G.ecrec.num_entries_centrl_dir_ths_disk =
makeword(&byterec[NUM_ENTRIES_CEN_DIR_THS_DISK]);
G.ecrec.total_entries_central_dir =
makeword(&byterec[TOTAL_ENTRIES_CENTRAL_DIR]);
G.ecrec.size_central_directory =
makelong(&byterec[SIZE_CENTRAL_DIRECTORY]);
G.ecrec.offset_start_central_directory =
makelong(&byterec[OFFSET_START_CENTRAL_DIRECTORY]);
G.ecrec.zipfile_comment_length =
makeword(&byterec[ZIPFILE_COMMENT_LENGTH]);
/* Now, we have to read the archive comment, BEFORE the file pointer
is moved away backwards to seek for a Zip64 ECLOC64 structure.
*/
if ( (error_in_archive = process_zip_cmmnt(__G)) > PK_WARN )
return error_in_archive;
/* Next: Check for existence of Zip64 end-of-cent-dir locator
ECLOC64. This structure must reside on the same volume as the
classic ECREC, at exactly (ECLOC64_SIZE+4) bytes in front
of the ECREC.
The ECLOC64 structure directs to the longer ECREC64 structure
A ECREC64 will ALWAYS exist for a proper Zip64 archive, as
the "Version Needed To Extract" field is required to be set
to 4.5 or higher whenever any Zip64 features are used anywhere
in the archive, so just check for that to see if this is a
Zip64 archive.
*/
result = find_ecrec64(__G__ searchlen+76);
/* 76 bytes for zip64ec & zip64 locator */
if (result != PK_COOL) {
if (error_in_archive < result)
error_in_archive = result;
return error_in_archive;
}
G.expect_ecrec_offset = G.ecrec.offset_start_central_directory +
G.ecrec.size_central_directory;
#ifndef NO_ZIPINFO
if (uO.zipinfo_mode) {
/* In ZipInfo mode, additional info about the data found in the
end-of-central-directory areas is printed out.
*/
zi_end_central(__G);
}
#endif
return error_in_archive;
} /* end function find_ecrec() */
/********************************/
/* Function process_zip_cmmnt() */
/********************************/
static int process_zip_cmmnt(__G) /* return PK-type error code */
__GDEF
{
int error = PK_COOL;
/*---------------------------------------------------------------------------
Get the zipfile comment (up to 64KB long), if any, and print it out.
---------------------------------------------------------------------------*/
#ifdef WINDLL
/* for comment button: */
if ((!G.fValidate) && (G.lpUserFunctions != NULL))
G.lpUserFunctions->cchComment = G.ecrec.zipfile_comment_length;
#endif /* WINDLL */
#ifndef NO_ZIPINFO
/* ZipInfo, verbose format */
if (uO.zipinfo_mode && uO.lflag > 9) {
/*-------------------------------------------------------------------
Get the zipfile comment, if any, and print it out.
(Comment may be up to 64KB long. May the fleas of a thousand
camels infest the arm-pits of anyone who actually takes advantage
of this fact.)
-------------------------------------------------------------------*/
if (!G.ecrec.zipfile_comment_length)
Info(slide, 0, ((char *)slide, LoadFarString(NoZipfileComment)));
else {
Info(slide, 0, ((char *)slide, LoadFarString(ZipfileCommentDesc),
G.ecrec.zipfile_comment_length));
Info(slide, 0, ((char *)slide, LoadFarString(ZipfileCommBegin)));
if (do_string(__G__ G.ecrec.zipfile_comment_length, DISPLAY))
error = PK_WARN;
Info(slide, 0, ((char *)slide, LoadFarString(ZipfileCommEnd)));
if (error)
Info(slide, 0, ((char *)slide,
LoadFarString(ZipfileCommTrunc2)));
} /* endif (comment exists) */
/* ZipInfo, non-verbose mode: print zipfile comment only if requested */
} else if (G.ecrec.zipfile_comment_length &&
(uO.zflag > 0) && uO.zipinfo_mode) {
if (do_string(__G__ G.ecrec.zipfile_comment_length, DISPLAY)) {
Info(slide, 0x401, ((char *)slide,
LoadFarString(ZipfileCommTrunc1)));
error = PK_WARN;
}
} else
#endif /* !NO_ZIPINFO */
if ( G.ecrec.zipfile_comment_length &&
(uO.zflag > 0
#ifndef WINDLL
|| (uO.zflag == 0
# ifndef NO_ZIPINFO
&& !uO.zipinfo_mode
# endif
# ifdef TIMESTAMP
&& !uO.T_flag
# endif
&& !uO.qflag)
#endif /* !WINDLL */
) )
{
if (do_string(__G__ G.ecrec.zipfile_comment_length,
#if (defined(SFX) && defined(CHEAP_SFX_AUTORUN))
# ifndef NO_ZIPINFO
(oU.zipinfo_mode ? DISPLAY : CHECK_AUTORUN)
# else
CHECK_AUTORUN
# endif
#else
DISPLAY
#endif
))
{
Info(slide, 0x401, ((char *)slide,
LoadFarString(ZipfileCommTrunc1)));
error = PK_WARN;
}
}
#if (defined(SFX) && defined(CHEAP_SFX_AUTORUN))
else if (G.ecrec.zipfile_comment_length) {
if (do_string(__G__ G.ecrec.zipfile_comment_length, CHECK_AUTORUN_Q))
{
Info(slide, 0x401, ((char *)slide,
LoadFarString(ZipfileCommTrunc1)));
error = PK_WARN;
}
}
#endif
return error;
} /* end function process_zip_cmmnt() */
/************************************/
/* Function process_cdir_file_hdr() */
/************************************/
int process_cdir_file_hdr(__G) /* return PK-type error code */
__GDEF
{
int error;
/*---------------------------------------------------------------------------
Get central directory info, save host and method numbers, and set flag
for lowercase conversion of filename, depending on the OS from which the
file is coming.
---------------------------------------------------------------------------*/
if ((error = get_cdir_ent(__G)) != 0)
return error;
G.pInfo->hostver = G.crec.version_made_by[0];
G.pInfo->hostnum = MIN(G.crec.version_made_by[1], NUM_HOSTS);
/* extnum = MIN(crec.version_needed_to_extract[1], NUM_HOSTS); */
G.pInfo->lcflag = 0;
if (uO.L_flag == 1) /* name conversion for monocase systems */
switch (G.pInfo->hostnum) {
case FS_FAT_: /* PKZIP and zip -k store in uppercase */
case CPM_: /* like MS-DOS, right? */
case VM_CMS_: /* all caps? */
case MVS_: /* all caps? */
case TANDEM_:
case TOPS20_:
case VMS_: /* our Zip uses lowercase, but ASi's doesn't */
/* case Z_SYSTEM_: ? */
/* case QDOS_: ? */
G.pInfo->lcflag = 1; /* convert filename to lowercase */
break;
default: /* AMIGA_, FS_HPFS_, FS_NTFS_, MAC_, UNIX_, ATARI_, */
break; /* FS_VFAT_, ATHEOS_, BEOS_ (Z_SYSTEM_), THEOS_: */
/* no conversion */
}
else if (uO.L_flag > 1) /* let -LL force lower case for all names */
G.pInfo->lcflag = 1;
/* do Amigas (AMIGA_) also have volume labels? */
if (IS_VOLID(G.crec.external_file_attributes) &&
(G.pInfo->hostnum == FS_FAT_ || G.pInfo->hostnum == FS_HPFS_ ||
G.pInfo->hostnum == FS_NTFS_ || G.pInfo->hostnum == ATARI_))
{
G.pInfo->vollabel = TRUE;
G.pInfo->lcflag = 0; /* preserve case of volume labels */
} else
G.pInfo->vollabel = FALSE;
/* this flag is needed to detect archives made by "PKZIP for Unix" when
deciding which kind of codepage conversion has to be applied to
strings (see do_string() function in fileio.c) */
G.pInfo->HasUxAtt = (G.crec.external_file_attributes & 0xffff0000L) != 0L;
#ifdef UNICODE_SUPPORT
/* remember the state of GPB11 (General Purpuse Bit 11) which indicates
that the standard path and comment are UTF-8. */
G.pInfo->GPFIsUTF8
= (G.crec.general_purpose_bit_flag & (1 << 11)) == (1 << 11);
#endif
return PK_COOL;
} /* end function process_cdir_file_hdr() */
/***************************/
/* Function get_cdir_ent() */
/***************************/
static int get_cdir_ent(__G) /* return PK-type error code */
__GDEF
{
cdir_byte_hdr byterec;
/*---------------------------------------------------------------------------
Read the next central directory entry and do any necessary machine-type
conversions (byte ordering, structure padding compensation--do so by
copying the data from the array into which it was read (byterec) to the
usable struct (crec)).
---------------------------------------------------------------------------*/
if (readbuf(__G__ (char *)byterec, CREC_SIZE) == 0)
return PK_EOF;
G.crec.version_made_by[0] = byterec[C_VERSION_MADE_BY_0];
G.crec.version_made_by[1] = byterec[C_VERSION_MADE_BY_1];
G.crec.version_needed_to_extract[0] =
byterec[C_VERSION_NEEDED_TO_EXTRACT_0];
G.crec.version_needed_to_extract[1] =
byterec[C_VERSION_NEEDED_TO_EXTRACT_1];
G.crec.general_purpose_bit_flag =
makeword(&byterec[C_GENERAL_PURPOSE_BIT_FLAG]);
G.crec.compression_method =
makeword(&byterec[C_COMPRESSION_METHOD]);
G.crec.last_mod_dos_datetime =
makelong(&byterec[C_LAST_MOD_DOS_DATETIME]);
G.crec.crc32 =
makelong(&byterec[C_CRC32]);
G.crec.csize =
makelong(&byterec[C_COMPRESSED_SIZE]);
G.crec.ucsize =
makelong(&byterec[C_UNCOMPRESSED_SIZE]);
G.crec.filename_length =
makeword(&byterec[C_FILENAME_LENGTH]);
G.crec.extra_field_length =
makeword(&byterec[C_EXTRA_FIELD_LENGTH]);
G.crec.file_comment_length =
makeword(&byterec[C_FILE_COMMENT_LENGTH]);
G.crec.disk_number_start =
makeword(&byterec[C_DISK_NUMBER_START]);
G.crec.internal_file_attributes =
makeword(&byterec[C_INTERNAL_FILE_ATTRIBUTES]);
G.crec.external_file_attributes =
makelong(&byterec[C_EXTERNAL_FILE_ATTRIBUTES]); /* LONG, not word! */
G.crec.relative_offset_local_header =
makelong(&byterec[C_RELATIVE_OFFSET_LOCAL_HEADER]);
return PK_COOL;
} /* end function get_cdir_ent() */
/*************************************/
/* Function process_local_file_hdr() */
/*************************************/
int process_local_file_hdr(__G) /* return PK-type error code */
__GDEF
{
local_byte_hdr byterec;
/*---------------------------------------------------------------------------
Read the next local file header and do any necessary machine-type con-
versions (byte ordering, structure padding compensation--do so by copy-
ing the data from the array into which it was read (byterec) to the
usable struct (lrec)).
---------------------------------------------------------------------------*/
if (readbuf(__G__ (char *)byterec, LREC_SIZE) == 0)
return PK_EOF;
G.lrec.version_needed_to_extract[0] =
byterec[L_VERSION_NEEDED_TO_EXTRACT_0];
G.lrec.version_needed_to_extract[1] =
byterec[L_VERSION_NEEDED_TO_EXTRACT_1];
G.lrec.general_purpose_bit_flag =
makeword(&byterec[L_GENERAL_PURPOSE_BIT_FLAG]);
G.lrec.compression_method = makeword(&byterec[L_COMPRESSION_METHOD]);
G.lrec.last_mod_dos_datetime = makelong(&byterec[L_LAST_MOD_DOS_DATETIME]);
G.lrec.crc32 = makelong(&byterec[L_CRC32]);
G.lrec.csize = makelong(&byterec[L_COMPRESSED_SIZE]);
G.lrec.ucsize = makelong(&byterec[L_UNCOMPRESSED_SIZE]);
G.lrec.filename_length = makeword(&byterec[L_FILENAME_LENGTH]);
G.lrec.extra_field_length = makeword(&byterec[L_EXTRA_FIELD_LENGTH]);
if ((G.lrec.general_purpose_bit_flag & 8) != 0) {
/* can't trust local header, use central directory: */
G.lrec.crc32 = G.pInfo->crc;
G.lrec.csize = G.pInfo->compr_size;
G.lrec.ucsize = G.pInfo->uncompr_size;
}
G.csize = G.lrec.csize;
return PK_COOL;
} /* end function process_local_file_hdr() */
/*******************************/
/* Function getZip64Data() */
/*******************************/
int getZip64Data(__G__ ef_buf, ef_len)
__GDEF
ZCONST uch *ef_buf; /* buffer containing extra field */
unsigned ef_len; /* total length of extra field */
{
unsigned eb_id;
unsigned eb_len;
/*---------------------------------------------------------------------------
This function scans the extra field for zip64 information, ie 8-byte
versions of compressed file size, uncompressed file size, relative offset
and a 4-byte version of disk start number.
Sets both local header and central header fields. Not terribly clever,
but it means that this procedure is only called in one place.
---------------------------------------------------------------------------*/
G.zip64 = FALSE;
if (ef_len == 0 || ef_buf == NULL)
return PK_COOL;
Trace((stderr,"\ngetZip64Data: scanning extra field of length %u\n",
ef_len));
while (ef_len >= EB_HEADSIZE) {
eb_id = makeword(EB_ID + ef_buf);
eb_len = makeword(EB_LEN + ef_buf);
if (eb_len > (ef_len - EB_HEADSIZE)) {
/* discovered some extra field inconsistency! */
Trace((stderr,
"getZip64Data: block length %u > rest ef_size %u\n", eb_len,
ef_len - EB_HEADSIZE));
break;
}
if (eb_id == EF_PKSZ64) {
int offset = EB_HEADSIZE;
if (G.crec.ucsize == 0xffffffff || G.lrec.ucsize == 0xffffffff){
G.lrec.ucsize = G.crec.ucsize = makeint64(offset + ef_buf);
offset += sizeof(G.crec.ucsize);
}
if (G.crec.csize == 0xffffffff || G.lrec.csize == 0xffffffff){
G.csize = G.lrec.csize = G.crec.csize = makeint64(offset + ef_buf);
offset += sizeof(G.crec.csize);
}
if (G.crec.relative_offset_local_header == 0xffffffff){
G.crec.relative_offset_local_header = makeint64(offset + ef_buf);
offset += sizeof(G.crec.relative_offset_local_header);
}
if (G.crec.disk_number_start == 0xffff){
G.crec.disk_number_start = (zuvl_t)makelong(offset + ef_buf);
offset += sizeof(G.crec.disk_number_start);
}
G.zip64 = TRUE;
}
/* Skip this extra field block */
ef_buf += (eb_len + EB_HEADSIZE);
ef_len -= (eb_len + EB_HEADSIZE);
}
return PK_COOL;
} /* end function getZip64Data() */
#ifdef UNICODE_SUPPORT
/*******************************/
/* Function getUnicodeData() */
/*******************************/
int getUnicodeData(__G__ ef_buf, ef_len)
__GDEF
ZCONST uch *ef_buf; /* buffer containing extra field */
unsigned ef_len; /* total length of extra field */
{
unsigned eb_id;
unsigned eb_len;
/*---------------------------------------------------------------------------
This function scans the extra field for Unicode information, ie UTF-8
path extra fields.
On return, G.unipath_filename =
NULL, if no Unicode path extra field or error
"", if the standard path is UTF-8 (free when done)
null-terminated UTF-8 path (free when done)
Return PK_COOL if no error.
---------------------------------------------------------------------------*/
G.unipath_filename = NULL;
if (ef_len == 0 || ef_buf == NULL)
return PK_COOL;
Trace((stderr,"\ngetUnicodeData: scanning extra field of length %u\n",
ef_len));
while (ef_len >= EB_HEADSIZE) {
eb_id = makeword(EB_ID + ef_buf);
eb_len = makeword(EB_LEN + ef_buf);
if (eb_len > (ef_len - EB_HEADSIZE)) {
/* discovered some extra field inconsistency! */
Trace((stderr,
"getUnicodeData: block length %u > rest ef_size %u\n", eb_len,
ef_len - EB_HEADSIZE));
break;
}
if (eb_id == EF_UNIPATH) {
int offset = EB_HEADSIZE;
ush ULen = eb_len - 5;
ulg chksum = CRCVAL_INITIAL;
/* version */
G.unipath_version = (uch) *(offset + ef_buf);
offset += 1;
if (G.unipath_version > 1) {
/* can do only version 1 */
Info(slide, 0x401, ((char *)slide,
LoadFarString(UnicodeVersionError)));
return PK_ERR;
}
/* filename CRC */
G.unipath_checksum = makelong(offset + ef_buf);
offset += 4;
/*
* Compute 32-bit crc
*/
chksum = crc32(chksum, (uch *)(G.filename_full),
strlen(G.filename_full));
/* If the checksums's don't match then likely filename has been
* modified and the Unicode Path is no longer valid.
*/
if (chksum != G.unipath_checksum) {
Info(slide, 0x401, ((char *)slide,
LoadFarString(UnicodeMismatchError)));
if (G.unicode_mismatch == 1) {
/* warn and continue */
} else if (G.unicode_mismatch == 2) {
/* ignore and continue */
} else if (G.unicode_mismatch == 0) {
}
return PK_ERR;
}
/* UTF-8 Path */
if ((G.unipath_filename = malloc(ULen + 1)) == NULL) {
return PK_ERR;
}
if (ULen == 0) {
/* standard path is UTF-8 so use that */
G.unipath_filename[0] = '\0';
} else {
/* UTF-8 path */
strncpy(G.unipath_filename,
(ZCONST char *)(offset + ef_buf), ULen);
G.unipath_filename[ULen] = '\0';
}
}
/* Skip this extra field block */
ef_buf += (eb_len + EB_HEADSIZE);
ef_len -= (eb_len + EB_HEADSIZE);
}
return PK_COOL;
} /* end function getUnicodeData() */
#ifdef UNICODE_WCHAR
/*---------------------------------------------
* Unicode conversion functions
*
* Based on functions provided by Paul Kienitz
*
*---------------------------------------------
*/
/*
NOTES APPLICABLE TO ALL STRING FUNCTIONS:
All of the x_to_y functions take parameters for an output buffer and
its available length, and return an int. The value returned is the
length of the string that the input produces, which may be larger than
the provided buffer length. If the returned value is less than the
buffer length, then the contents of the buffer will be null-terminated;
otherwise, it will not be terminated and may be invalid, possibly
stopping in the middle of a multibyte sequence.
In all cases you may pass NULL as the buffer and/or 0 as the length, if
you just want to learn how much space the string is going to require.
The functions will return -1 if the input is invalid UTF-8 or cannot be
encoded as UTF-8.
*/
static int utf8_char_bytes OF((ZCONST char *utf8));
static ulg ucs4_char_from_utf8 OF((ZCONST char **utf8));
static int utf8_to_ucs4_string OF((ZCONST char *utf8, ulg *ucs4buf,
int buflen));
/* utility functions for managing UTF-8 and UCS-4 strings */
/* utf8_char_bytes
*
* Returns the number of bytes used by the first character in a UTF-8
* string, or -1 if the UTF-8 is invalid or null.
*/
static int utf8_char_bytes(utf8)
ZCONST char *utf8;
{
int t, r;
unsigned lead;
if (!utf8)
return -1; /* no input */
lead = (unsigned char) *utf8;
if (lead < 0x80)
r = 1; /* an ascii-7 character */
else if (lead < 0xC0)
return -1; /* error: trailing byte without lead byte */
else if (lead < 0xE0)
r = 2; /* an 11 bit character */
else if (lead < 0xF0)
r = 3; /* a 16 bit character */
else if (lead < 0xF8)
r = 4; /* a 21 bit character (the most currently used) */
else if (lead < 0xFC)
r = 5; /* a 26 bit character (shouldn't happen) */
else if (lead < 0xFE)
r = 6; /* a 31 bit character (shouldn't happen) */
else
return -1; /* error: invalid lead byte */
for (t = 1; t < r; t++)
if ((unsigned char) utf8[t] < 0x80 || (unsigned char) utf8[t] >= 0xC0)
return -1; /* error: not enough valid trailing bytes */
return r;
}
/* ucs4_char_from_utf8
*
* Given a reference to a pointer into a UTF-8 string, returns the next
* UCS-4 character and advances the pointer to the next character sequence.
* Returns ~0 (= -1 in twos-complement notation) and does not advance the
* pointer when input is ill-formed.
*/
static ulg ucs4_char_from_utf8(utf8)
ZCONST char **utf8;
{
ulg ret;
int t, bytes;
if (!utf8)
return ~0L; /* no input */
bytes = utf8_char_bytes(*utf8);
if (bytes <= 0)
return ~0L; /* invalid input */
if (bytes == 1)
ret = **utf8; /* ascii-7 */
else
ret = **utf8 & (0x7F >> bytes); /* lead byte of a multibyte sequence */
(*utf8)++;
for (t = 1; t < bytes; t++) /* consume trailing bytes */
ret = (ret << 6) | (*((*utf8)++) & 0x3F);
return (zwchar) ret;
}
#if 0 /* currently unused */
/* utf8_from_ucs4_char - Convert UCS char to UTF-8
*
* Returns the number of bytes put into utf8buf to represent ch, from 1 to 6,
* or -1 if ch is too large to represent. utf8buf must have room for 6 bytes.
*/
static int utf8_from_ucs4_char(utf8buf, ch)
char *utf8buf;
ulg ch;
{
int trailing = 0;
int leadmask = 0x80;
int leadbits = 0x3F;
int tch = ch;
int ret;
if (ch > 0x7FFFFFFFL)
return -1; /* UTF-8 can represent 31 bits */
if (ch < 0x7F)
{
*utf8buf++ = (char) ch; /* ascii-7 */
return 1;
}
do {
trailing++;
leadmask = (leadmask >> 1) | 0x80;
leadbits >>= 1;
tch >>= 6;
} while (tch & ~leadbits);
ret = trailing + 1;
/* produce lead byte */
*utf8buf++ = (char) (leadmask | (ch >> (6 * trailing)));
while (--trailing >= 0)
/* produce trailing bytes */
*utf8buf++ = (char) (0x80 | ((ch >> (6 * trailing)) & 0x3F));
return ret;
}
#endif /* unused */
/*===================================================================*/
/* utf8_to_ucs4_string - convert UTF-8 string to UCS string
*
* Return UCS count. Now returns int so can return -1.
*/
static int utf8_to_ucs4_string(utf8, ucs4buf, buflen)
ZCONST char *utf8;
ulg *ucs4buf;
int buflen;
{
int count = 0;
for (;;)
{
ulg ch = ucs4_char_from_utf8(&utf8);
if (ch == ~0L)
return -1;
else
{
if (ucs4buf && count < buflen)
ucs4buf[count] = ch;
if (ch == 0)
return count;
count++;
}
}
}
#if 0 /* currently unused */
/* ucs4_string_to_utf8
*
*
*/
static int ucs4_string_to_utf8(ucs4, utf8buf, buflen)
ZCONST ulg *ucs4;
char *utf8buf;
int buflen;
{
char mb[6];
int count = 0;
if (!ucs4)
return -1;
for (;;)
{
int mbl = utf8_from_ucs4_char(mb, *ucs4++);
int c;
if (mbl <= 0)
return -1;
/* We could optimize this a bit by passing utf8buf + count */
/* directly to utf8_from_ucs4_char when buflen >= count + 6... */
c = buflen - count;
if (mbl < c)
c = mbl;
if (utf8buf && count < buflen)
strncpy(utf8buf + count, mb, c);
if (mbl == 1 && !mb[0])
return count; /* terminating nul */
count += mbl;
}
}
/* utf8_chars
*
* Wrapper: counts the actual unicode characters in a UTF-8 string.
*/
static int utf8_chars(utf8)
ZCONST char *utf8;
{
return utf8_to_ucs4_string(utf8, NULL, 0);
}
#endif /* unused */
/* --------------------------------------------------- */
/* Unicode Support
*
* These functions common for all Unicode ports.
*
* These functions should allocate and return strings that can be
* freed with free().
*
* 8/27/05 EG
*
* Use zwchar for wide char which is unsigned long
* in zip.h and 32 bits. This avoids problems with
* different sizes of wchar_t.
*/
#if 0 /* currently unused */
/* is_ascii_string
* Checks if a string is all ascii
*/
int is_ascii_string(mbstring)
ZCONST char *mbstring;
{
char *p;
uch c;
for (p = mbstring; c = (uch)*p; p++) {
if (c > 0x7F) {
return 0;
}
}
return 1;
}
/* local to UTF-8 */
char *local_to_utf8_string(local_string)
ZCONST char *local_string;
{
return wide_to_utf8_string(local_to_wide_string(local_string));
}
# endif /* unused */
/* wide_to_escape_string
provides a string that represents a wide char not in local char set
An initial try at an algorithm. Suggestions welcome.
According to the standard, Unicode character points are restricted to
the number range from 0 to 0x10FFFF, respective 21 bits.
For a hexadecimal notation, 2 octets are sufficient for the mostly
used characters from the "Basic Multilingual Plane", all other
Unicode characters can be represented by 3 octets (= 6 hex digits).
The Unicode standard suggests to write Unicode character points
as 4 resp. 6 hex digits, preprended by "U+".
(e.g.: U+10FFFF for the highest character point, or U+0030 for the ASCII
digit "0")
However, for the purpose of escaping non-ASCII chars in an ASCII character
stream, the "U" is not a very good escape initializer. Therefore, we
use the following convention within our Info-ZIP code:
If not an ASCII char probably need 2 bytes at least. So if
a 2-byte wide encode it as 4 hex digits with a leading #U. If
needs 3 bytes then prefix the string with #L. So
#U1234
is a 2-byte wide character with bytes 0x12 and 0x34 while
#L123456
is a 3-byte wide character with bytes 0x12, 0x34, 0x56.
On Windows, wide that need two wide characters need to be converted
to a single number.
*/
/* set this to the max bytes an escape can be */
#define MAX_ESCAPE_BYTES 8
char *wide_to_escape_string(wide_char)
zwchar wide_char;
{
int i;
zwchar w = wide_char;
uch b[sizeof(zwchar)];
char d[3];
char e[11];
int len;
char *r;
/* fill byte array with zeros */
memzero(b, sizeof(zwchar));
/* get bytes in right to left order */
for (len = 0; w; len++) {
b[len] = (char)(w % 0x100);
w /= 0x100;
}
strcpy(e, "#");
/* either 2 bytes or 3 bytes */
if (len <= 2) {
len = 2;
strcat(e, "U");
} else {
strcat(e, "L");
}
for (i = len - 1; i >= 0; i--) {
sprintf(d, "%02x", b[i]);
strcat(e, d);
}
if ((r = malloc(strlen(e) + 1)) == NULL) {
return NULL;
}
strcpy(r, e);
return r;
}
#if 0 /* currently unused */
/* returns the wide character represented by the escape string */
zwchar escape_string_to_wide(escape_string)
ZCONST char *escape_string;
{
int i;
zwchar w;
char c;
int len;
ZCONST char *e = escape_string;
if (e == NULL) {
return 0;
}
if (e[0] != '#') {
/* no leading # */
return 0;
}
len = strlen(e);
/* either #U1234 or #L123456 format */
if (len != 6 && len != 8) {
return 0;
}
w = 0;
if (e[1] == 'L') {
if (len != 8) {
return 0;
}
/* 3 bytes */
for (i = 2; i < 8; i++) {
c = e[i];
if (c < '0' || c > '9') {
return 0;
}
w = w * 0x10 + (zwchar)(c - '0');
}
} else if (e[1] == 'U') {
/* 2 bytes */
for (i = 2; i < 6; i++) {
c = e[i];
if (c < '0' || c > '9') {
return 0;
}
w = w * 0x10 + (zwchar)(c - '0');
}
}
return w;
}
#endif /* unused */
#ifndef WIN32 /* WIN32 supplies a special variant of this function */
/* convert wide character string to multi-byte character string */
char *wide_to_local_string(wide_string, escape_all)
ZCONST zwchar *wide_string;
int escape_all;
{
int i;
wchar_t wc;
int b;
int state_dependent;
int wsize = 0;
int max_bytes = MB_CUR_MAX;
char buf[9];
char *buffer = NULL;
char *local_string = NULL;
for (wsize = 0; wide_string[wsize]; wsize++) ;
if (max_bytes < MAX_ESCAPE_BYTES)
max_bytes = MAX_ESCAPE_BYTES;
if ((buffer = (char *)malloc(wsize * max_bytes + 1)) == NULL) {
return NULL;
}
/* convert it */
buffer[0] = '\0';
/* set initial state if state-dependent encoding */
wc = (wchar_t)'a';
b = wctomb(NULL, wc);
if (b == 0)
state_dependent = 0;
else
state_dependent = 1;
for (i = 0; i < wsize; i++) {
if (sizeof(wchar_t) < 4 && wide_string[i] > 0xFFFF) {
/* wchar_t probably 2 bytes */
/* could do surrogates if state_dependent and wctomb can do */
wc = zwchar_to_wchar_t_default_char;
} else {
wc = (wchar_t)wide_string[i];
}
b = wctomb(buf, wc);
if (escape_all) {
if (b == 1 && (uch)buf[0] <= 0x7f) {
/* ASCII */
strncat(buffer, buf, b);
} else {
/* use escape for wide character */
char *escape_string = wide_to_escape_string(wide_string[i]);
strcat(buffer, escape_string);
free(escape_string);
}
} else if (b > 0) {
/* multi-byte char */
strncat(buffer, buf, b);
} else {
/* no MB for this wide */
/* use escape for wide character */
char *escape_string = wide_to_escape_string(wide_string[i]);
strcat(buffer, escape_string);
free(escape_string);
}
}
if ((local_string = (char *)malloc(strlen(buffer) + 1)) != NULL) {
strcpy(local_string, buffer);
}
free(buffer);
return local_string;
}
#endif /* !WIN32 */
#if 0 /* currently unused */
/* convert local string to display character set string */
char *local_to_display_string(local_string)
ZCONST char *local_string;
{
char *display_string;
/* For Windows, OEM string should never be bigger than ANSI string, says
CharToOem description.
For all other ports, just make a copy of local_string.
*/
if ((display_string = (char *)malloc(strlen(local_string) + 1)) == NULL) {
return NULL;
}
strcpy(display_string, local_string);
#ifdef EBCDIC
{
char *ebc;
if ((ebc = malloc(strlen(display_string) + 1)) == NULL) {
return NULL;
}
strtoebc(ebc, display_string);
free(display_string);
display_string = ebc;
}
#endif
return display_string;
}
#endif /* unused */
/* UTF-8 to local */
char *utf8_to_local_string(utf8_string, escape_all)
ZCONST char *utf8_string;
int escape_all;
{
zwchar *wide = utf8_to_wide_string(utf8_string);
char *loc = wide_to_local_string(wide, escape_all);
free(wide);
return loc;
}
#if 0 /* currently unused */
/* convert multi-byte character string to wide character string */
zwchar *local_to_wide_string(local_string)
ZCONST char *local_string;
{
int wsize;
wchar_t *wc_string;
zwchar *wide_string;
/* for now try to convert as string - fails if a bad char in string */
wsize = mbstowcs(NULL, local_string, strlen(local_string) + 1);
if (wsize == (size_t)-1) {
/* could not convert */
return NULL;
}
/* convert it */
if ((wc_string = (wchar_t *)malloc((wsize + 1) * sizeof(wchar_t))) == NULL) {
return NULL;
}
wsize = mbstowcs(wc_string, local_string, strlen(local_string) + 1);
wc_string[wsize] = (wchar_t) 0;
/* in case wchar_t is not zwchar */
if ((wide_string = (zwchar *)malloc((wsize + 1) * sizeof(zwchar))) == NULL) {
return NULL;
}
for (wsize = 0; wide_string[wsize] = (zwchar)wc_string[wsize]; wsize++) ;
wide_string[wsize] = (zwchar) 0;
free(wc_string);
return wide_string;
}
/* convert wide string to UTF-8 */
char *wide_to_utf8_string(wide_string)
ZCONST zwchar *wide_string;
{
int mbcount;
char *utf8_string;
/* get size of utf8 string */
mbcount = ucs4_string_to_utf8(wide_string, NULL, 0);
if (mbcount == -1)
return NULL;
if ((utf8_string = (char *) malloc(mbcount + 1)) == NULL) {
return NULL;
}
mbcount = ucs4_string_to_utf8(wide_string, utf8_string, mbcount + 1);
if (mbcount == -1)
return NULL;
return utf8_string;
}
#endif /* unused */
/* convert UTF-8 string to wide string */
zwchar *utf8_to_wide_string(utf8_string)
ZCONST char *utf8_string;
{
int wcount;
zwchar *wide_string;
wcount = utf8_to_ucs4_string(utf8_string, NULL, 0);
if (wcount == -1)
return NULL;
if ((wide_string = (zwchar *) malloc((wcount + 1) * sizeof(zwchar)))
== NULL) {
return NULL;
}
wcount = utf8_to_ucs4_string(utf8_string, wide_string, wcount + 1);
return wide_string;
}
#endif /* UNICODE_WCHAR */
#endif /* UNICODE_SUPPORT */
#ifdef USE_EF_UT_TIME
#ifdef IZ_HAVE_UXUIDGID
static int read_ux3_value(dbuf, uidgid_sz, p_uidgid)
ZCONST uch *dbuf; /* buffer a uid or gid value */
unsigned uidgid_sz; /* size of uid/gid value */
ulg *p_uidgid; /* return storage: uid or gid value */
{
zusz_t uidgid64;
switch (uidgid_sz) {
case 2:
*p_uidgid = (ulg)makeword(dbuf);
break;
case 4:
*p_uidgid = (ulg)makelong(dbuf);
break;
case 8:
uidgid64 = makeint64(dbuf);
#ifndef LARGE_FILE_SUPPORT
if (uidgid64 == (zusz_t)0xffffffffL)
return FALSE;
#endif
*p_uidgid = (ulg)uidgid64;
if ((zusz_t)(*p_uidgid) != uidgid64)
return FALSE;
break;
}
return TRUE;
}
#endif /* IZ_HAVE_UXUIDGID */
/*******************************/
/* Function ef_scan_for_izux() */
/*******************************/
unsigned ef_scan_for_izux(ef_buf, ef_len, ef_is_c, dos_mdatetime,
z_utim, z_uidgid)
ZCONST uch *ef_buf; /* buffer containing extra field */
unsigned ef_len; /* total length of extra field */
int ef_is_c; /* flag indicating "is central extra field" */
ulg dos_mdatetime; /* last_mod_file_date_time in DOS format */
iztimes *z_utim; /* return storage: atime, mtime, ctime */
ulg *z_uidgid; /* return storage: uid and gid */
{
unsigned flags = 0;
unsigned eb_id;
unsigned eb_len;
int have_new_type_eb = 0;
long i_time; /* buffer for Unix style 32-bit integer time value */
#ifdef TIME_T_TYPE_DOUBLE
int ut_in_archive_sgn = 0;
#else
int ut_zip_unzip_compatible = FALSE;
#endif
/*---------------------------------------------------------------------------
This function scans the extra field for EF_TIME, EF_IZUNIX2, EF_IZUNIX, or
EF_PKUNIX blocks containing Unix-style time_t (GMT) values for the entry's
access, creation, and modification time.
If a valid block is found, the time stamps are copied to the iztimes
structure (provided the z_utim pointer is not NULL).
If a IZUNIX2 block is found or the IZUNIX block contains UID/GID fields,
and the z_uidgid array pointer is valid (!= NULL), the owner info is
transfered as well.
The presence of an EF_TIME or EF_IZUNIX2 block results in ignoring all
data from probably present obsolete EF_IZUNIX blocks.
If multiple blocks of the same type are found, only the information from
the last block is used.
The return value is a combination of the EF_TIME Flags field with an
additional flag bit indicating the presence of valid UID/GID info,
or 0 in case of failure.
---------------------------------------------------------------------------*/
if (ef_len == 0 || ef_buf == NULL || (z_utim == 0 && z_uidgid == NULL))
return 0;
TTrace((stderr,"\nef_scan_for_izux: scanning extra field of length %u\n",
ef_len));
while (ef_len >= EB_HEADSIZE) {
eb_id = makeword(EB_ID + ef_buf);
eb_len = makeword(EB_LEN + ef_buf);
if (eb_len > (ef_len - EB_HEADSIZE)) {
/* discovered some extra field inconsistency! */
TTrace((stderr,
"ef_scan_for_izux: block length %u > rest ef_size %u\n", eb_len,
ef_len - EB_HEADSIZE));
break;
}
switch (eb_id) {
case EF_TIME:
flags &= ~0x0ff; /* ignore previous IZUNIX or EF_TIME fields */
have_new_type_eb = 1;
if ( eb_len >= EB_UT_MINLEN && z_utim != NULL) {
unsigned eb_idx = EB_UT_TIME1;
TTrace((stderr,"ef_scan_for_izux: found TIME extra field\n"));
flags |= (ef_buf[EB_HEADSIZE+EB_UT_FLAGS] & 0x0ff);
if ((flags & EB_UT_FL_MTIME)) {
if ((eb_idx+4) <= eb_len) {
i_time = (long)makelong((EB_HEADSIZE+eb_idx) + ef_buf);
eb_idx += 4;
TTrace((stderr," UT e.f. modification time = %ld\n",
i_time));
#ifdef TIME_T_TYPE_DOUBLE
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
if (dos_mdatetime == DOSTIME_MINIMUM) {
ut_in_archive_sgn = -1;
z_utim->mtime =
(time_t)((long)i_time | (~(long)0x7fffffffL));
} else if (dos_mdatetime >= DOSTIME_2038_01_18) {
ut_in_archive_sgn = 1;
z_utim->mtime =
(time_t)((ulg)i_time & (ulg)0xffffffffL);
} else {
ut_in_archive_sgn = 0;
/* cannot determine sign of mtime;
without modtime: ignore complete UT field */
flags &= ~0x0ff; /* no time_t times available */
TTrace((stderr,
" UT modtime range error; ignore e.f.!\n"));
break; /* stop scanning this field */
}
} else {
/* cannot determine, safe assumption is FALSE */
ut_in_archive_sgn = 0;
z_utim->mtime = (time_t)i_time;
}
#else /* !TIME_T_TYPE_DOUBLE */
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
ut_zip_unzip_compatible =
((time_t)0x80000000L < (time_t)0L)
? (dos_mdatetime == DOSTIME_MINIMUM)
: (dos_mdatetime >= DOSTIME_2038_01_18);
if (!ut_zip_unzip_compatible) {
/* UnZip interprets mtime differently than Zip;
without modtime: ignore complete UT field */
flags &= ~0x0ff; /* no time_t times available */
TTrace((stderr,
" UT modtime range error; ignore e.f.!\n"));
break; /* stop scanning this field */
}
} else {
/* cannot determine, safe assumption is FALSE */
ut_zip_unzip_compatible = FALSE;
}
z_utim->mtime = (time_t)i_time;
#endif /* ?TIME_T_TYPE_DOUBLE */
} else {
flags &= ~EB_UT_FL_MTIME;
TTrace((stderr," UT e.f. truncated; no modtime\n"));
}
}
if (ef_is_c) {
break; /* central version of TIME field ends here */
}
if (flags & EB_UT_FL_ATIME) {
if ((eb_idx+4) <= eb_len) {
i_time = (long)makelong((EB_HEADSIZE+eb_idx) + ef_buf);
eb_idx += 4;
TTrace((stderr," UT e.f. access time = %ld\n",
i_time));
#ifdef TIME_T_TYPE_DOUBLE
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
if (ut_in_archive_sgn == -1)
z_utim->atime =
(time_t)((long)i_time | (~(long)0x7fffffffL));
} else if (ut_in_archive_sgn == 1) {
z_utim->atime =
(time_t)((ulg)i_time & (ulg)0xffffffffL);
} else {
/* sign of 32-bit time is unknown -> ignore it */
flags &= ~EB_UT_FL_ATIME;
TTrace((stderr,
" UT access time range error: skip time!\n"));
}
} else {
z_utim->atime = (time_t)i_time;
}
#else /* !TIME_T_TYPE_DOUBLE */
if (((ulg)(i_time) & (ulg)(0x80000000L)) &&
!ut_zip_unzip_compatible) {
flags &= ~EB_UT_FL_ATIME;
TTrace((stderr,
" UT access time range error: skip time!\n"));
} else {
z_utim->atime = (time_t)i_time;
}
#endif /* ?TIME_T_TYPE_DOUBLE */
} else {
flags &= ~EB_UT_FL_ATIME;
}
}
if (flags & EB_UT_FL_CTIME) {
if ((eb_idx+4) <= eb_len) {
i_time = (long)makelong((EB_HEADSIZE+eb_idx) + ef_buf);
TTrace((stderr," UT e.f. creation time = %ld\n",
i_time));
#ifdef TIME_T_TYPE_DOUBLE
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
if (ut_in_archive_sgn == -1)
z_utim->ctime =
(time_t)((long)i_time | (~(long)0x7fffffffL));
} else if (ut_in_archive_sgn == 1) {
z_utim->ctime =
(time_t)((ulg)i_time & (ulg)0xffffffffL);
} else {
/* sign of 32-bit time is unknown -> ignore it */
flags &= ~EB_UT_FL_CTIME;
TTrace((stderr,
" UT creation time range error: skip time!\n"));
}
} else {
z_utim->ctime = (time_t)i_time;
}
#else /* !TIME_T_TYPE_DOUBLE */
if (((ulg)(i_time) & (ulg)(0x80000000L)) &&
!ut_zip_unzip_compatible) {
flags &= ~EB_UT_FL_CTIME;
TTrace((stderr,
" UT creation time range error: skip time!\n"));
} else {
z_utim->ctime = (time_t)i_time;
}
#endif /* ?TIME_T_TYPE_DOUBLE */
} else {
flags &= ~EB_UT_FL_CTIME;
}
}
}
break;
case EF_IZUNIX2:
if (have_new_type_eb == 0) {
flags &= ~0x0ff; /* ignore any previous IZUNIX field */
have_new_type_eb = 1;
}
#ifdef IZ_HAVE_UXUIDGID
if (have_new_type_eb > 1)
break; /* IZUNIX3 overrides IZUNIX2 e.f. block ! */
if (eb_len == EB_UX2_MINLEN && z_uidgid != NULL) {
z_uidgid[0] = (ulg)makeword((EB_HEADSIZE+EB_UX2_UID) + ef_buf);
z_uidgid[1] = (ulg)makeword((EB_HEADSIZE+EB_UX2_GID) + ef_buf);
flags |= EB_UX2_VALID; /* signal success */
}
#endif
break;
case EF_IZUNIX3:
/* new 3rd generation Unix ef */
have_new_type_eb = 2;
/*
Version 1 byte version of this extra field, currently 1
UIDSize 1 byte Size of UID field
UID Variable UID for this entry
GIDSize 1 byte Size of GID field
GID Variable GID for this entry
*/
#ifdef IZ_HAVE_UXUIDGID
if (eb_len >= EB_UX3_MINLEN
&& z_uidgid != NULL
&& (*((EB_HEADSIZE + 0) + ef_buf) == 1)
/* only know about version 1 */
{
uch uid_size;
uch gid_size;
uid_size = *((EB_HEADSIZE + 1) + ef_buf);
gid_size = *((EB_HEADSIZE + uid_size + 2) + ef_buf);
flags &= ~0x0ff; /* ignore any previous UNIX field */
if ( read_ux3_value((EB_HEADSIZE + 2) + ef_buf,
uid_size, z_uidgid[0])
&&
read_ux3_value((EB_HEADSIZE + uid_size + 3) + ef_buf,
gid_size, z_uidgid[1]) )
{
flags |= EB_UX2_VALID; /* signal success */
}
}
#endif /* IZ_HAVE_UXUIDGID */
break;
case EF_IZUNIX:
case EF_PKUNIX: /* PKUNIX e.f. layout is identical to IZUNIX */
if (eb_len >= EB_UX_MINLEN) {
TTrace((stderr,"ef_scan_for_izux: found %s extra field\n",
(eb_id == EF_IZUNIX ? "IZUNIX" : "PKUNIX")));
if (have_new_type_eb > 0) {
break; /* Ignore IZUNIX extra field block ! */
}
if (z_utim != NULL) {
flags |= (EB_UT_FL_MTIME | EB_UT_FL_ATIME);
i_time = (long)makelong((EB_HEADSIZE+EB_UX_MTIME)+ef_buf);
TTrace((stderr," Unix EF modtime = %ld\n", i_time));
#ifdef TIME_T_TYPE_DOUBLE
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
if (dos_mdatetime == DOSTIME_MINIMUM) {
ut_in_archive_sgn = -1;
z_utim->mtime =
(time_t)((long)i_time | (~(long)0x7fffffffL));
} else if (dos_mdatetime >= DOSTIME_2038_01_18) {
ut_in_archive_sgn = 1;
z_utim->mtime =
(time_t)((ulg)i_time & (ulg)0xffffffffL);
} else {
ut_in_archive_sgn = 0;
/* cannot determine sign of mtime;
without modtime: ignore complete UT field */
flags &= ~0x0ff; /* no time_t times available */
TTrace((stderr,
" UX modtime range error: ignore e.f.!\n"));
}
} else {
/* cannot determine, safe assumption is FALSE */
ut_in_archive_sgn = 0;
z_utim->mtime = (time_t)i_time;
}
#else /* !TIME_T_TYPE_DOUBLE */
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
ut_zip_unzip_compatible =
((time_t)0x80000000L < (time_t)0L)
? (dos_mdatetime == DOSTIME_MINIMUM)
: (dos_mdatetime >= DOSTIME_2038_01_18);
if (!ut_zip_unzip_compatible) {
/* UnZip interpretes mtime differently than Zip;
without modtime: ignore complete UT field */
flags &= ~0x0ff; /* no time_t times available */
TTrace((stderr,
" UX modtime range error: ignore e.f.!\n"));
}
} else {
/* cannot determine, safe assumption is FALSE */
ut_zip_unzip_compatible = FALSE;
}
z_utim->mtime = (time_t)i_time;
#endif /* ?TIME_T_TYPE_DOUBLE */
i_time = (long)makelong((EB_HEADSIZE+EB_UX_ATIME)+ef_buf);
TTrace((stderr," Unix EF actime = %ld\n", i_time));
#ifdef TIME_T_TYPE_DOUBLE
if ((ulg)(i_time) & (ulg)(0x80000000L)) {
if (ut_in_archive_sgn == -1)
z_utim->atime =
(time_t)((long)i_time | (~(long)0x7fffffffL));
} else if (ut_in_archive_sgn == 1) {
z_utim->atime =
(time_t)((ulg)i_time & (ulg)0xffffffffL);
} else if (flags & 0x0ff) {
/* sign of 32-bit time is unknown -> ignore it */
flags &= ~EB_UT_FL_ATIME;
TTrace((stderr,
" UX access time range error: skip time!\n"));
}
} else {
z_utim->atime = (time_t)i_time;
}
#else /* !TIME_T_TYPE_DOUBLE */
if (((ulg)(i_time) & (ulg)(0x80000000L)) &&
!ut_zip_unzip_compatible && (flags & 0x0ff)) {
/* atime not in range of UnZip's time_t */
flags &= ~EB_UT_FL_ATIME;
TTrace((stderr,
" UX access time range error: skip time!\n"));
} else {
z_utim->atime = (time_t)i_time;
}
#endif /* ?TIME_T_TYPE_DOUBLE */
}
#ifdef IZ_HAVE_UXUIDGID
if (eb_len >= EB_UX_FULLSIZE && z_uidgid != NULL) {
z_uidgid[0] = makeword((EB_HEADSIZE+EB_UX_UID) + ef_buf);
z_uidgid[1] = makeword((EB_HEADSIZE+EB_UX_GID) + ef_buf);
flags |= EB_UX2_VALID;
}
#endif /* IZ_HAVE_UXUIDGID */
}
break;
default:
break;
}
/* Skip this extra field block */
ef_buf += (eb_len + EB_HEADSIZE);
ef_len -= (eb_len + EB_HEADSIZE);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400'], 'message': 'Do not raise a zip bomb alert for a misplaced central directory.
There is a zip-like file in the Firefox distribution, omni.ja,
which is a zip container with the central directory placed at the
start of the file instead of after the local entries as required
by the zip standard. This commit marks the actual location of the
central directory, as well as the end of central directory records,
as disallowed locations. This now permits such containers to not
raise a zip bomb alert, where in fact there are no overlaps.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int hci_conn_check_link_mode(struct hci_conn *conn)
{
BT_DBG("hcon %p", conn);
/* In Secure Connections Only mode, it is required that Secure
* Connections is used and the link is encrypted with AES-CCM
* using a P-256 authenticated combination key.
*/
if (hci_dev_test_flag(conn->hdev, HCI_SC_ONLY)) {
if (!hci_conn_sc_enabled(conn) ||
!test_bit(HCI_CONN_AES_CCM, &conn->flags) ||
conn->key_type != HCI_LK_AUTH_COMBINATION_P256)
return 0;
}
if (hci_conn_ssp_enabled(conn) &&
!test_bit(HCI_CONN_ENCRYPT, &conn->flags))
return 0;
/* The minimum encryption key size needs to be enforced by the
* host stack before establishing any L2CAP connections. The
* specification in theory allows a minimum of 1, but to align
* BR/EDR and LE transports, a minimum of 7 is chosen.
*/
if (conn->enc_key_size < HCI_MIN_ENC_KEY_SIZE)
return 0;
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-327'], 'message': 'Bluetooth: Fix regression with minimum encryption key size alignment
When trying to align the minimum encryption key size requirement for
Bluetooth connections, it turns out doing this in a central location in
the HCI connection handling code is not possible.
Original Bluetooth version up to 2.0 used a security model where the
L2CAP service would enforce authentication and encryption. Starting
with Bluetooth 2.1 and Secure Simple Pairing that model has changed into
that the connection initiator is responsible for providing an encrypted
ACL link before any L2CAP communication can happen.
Now connecting Bluetooth 2.1 or later devices with Bluetooth 2.0 and
before devices are causing a regression. The encryption key size check
needs to be moved out of the HCI connection handling into the L2CAP
channel setup.
To achieve this, the current check inside hci_conn_security() has been
moved into l2cap_check_enc_key_size() helper function and then called
from four decisions point inside L2CAP to cover all combinations of
Secure Simple Pairing enabled devices and device using legacy pairing
and legacy service security model.
Fixes: d5bb334a8e17 ("Bluetooth: Align minimum encryption key size for LE and BR/EDR connections")
Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=203643
Signed-off-by: Marcel Holtmann <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void l2cap_do_start(struct l2cap_chan *chan)
{
struct l2cap_conn *conn = chan->conn;
if (conn->hcon->type == LE_LINK) {
l2cap_le_start(chan);
return;
}
if (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT)) {
l2cap_request_info(conn);
return;
}
if (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE))
return;
if (l2cap_chan_check_security(chan, true) &&
__l2cap_no_conn_pending(chan))
l2cap_start_connection(chan);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-327'], 'message': 'Bluetooth: Fix regression with minimum encryption key size alignment
When trying to align the minimum encryption key size requirement for
Bluetooth connections, it turns out doing this in a central location in
the HCI connection handling code is not possible.
Original Bluetooth version up to 2.0 used a security model where the
L2CAP service would enforce authentication and encryption. Starting
with Bluetooth 2.1 and Secure Simple Pairing that model has changed into
that the connection initiator is responsible for providing an encrypted
ACL link before any L2CAP communication can happen.
Now connecting Bluetooth 2.1 or later devices with Bluetooth 2.0 and
before devices are causing a regression. The encryption key size check
needs to be moved out of the HCI connection handling into the L2CAP
channel setup.
To achieve this, the current check inside hci_conn_security() has been
moved into l2cap_check_enc_key_size() helper function and then called
from four decisions point inside L2CAP to cover all combinations of
Secure Simple Pairing enabled devices and device using legacy pairing
and legacy service security model.
Fixes: d5bb334a8e17 ("Bluetooth: Align minimum encryption key size for LE and BR/EDR connections")
Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=203643
Signed-off-by: Marcel Holtmann <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int hci_conn_security(struct hci_conn *conn, __u8 sec_level, __u8 auth_type,
bool initiator)
{
BT_DBG("hcon %p", conn);
if (conn->type == LE_LINK)
return smp_conn_security(conn, sec_level);
/* For sdp we don't need the link key. */
if (sec_level == BT_SECURITY_SDP)
return 1;
/* For non 2.1 devices and low security level we don't need the link
key. */
if (sec_level == BT_SECURITY_LOW && !hci_conn_ssp_enabled(conn))
return 1;
/* For other security levels we need the link key. */
if (!test_bit(HCI_CONN_AUTH, &conn->flags))
goto auth;
/* An authenticated FIPS approved combination key has sufficient
* security for security level 4. */
if (conn->key_type == HCI_LK_AUTH_COMBINATION_P256 &&
sec_level == BT_SECURITY_FIPS)
goto encrypt;
/* An authenticated combination key has sufficient security for
security level 3. */
if ((conn->key_type == HCI_LK_AUTH_COMBINATION_P192 ||
conn->key_type == HCI_LK_AUTH_COMBINATION_P256) &&
sec_level == BT_SECURITY_HIGH)
goto encrypt;
/* An unauthenticated combination key has sufficient security for
security level 1 and 2. */
if ((conn->key_type == HCI_LK_UNAUTH_COMBINATION_P192 ||
conn->key_type == HCI_LK_UNAUTH_COMBINATION_P256) &&
(sec_level == BT_SECURITY_MEDIUM || sec_level == BT_SECURITY_LOW))
goto encrypt;
/* A combination key has always sufficient security for the security
levels 1 or 2. High security level requires the combination key
is generated using maximum PIN code length (16).
For pre 2.1 units. */
if (conn->key_type == HCI_LK_COMBINATION &&
(sec_level == BT_SECURITY_MEDIUM || sec_level == BT_SECURITY_LOW ||
conn->pin_length == 16))
goto encrypt;
auth:
if (test_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags))
return 0;
if (initiator)
set_bit(HCI_CONN_AUTH_INITIATOR, &conn->flags);
if (!hci_conn_auth(conn, sec_level, auth_type))
return 0;
encrypt:
if (test_bit(HCI_CONN_ENCRYPT, &conn->flags))
return 1;
hci_conn_encrypt(conn);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-327'], 'message': 'Bluetooth: Fix regression with minimum encryption key size alignment
When trying to align the minimum encryption key size requirement for
Bluetooth connections, it turns out doing this in a central location in
the HCI connection handling code is not possible.
Original Bluetooth version up to 2.0 used a security model where the
L2CAP service would enforce authentication and encryption. Starting
with Bluetooth 2.1 and Secure Simple Pairing that model has changed into
that the connection initiator is responsible for providing an encrypted
ACL link before any L2CAP communication can happen.
Now connecting Bluetooth 2.1 or later devices with Bluetooth 2.0 and
before devices are causing a regression. The encryption key size check
needs to be moved out of the HCI connection handling into the L2CAP
channel setup.
To achieve this, the current check inside hci_conn_security() has been
moved into l2cap_check_enc_key_size() helper function and then called
from four decisions point inside L2CAP to cover all combinations of
Secure Simple Pairing enabled devices and device using legacy pairing
and legacy service security model.
Fixes: d5bb334a8e17 ("Bluetooth: Align minimum encryption key size for LE and BR/EDR connections")
Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=203643
Signed-off-by: Marcel Holtmann <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport void RemoveDuplicateLayers(Image **images,
ExceptionInfo *exception)
{
register Image
*curr,
*next;
RectangleInfo
bounds;
assert((*images) != (const Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
curr=GetFirstImageInList(*images);
for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next)
{
if ( curr->columns != next->columns || curr->rows != next->rows
|| curr->page.x != next->page.x || curr->page.y != next->page.y )
continue;
bounds=CompareImagesBounds(curr,next,CompareAnyLayer,exception);
if ( bounds.x < 0 ) {
/*
the two images are the same, merge time delays and delete one.
*/
size_t time;
time = curr->delay*1000/curr->ticks_per_second;
time += next->delay*1000/next->ticks_per_second;
next->ticks_per_second = 100L;
next->delay = time*curr->ticks_per_second/1000;
next->iterations = curr->iterations;
*images = curr;
(void) DeleteImageFromList(images);
}
}
*images = GetFirstImageInList(*images);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1629'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void PngImage::readMetadata()
{
#ifdef DEBUG
std::cerr << "Exiv2::PngImage::readMetadata: Reading PNG file " << io_->path() << std::endl;
#endif
if (io_->open() != 0)
{
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
}
IoCloser closer(*io_);
if (!isPngType(*io_, true)) {
throw Error(kerNotAnImage, "PNG");
}
clearMetadata();
const long imgSize = (long) io_->size();
DataBuf cheaderBuf(8); // Chunk header: 4 bytes (data size) + 4 bytes (chunk type).
while(!io_->eof())
{
std::memset(cheaderBuf.pData_, 0x0, cheaderBuf.size_);
readChunk(cheaderBuf, *io_); // Read chunk header.
// Decode chunk data length.
uint32_t chunkLength = Exiv2::getULong(cheaderBuf.pData_, Exiv2::bigEndian);
long pos = io_->tell();
if (pos == -1 ||
chunkLength > uint32_t(0x7FFFFFFF) ||
static_cast<long>(chunkLength) > imgSize - pos) {
throw Exiv2::Error(kerFailedToReadImageData);
}
std::string chunkType(reinterpret_cast<char *>(cheaderBuf.pData_) + 4, 4);
#ifdef DEBUG
std::cout << "Exiv2::PngImage::readMetadata: chunk type: " << chunkType
<< " length: " << chunkLength << std::endl;
#endif
/// \todo analyse remaining chunks of the standard
// Perform a chunk triage for item that we need.
if (chunkType == "IEND" || chunkType == "IHDR" || chunkType == "tEXt" || chunkType == "zTXt" ||
chunkType == "iTXt" || chunkType == "iCCP") {
DataBuf chunkData(chunkLength);
readChunk(chunkData, *io_); // Extract chunk data.
if (chunkType == "IEND") {
return; // Last chunk found: we stop parsing.
} else if (chunkType == "IHDR" && chunkData.size_ >= 8) {
PngChunk::decodeIHDRChunk(chunkData, &pixelWidth_, &pixelHeight_);
} else if (chunkType == "tEXt") {
PngChunk::decodeTXTChunk(this, chunkData, PngChunk::tEXt_Chunk);
} else if (chunkType == "zTXt") {
PngChunk::decodeTXTChunk(this, chunkData, PngChunk::zTXt_Chunk);
} else if (chunkType == "iTXt") {
PngChunk::decodeTXTChunk(this, chunkData, PngChunk::iTXt_Chunk);
} else if (chunkType == "iCCP") {
// The ICC profile name can vary from 1-79 characters.
uint32_t iccOffset = 0;
while (iccOffset < 80 && iccOffset < chunkLength) {
if (chunkData.pData_[iccOffset++] == 0x00) {
break;
}
}
profileName_ = std::string(reinterpret_cast<char *>(chunkData.pData_), iccOffset-1);
++iccOffset; // +1 = 'compressed' flag
enforce(iccOffset <= chunkLength, Exiv2::kerCorruptedMetadata);
zlibToDataBuf(chunkData.pData_ + iccOffset, chunkLength - iccOffset, iccProfile_);
#ifdef DEBUG
std::cout << "Exiv2::PngImage::readMetadata: profile name: " << profileName_ << std::endl;
std::cout << "Exiv2::PngImage::readMetadata: iccProfile.size_ (uncompressed) : "
<< iccProfile_.size_ << std::endl;
#endif
}
// Set chunkLength to 0 in case we have read a supported chunk type. Otherwise, we need to seek the
// file to the next chunk position.
chunkLength = 0;
}
// Move to the next chunk: chunk data size + 4 CRC bytes.
#ifdef DEBUG
std::cout << "Exiv2::PngImage::readMetadata: Seek to offset: " << chunkLength + 4 << std::endl;
#endif
io_->seek(chunkLength + 4 , BasicIo::cur);
if (io_->error() || io_->eof()) {
throw Error(kerFailedToReadImageData);
}
}
} // PngImage::readMetadata ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Avoid negative integer overflow when `chunkLength == 0`.
This fixes #789.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void PngImage::readMetadata()
{
#ifdef DEBUG
std::cerr << "Exiv2::PngImage::readMetadata: Reading PNG file " << io_->path() << std::endl;
#endif
if (io_->open() != 0)
{
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
}
IoCloser closer(*io_);
if (!isPngType(*io_, true)) {
throw Error(kerNotAnImage, "PNG");
}
clearMetadata();
const long imgSize = (long) io_->size();
DataBuf cheaderBuf(8); // Chunk header: 4 bytes (data size) + 4 bytes (chunk type).
while(!io_->eof())
{
std::memset(cheaderBuf.pData_, 0x0, cheaderBuf.size_);
readChunk(cheaderBuf, *io_); // Read chunk header.
// Decode chunk data length.
uint32_t chunkLength = Exiv2::getULong(cheaderBuf.pData_, Exiv2::bigEndian);
long pos = io_->tell();
if (pos == -1 ||
chunkLength > uint32_t(0x7FFFFFFF) ||
static_cast<long>(chunkLength) > imgSize - pos) {
throw Exiv2::Error(kerFailedToReadImageData);
}
std::string chunkType(reinterpret_cast<char *>(cheaderBuf.pData_) + 4, 4);
#ifdef DEBUG
std::cout << "Exiv2::PngImage::readMetadata: chunk type: " << chunkType
<< " length: " << chunkLength << std::endl;
#endif
/// \todo analyse remaining chunks of the standard
// Perform a chunk triage for item that we need.
if (chunkType == "IEND" || chunkType == "IHDR" || chunkType == "tEXt" || chunkType == "zTXt" ||
chunkType == "iTXt" || chunkType == "iCCP") {
DataBuf chunkData(chunkLength);
readChunk(chunkData, *io_); // Extract chunk data.
if (chunkType == "IEND") {
return; // Last chunk found: we stop parsing.
} else if (chunkType == "IHDR" && chunkData.size_ >= 8) {
PngChunk::decodeIHDRChunk(chunkData, &pixelWidth_, &pixelHeight_);
} else if (chunkType == "tEXt") {
PngChunk::decodeTXTChunk(this, chunkData, PngChunk::tEXt_Chunk);
} else if (chunkType == "zTXt") {
PngChunk::decodeTXTChunk(this, chunkData, PngChunk::zTXt_Chunk);
} else if (chunkType == "iTXt") {
PngChunk::decodeTXTChunk(this, chunkData, PngChunk::iTXt_Chunk);
} else if (chunkType == "iCCP") {
// The ICC profile name can vary from 1-79 characters.
uint32_t iccOffset = 0;
while (iccOffset < 80 && iccOffset < chunkLength) {
if (chunkData.pData_[iccOffset++] == 0x00) {
break;
}
}
profileName_ = std::string(reinterpret_cast<char *>(chunkData.pData_), iccOffset-1);
++iccOffset; // +1 = 'compressed' flag
zlibToDataBuf(chunkData.pData_ + iccOffset, chunkLength - iccOffset, iccProfile_);
#ifdef DEBUG
std::cout << "Exiv2::PngImage::readMetadata: profile name: " << profileName_ << std::endl;
std::cout << "Exiv2::PngImage::readMetadata: iccProfile.size_ (uncompressed) : "
<< iccProfile_.size_ << std::endl;
#endif
}
// Set chunkLength to 0 in case we have read a supported chunk type. Otherwise, we need to seek the
// file to the next chunk position.
chunkLength = 0;
}
// Move to the next chunk: chunk data size + 4 CRC bytes.
#ifdef DEBUG
std::cout << "Exiv2::PngImage::readMetadata: Seek to offset: " << chunkLength + 4 << std::endl;
#endif
io_->seek(chunkLength + 4 , BasicIo::cur);
if (io_->error() || io_->eof()) {
throw Error(kerFailedToReadImageData);
}
}
} // PngImage::readMetadata ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Avoid negative integer overflow when `iccOffset > chunkLength`.
This fixes #790.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void CiffDirectory::readDirectory(const byte* pData,
uint32_t size,
ByteOrder byteOrder)
{
if (size < 4)
throw Error(kerCorruptedMetadata);
uint32_t o = getULong(pData + size - 4, byteOrder);
if ( o+2 > size )
throw Error(kerCorruptedMetadata);
uint16_t count = getUShort(pData + o, byteOrder);
#ifdef DEBUG
std::cout << "Directory at offset " << std::dec << o
<<", " << count << " entries \n";
#endif
o += 2;
if ( (o + (count * 10)) > size )
throw Error(kerCorruptedMetadata);
for (uint16_t i = 0; i < count; ++i) {
uint16_t tag = getUShort(pData + o, byteOrder);
CiffComponent::AutoPtr m;
switch (CiffComponent::typeId(tag)) {
case directory: m = CiffComponent::AutoPtr(new CiffDirectory); break;
default: m = CiffComponent::AutoPtr(new CiffEntry); break;
}
m->setDir(this->tag());
m->read(pData, size, o, byteOrder);
add(m);
o += 10;
}
} // CiffDirectory::readDirectory ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Avoid integer overflow.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool isWebPType(BasicIo& iIo, bool /*advance*/)
{
const int32_t len = 4;
const unsigned char RiffImageId[4] = { 'R', 'I', 'F' ,'F'};
const unsigned char WebPImageId[4] = { 'W', 'E', 'B' ,'P'};
byte webp[len];
byte data[len];
byte riff[len];
iIo.read(riff, len);
iIo.read(data, len);
iIo.read(webp, len);
bool matched_riff = (memcmp(riff, RiffImageId, len) == 0);
bool matched_webp = (memcmp(webp, WebPImageId, len) == 0);
iIo.seek(-12, BasicIo::cur);
return matched_riff && matched_webp;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Avoid negative integer overflow when `filesize < io_->tell()`.
This fixes #791.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void WebPImage::decodeChunks(uint64_t filesize)
{
DataBuf chunkId(5);
byte size_buff[WEBP_TAG_SIZE];
bool has_canvas_data = false;
#ifdef DEBUG
std::cout << "Reading metadata" << std::endl;
#endif
chunkId.pData_[4] = '\0' ;
while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {
io_->read(chunkId.pData_, WEBP_TAG_SIZE);
io_->read(size_buff, WEBP_TAG_SIZE);
const uint32_t size = Exiv2::getULong(size_buff, littleEndian);
enforce(size <= (filesize - io_->tell()), Exiv2::kerCorruptedMetadata);
DataBuf payload(size);
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_canvas_data) {
enforce(size >= 10, Exiv2::kerCorruptedMetadata);
has_canvas_data = true;
byte size_buf[WEBP_TAG_SIZE];
io_->read(payload.pData_, payload.size_);
// Fetch width
memcpy(&size_buf, &payload.pData_[4], 3);
size_buf[3] = 0;
pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) + 1;
// Fetch height
memcpy(&size_buf, &payload.pData_[7], 3);
size_buf[3] = 0;
pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) + 1;
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_canvas_data) {
enforce(size >= 10, Exiv2::kerCorruptedMetadata);
has_canvas_data = true;
io_->read(payload.pData_, payload.size_);
byte size_buf[WEBP_TAG_SIZE];
// Fetch width""
memcpy(&size_buf, &payload.pData_[6], 2);
size_buf[2] = 0;
size_buf[3] = 0;
pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) & 0x3fff;
// Fetch height
memcpy(&size_buf, &payload.pData_[8], 2);
size_buf[2] = 0;
size_buf[3] = 0;
pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) & 0x3fff;
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_canvas_data) {
enforce(size >= 5, Exiv2::kerCorruptedMetadata);
has_canvas_data = true;
byte size_buf_w[2];
byte size_buf_h[3];
io_->read(payload.pData_, payload.size_);
// Fetch width
memcpy(&size_buf_w, &payload.pData_[1], 2);
size_buf_w[1] &= 0x3F;
pixelWidth_ = Exiv2::getUShort(size_buf_w, littleEndian) + 1;
// Fetch height
memcpy(&size_buf_h, &payload.pData_[2], 3);
size_buf_h[0] = ((size_buf_h[0] >> 6) & 0x3) | ((size_buf_h[1] & 0x3F) << 0x2);
size_buf_h[1] = ((size_buf_h[1] >> 6) & 0x3) | ((size_buf_h[2] & 0xF) << 0x2);
pixelHeight_ = Exiv2::getUShort(size_buf_h, littleEndian) + 1;
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_canvas_data) {
enforce(size >= 12, Exiv2::kerCorruptedMetadata);
has_canvas_data = true;
byte size_buf[WEBP_TAG_SIZE];
io_->read(payload.pData_, payload.size_);
// Fetch width
memcpy(&size_buf, &payload.pData_[6], 3);
size_buf[3] = 0;
pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) + 1;
// Fetch height
memcpy(&size_buf, &payload.pData_[9], 3);
size_buf[3] = 0;
pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) + 1;
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP)) {
io_->read(payload.pData_, payload.size_);
this->setIccProfile(payload);
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF)) {
io_->read(payload.pData_, payload.size_);
byte size_buff[2];
// 4 meaningful bytes + 2 padding bytes
byte exifLongHeader[] = { 0xFF, 0x01, 0xFF, 0xE1, 0x00, 0x00 };
byte exifShortHeader[] = { 0x45, 0x78, 0x69, 0x66, 0x00, 0x00 };
byte exifTiffLEHeader[] = { 0x49, 0x49, 0x2A }; // "MM*"
byte exifTiffBEHeader[] = { 0x4D, 0x4D, 0x00, 0x2A }; // "II\0*"
byte* rawExifData = NULL;
long offset = 0;
bool s_header = false;
bool le_header = false;
bool be_header = false;
long pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifLongHeader, 4);
if (pos == -1) {
pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifLongHeader, 6);
if (pos != -1) {
s_header = true;
}
}
if (pos == -1) {
pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifTiffLEHeader, 3);
if (pos != -1) {
le_header = true;
}
}
if (pos == -1) {
pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifTiffBEHeader, 4);
if (pos != -1) {
be_header = true;
}
}
if (s_header) {
offset += 6;
}
if (be_header || le_header) {
offset += 12;
}
const long size = payload.size_ + offset;
rawExifData = (byte*)malloc(size);
if (s_header) {
us2Data(size_buff, (uint16_t) (size - 6), bigEndian);
memcpy(rawExifData, (char*)&exifLongHeader, 4);
memcpy(rawExifData + 4, (char*)&size_buff, 2);
}
if (be_header || le_header) {
us2Data(size_buff, (uint16_t) (size - 6), bigEndian);
memcpy(rawExifData, (char*)&exifLongHeader, 4);
memcpy(rawExifData + 4, (char*)&size_buff, 2);
memcpy(rawExifData + 6, (char*)&exifShortHeader, 6);
}
memcpy(rawExifData + offset, payload.pData_, payload.size_);
#ifdef DEBUG
std::cout << "Display Hex Dump [size:" << (unsigned long)size << "]" << std::endl;
std::cout << Internal::binaryToHex(rawExifData, size);
#endif
if (pos != -1) {
XmpData xmpData;
ByteOrder bo = ExifParser::decode(exifData_,
payload.pData_ + pos,
payload.size_ - pos);
setByteOrder(bo);
}
else
{
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Failed to decode Exif metadata." << std::endl;
#endif
exifData_.clear();
}
if (rawExifData) free(rawExifData);
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP)) {
io_->read(payload.pData_, payload.size_);
xmpPacket_.assign(reinterpret_cast<char*>(payload.pData_), payload.size_);
if (xmpPacket_.size() > 0 && XmpParser::decode(xmpData_, xmpPacket_)) {
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Failed to decode XMP metadata." << std::endl;
#endif
} else {
#ifdef DEBUG
std::cout << "Display Hex Dump [size:" << (unsigned long)payload.size_ << "]" << std::endl;
std::cout << Internal::binaryToHex(payload.pData_, payload.size_);
#endif
}
} else {
io_->seek(size, BasicIo::cur);
}
if ( io_->tell() % 2 ) io_->seek(+1, BasicIo::cur);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Avoid negative integer overflow when `filesize < io_->tell()`.
This fixes #791.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: DataLocId CiffComponent::dataLocation(uint16_t tag)
{
DataLocId di = invalidDataLocId;
switch (tag & 0xc000) {
case 0x0000: di = valueData; break;
case 0x4000: di = directoryData; break;
}
return di;
} // CiffComponent::dataLocation ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-617'], 'message': 'Throw an exception if the data location is invalid. (#842)
(cherry picked from commit 7798ae25574425271305fffe85de77bec8df03f1)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int Exiv2::http(Exiv2::Dictionary& request,Exiv2::Dictionary& response,std::string& errors)
{
if ( !request.count("verb") ) request["verb" ] = "GET";
if ( !request.count("header") ) request["header" ] = "" ;
if ( !request.count("version")) request["version"] = "1.0";
if ( !request.count("port") ) request["port" ] = "" ;
std::string file;
errors = "";
int result = 0;
////////////////////////////////////
// Windows specific code
#ifdef WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
#endif
const char* servername = request["server" ].c_str();
const char* page = request["page" ].c_str();
const char* verb = request["verb" ].c_str();
const char* header = request["header" ].c_str();
const char* version = request["version"].c_str();
const char* port = request["port" ].c_str();
const char* servername_p = servername;
const char* port_p = port ;
std::string url = std::string("http://") + request["server"] + request["page"];
// parse and change server if using a proxy
const char* PROXI = "HTTP_PROXY";
const char* proxi = "http_proxy";
const char* PROXY = getenv(PROXI);
const char* proxy = getenv(proxi);
bool bProx = PROXY || proxy;
const char* prox = bProx ? (proxy?proxy:PROXY):"";
Exiv2::Uri Proxy = Exiv2::Uri::Parse(prox);
// find the dictionary of no_proxy servers
const char* NO_PROXI = "NO_PROXY";
const char* no_proxi = "no_proxy";
const char* NO_PROXY = getenv(NO_PROXI);
const char* no_proxy = getenv(no_proxi);
bool bNoProxy = NO_PROXY||no_proxy;
std::string no_prox = std::string(bNoProxy?(no_proxy?no_proxy:NO_PROXY):"");
Exiv2::Dictionary noProxy= stringToDict(no_prox + ",localhost,127.0.0.1");
// if the server is on the no_proxy list ... ignore the proxy!
if ( noProxy.count(servername) ) bProx = false;
if ( bProx ) {
servername_p = Proxy.Host.c_str();
port_p = Proxy.Port.c_str();
page = url.c_str();
std::string p(proxy?proxi:PROXI);
// std::cerr << p << '=' << prox << " page = " << page << std::endl;
}
if ( !port [0] ) port = "80";
if ( !port_p[0] ) port_p = "80";
////////////////////////////////////
// open the socket
int sockfd = (int) socket(AF_INET , SOCK_STREAM,IPPROTO_TCP) ;
if ( sockfd < 0 ) return error(errors, "unable to create socket\n",NULL,NULL,0) ;
// connect the socket to the server
int server = -1 ;
// fill in the address
struct sockaddr_in serv_addr ;
int serv_len = sizeof(serv_addr);
memset((char *)&serv_addr,0,serv_len);
serv_addr.sin_addr.s_addr = inet_addr(servername_p);
serv_addr.sin_family = AF_INET ;
serv_addr.sin_port = htons(atoi(port_p));
// convert unknown servername into IP address
// http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzab6/rzab6uafinet.htm
if (serv_addr.sin_addr.s_addr == (unsigned long)INADDR_NONE)
{
struct hostent* host = gethostbyname(servername_p);
if ( !host ) return error(errors, "no such host", servername_p);
memcpy(&serv_addr.sin_addr,host->h_addr,sizeof(serv_addr.sin_addr));
}
makeNonBlocking(sockfd) ;
////////////////////////////////////
// and connect
server = connect(sockfd, (const struct sockaddr *) &serv_addr, serv_len) ;
if ( server == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK )
return error(errors,"error - unable to connect to server = %s port = %s wsa_error = %d",servername_p,port_p,WSAGetLastError());
char buffer[32*1024+1];
size_t buff_l= sizeof buffer - 1 ;
////////////////////////////////////
// format the request
int n = snprintf(buffer,buff_l,httpTemplate,verb,page,version,servername,header) ;
buffer[n] = 0 ;
response["requestheaders"]=std::string(buffer,n);
////////////////////////////////////
// send the header (we'll have to wait for the connection by the non-blocking socket)
while ( sleep_ >= 0 && send(sockfd,buffer,n,0) == SOCKET_ERROR /* && WSAGetLastError() == WSAENOTCONN */ ) {
Sleep(snooze) ;
sleep_ -= snooze ;
}
if ( sleep_ < 0 )
return error(errors,"error - timeout connecting to server = %s port = %s wsa_error = %d",servername,port,WSAGetLastError());
int end = 0 ; // write position in buffer
bool bSearching = true ; // looking for headers in the response
int status= 200 ; // assume happiness
////////////////////////////////////
// read and process the response
int err ;
n=forgive(recv(sockfd,buffer,(int)buff_l,0),err) ;
while ( n >= 0 && OK(status) ) {
if ( n ) {
end += n ;
buffer[end] = 0 ;
size_t body = 0 ; // start of body
if ( bSearching ) {
// search for the body
for ( size_t b = 0 ; bSearching && b < lengthof(blankLines) ; b++ ) {
if ( strstr(buffer,blankLines[b]) ) {
bSearching = false ;
body = (int) ( strstr(buffer,blankLines[b]) - buffer ) + strlen(blankLines[b]) ;
status = atoi(strchr(buffer,' ')) ;
}
}
// parse response headers
char* h = buffer;
char C = ':' ;
char N = '\n';
int i = 0 ; // initial byte in buffer
while(buffer[i] == N ) i++;
h = strchr(h+i,N)+1;
response[""]=std::string(buffer+i).substr(0,h-buffer-2);
result = atoi(strchr(buffer,' '));
char* c = strchr(h,C);
char* first_newline = strchr(h,N);
while ( c && first_newline && c < first_newline && h < buffer+body ) {
std::string key(h);
std::string value(c+1);
key = key.substr(0,c-h);
value = value.substr(0,first_newline-c-1);
response[key]=value;
h = first_newline+1;
c = strchr(h,C);
first_newline = strchr(h,N);
}
}
// if the bufffer's full and we're still searching - give up!
// this handles the possibility that there are no headers
if ( bSearching && buff_l-end < 10 ) {
bSearching = false ;
body = 0 ;
}
if ( !bSearching && OK(status) ) {
flushBuffer(buffer,body,end,file);
}
}
n=forgive(recv(sockfd,buffer+end,(int)(buff_l-end),0),err) ;
if ( !n ) {
Sleep(snooze) ;
sleep_ -= snooze ;
if ( sleep_ < 0 ) n = FINISH ;
}
}
if ( n != FINISH || !OK(status) ) {
snprintf(buffer,sizeof buffer,"wsa_error = %d,n = %d,sleep_ = %d status = %d"
, WSAGetLastError()
, n
, sleep_
, status
) ;
error(errors,buffer,NULL,NULL,0) ;
} else if ( bSearching && OK(status) ) {
if ( end ) {
// we finished OK without finding headers, flush the buffer
flushBuffer(buffer,0,end,file) ;
} else {
return error(errors,"error - no response from server = %s port = %s wsa_error = %d",servername,port,WSAGetLastError());
}
}
////////////////////////////////////
// close sockets
closesocket(server) ;
closesocket(sockfd) ;
response["body"]=file;
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Avoid null pointer exception due to NULL return value from strchr.
This fixes #793.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-369'], 'message': '[MJ2] To avoid divisions by zero / undefined behaviour on shift
Signed-off-by: Young_X <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block)
{
OPJ_UINT32 (*l_gain_ptr)(OPJ_UINT32) = 00;
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
opj_tcp_t * l_tcp = 00;
opj_cp_t * l_cp = 00;
opj_tcd_tile_t * l_tile = 00;
opj_tccp_t *l_tccp = 00;
opj_tcd_tilecomp_t *l_tilec = 00;
opj_image_comp_t * l_image_comp = 00;
opj_tcd_resolution_t *l_res = 00;
opj_tcd_band_t *l_band = 00;
opj_stepsize_t * l_step_size = 00;
opj_tcd_precinct_t *l_current_precinct = 00;
opj_image_t *l_image = 00;
OPJ_UINT32 p,q;
OPJ_UINT32 l_level_no;
OPJ_UINT32 l_pdx, l_pdy;
OPJ_UINT32 l_gain;
OPJ_INT32 l_x0b, l_y0b;
/* extent of precincts , top left, bottom right**/
OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end;
/* number of precinct for a resolution */
OPJ_UINT32 l_nb_precincts;
/* room needed to store l_nb_precinct precinct for a resolution */
OPJ_UINT32 l_nb_precinct_size;
/* number of code blocks for a precinct*/
OPJ_UINT32 l_nb_code_blocks;
/* room needed to store l_nb_code_blocks code blocks for a precinct*/
OPJ_UINT32 l_nb_code_blocks_size;
/* size of data for a tile */
OPJ_UINT32 l_data_size;
l_cp = p_tcd->cp;
l_tcp = &(l_cp->tcps[p_tile_no]);
l_tile = p_tcd->tcd_image->tiles;
l_tccp = l_tcp->tccps;
l_tilec = l_tile->comps;
l_image = p_tcd->image;
l_image_comp = p_tcd->image->comps;
p = p_tile_no % l_cp->tw; /* tile coordinates */
q = p_tile_no / l_cp->tw;
/*fprintf(stderr, "Tile coordinate = %d,%d\n", p, q);*/
/* 4 borders of the tile rescale on the image if necessary */
l_tile->x0 = opj_int_max((OPJ_INT32)(l_cp->tx0 + p * l_cp->tdx), (OPJ_INT32)l_image->x0);
l_tile->y0 = opj_int_max((OPJ_INT32)(l_cp->ty0 + q * l_cp->tdy), (OPJ_INT32)l_image->y0);
l_tile->x1 = opj_int_min((OPJ_INT32)(l_cp->tx0 + (p + 1) * l_cp->tdx), (OPJ_INT32)l_image->x1);
l_tile->y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (q + 1) * l_cp->tdy), (OPJ_INT32)l_image->y1);
/* testcase 1888.pdf.asan.35.988 */
if (l_tccp->numresolutions == 0) {
fprintf(stderr, "tiles require at least one resolution\n");
return OPJ_FALSE;
}
/*fprintf(stderr, "Tile border = %d,%d,%d,%d\n", l_tile->x0, l_tile->y0,l_tile->x1,l_tile->y1);*/
/*tile->numcomps = image->numcomps; */
for (compno = 0; compno < l_tile->numcomps; ++compno) {
/*fprintf(stderr, "compno = %d/%d\n", compno, l_tile->numcomps);*/
l_image_comp->resno_decoded = 0;
/* border of each l_tile component (global) */
l_tilec->x0 = opj_int_ceildiv(l_tile->x0, (OPJ_INT32)l_image_comp->dx);
l_tilec->y0 = opj_int_ceildiv(l_tile->y0, (OPJ_INT32)l_image_comp->dy);
l_tilec->x1 = opj_int_ceildiv(l_tile->x1, (OPJ_INT32)l_image_comp->dx);
l_tilec->y1 = opj_int_ceildiv(l_tile->y1, (OPJ_INT32)l_image_comp->dy);
/*fprintf(stderr, "\tTile compo border = %d,%d,%d,%d\n", l_tilec->x0, l_tilec->y0,l_tilec->x1,l_tilec->y1);*/
/* compute l_data_size with overflow check */
l_data_size = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
if ((((OPJ_UINT32)-1) / l_data_size) < (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0)) {
/* TODO event */
return OPJ_FALSE;
}
l_data_size = l_data_size * (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
if ((((OPJ_UINT32)-1) / (OPJ_UINT32)sizeof(OPJ_UINT32)) < l_data_size) {
/* TODO event */
return OPJ_FALSE;
}
l_data_size = l_data_size * (OPJ_UINT32)sizeof(OPJ_UINT32);
l_tilec->numresolutions = l_tccp->numresolutions;
if (l_tccp->numresolutions < l_cp->m_specific_param.m_dec.m_reduce) {
l_tilec->minimum_num_resolutions = 1;
}
else {
l_tilec->minimum_num_resolutions = l_tccp->numresolutions - l_cp->m_specific_param.m_dec.m_reduce;
}
l_tilec->data_size_needed = l_data_size;
if (p_tcd->m_is_decoder && !opj_alloc_tile_component_data(l_tilec)) {
return OPJ_FALSE;
}
l_data_size = l_tilec->numresolutions * (OPJ_UINT32)sizeof(opj_tcd_resolution_t);
if (l_tilec->resolutions == 00) {
l_tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(l_data_size);
if (! l_tilec->resolutions ) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\tAllocate resolutions of tilec (opj_tcd_resolution_t): %d\n",l_data_size);*/
l_tilec->resolutions_size = l_data_size;
memset(l_tilec->resolutions,0,l_data_size);
}
else if (l_data_size > l_tilec->resolutions_size) {
opj_tcd_resolution_t* new_resolutions = (opj_tcd_resolution_t *) opj_realloc(l_tilec->resolutions, l_data_size);
if (! new_resolutions) {
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to tile resolutions\n"); */
fprintf(stderr, "Not enough memory to tile resolutions\n");
opj_free(l_tilec->resolutions);
l_tilec->resolutions = NULL;
l_tilec->resolutions_size = 0;
return OPJ_FALSE;
}
l_tilec->resolutions = new_resolutions;
/*fprintf(stderr, "\tReallocate data of tilec (int): from %d to %d x OPJ_UINT32\n", l_tilec->resolutions_size, l_data_size);*/
memset(((OPJ_BYTE*) l_tilec->resolutions)+l_tilec->resolutions_size,0,l_data_size - l_tilec->resolutions_size);
l_tilec->resolutions_size = l_data_size;
}
l_level_no = l_tilec->numresolutions - 1;
l_res = l_tilec->resolutions;
l_step_size = l_tccp->stepsizes;
if (l_tccp->qmfbid == 0) {
l_gain_ptr = &opj_dwt_getgain_real;
}
else {
l_gain_ptr = &opj_dwt_getgain;
}
/*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/
for (resno = 0; resno < l_tilec->numresolutions; ++resno) {
/*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/
OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/;
OPJ_UINT32 cbgwidthexpn, cbgheightexpn;
OPJ_UINT32 cblkwidthexpn, cblkheightexpn;
/* border for each resolution level (global) */
l_res->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
l_res->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
l_res->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
l_res->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
/*fprintf(stderr, "\t\t\tres_x0= %d, res_y0 =%d, res_x1=%d, res_y1=%d\n", l_res->x0, l_res->y0, l_res->x1, l_res->y1);*/
/* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
/*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/
/* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */
l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx;
l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy;
l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx;
l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy;
/*fprintf(stderr, "\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/
l_res->pw = (l_res->x0 == l_res->x1) ? 0 : (OPJ_UINT32)((l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx);
l_res->ph = (l_res->y0 == l_res->y1) ? 0 : (OPJ_UINT32)((l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy);
/*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/
l_nb_precincts = l_res->pw * l_res->ph;
l_nb_precinct_size = l_nb_precincts * (OPJ_UINT32)sizeof(opj_tcd_precinct_t);
if (resno == 0) {
tlcbgxstart = l_tl_prc_x_start;
tlcbgystart = l_tl_prc_y_start;
/*brcbgxend = l_br_prc_x_end;*/
/* brcbgyend = l_br_prc_y_end;*/
cbgwidthexpn = l_pdx;
cbgheightexpn = l_pdy;
l_res->numbands = 1;
}
else {
tlcbgxstart = opj_int_ceildivpow2(l_tl_prc_x_start, 1);
tlcbgystart = opj_int_ceildivpow2(l_tl_prc_y_start, 1);
/*brcbgxend = opj_int_ceildivpow2(l_br_prc_x_end, 1);*/
/*brcbgyend = opj_int_ceildivpow2(l_br_prc_y_end, 1);*/
cbgwidthexpn = l_pdx - 1;
cbgheightexpn = l_pdy - 1;
l_res->numbands = 3;
}
cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn);
cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn);
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno) {
OPJ_INT32 numbps;
/*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/
if (resno == 0) {
l_band->bandno = 0 ;
l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
l_band->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
}
else {
l_band->bandno = bandno + 1;
/* x0b = 1 if bandno = 1 or 3 */
l_x0b = l_band->bandno&1;
/* y0b = 1 if bandno = 2 or 3 */
l_y0b = (OPJ_INT32)((l_band->bandno)>>1);
/* l_band border (global) */
l_band->x0 = opj_int_ceildivpow2(l_tilec->x0 - (1 << l_level_no) * l_x0b, (OPJ_INT32)(l_level_no + 1));
l_band->y0 = opj_int_ceildivpow2(l_tilec->y0 - (1 << l_level_no) * l_y0b, (OPJ_INT32)(l_level_no + 1));
l_band->x1 = opj_int_ceildivpow2(l_tilec->x1 - (1 << l_level_no) * l_x0b, (OPJ_INT32)(l_level_no + 1));
l_band->y1 = opj_int_ceildivpow2(l_tilec->y1 - (1 << l_level_no) * l_y0b, (OPJ_INT32)(l_level_no + 1));
}
/** avoid an if with storing function pointer */
l_gain = (*l_gain_ptr) (l_band->bandno);
numbps = (OPJ_INT32)(l_image_comp->prec + l_gain);
l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0, (OPJ_INT32) (numbps - l_step_size->expn)))) * fraction;
l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits - 1; /* WHY -1 ? */
if (! l_band->precincts) {
l_band->precincts = (opj_tcd_precinct_t *) opj_malloc( /*3 * */ l_nb_precinct_size);
if (! l_band->precincts) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\t\t\t\tAllocate precincts of a band (opj_tcd_precinct_t): %d\n",l_nb_precinct_size); */
memset(l_band->precincts,0,l_nb_precinct_size);
l_band->precincts_data_size = l_nb_precinct_size;
}
else if (l_band->precincts_data_size < l_nb_precinct_size) {
opj_tcd_precinct_t * new_precincts = (opj_tcd_precinct_t *) opj_realloc(l_band->precincts,/*3 * */ l_nb_precinct_size);
if (! new_precincts) {
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle band precints\n"); */
fprintf(stderr, "Not enough memory to handle band precints\n");
opj_free(l_band->precincts);
l_band->precincts = NULL;
l_band->precincts_data_size = 0;
return OPJ_FALSE;
}
l_band->precincts = new_precincts;
/*fprintf(stderr, "\t\t\t\tReallocate precincts of a band (opj_tcd_precinct_t): from %d to %d\n",l_band->precincts_data_size, l_nb_precinct_size);*/
memset(((OPJ_BYTE *) l_band->precincts) + l_band->precincts_data_size,0,l_nb_precinct_size - l_band->precincts_data_size);
l_band->precincts_data_size = l_nb_precinct_size;
}
l_current_precinct = l_band->precincts;
for (precno = 0; precno < l_nb_precincts; ++precno) {
OPJ_INT32 tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend;
OPJ_INT32 cbgxstart = tlcbgxstart + (OPJ_INT32)(precno % l_res->pw) * (1 << cbgwidthexpn);
OPJ_INT32 cbgystart = tlcbgystart + (OPJ_INT32)(precno / l_res->pw) * (1 << cbgheightexpn);
OPJ_INT32 cbgxend = cbgxstart + (1 << cbgwidthexpn);
OPJ_INT32 cbgyend = cbgystart + (1 << cbgheightexpn);
/*fprintf(stderr, "\t precno=%d; bandno=%d, resno=%d; compno=%d\n", precno, bandno , resno, compno);*/
/*fprintf(stderr, "\t tlcbgxstart(=%d) + (precno(=%d) percent res->pw(=%d)) * (1 << cbgwidthexpn(=%d)) \n",tlcbgxstart,precno,l_res->pw,cbgwidthexpn);*/
/* precinct size (global) */
/*fprintf(stderr, "\t cbgxstart=%d, l_band->x0 = %d \n",cbgxstart, l_band->x0);*/
l_current_precinct->x0 = opj_int_max(cbgxstart, l_band->x0);
l_current_precinct->y0 = opj_int_max(cbgystart, l_band->y0);
l_current_precinct->x1 = opj_int_min(cbgxend, l_band->x1);
l_current_precinct->y1 = opj_int_min(cbgyend, l_band->y1);
/*fprintf(stderr, "\t prc_x0=%d; prc_y0=%d, prc_x1=%d; prc_y1=%d\n",l_current_precinct->x0, l_current_precinct->y0 ,l_current_precinct->x1, l_current_precinct->y1);*/
tlcblkxstart = opj_int_floordivpow2(l_current_precinct->x0, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
/*fprintf(stderr, "\t tlcblkxstart =%d\n",tlcblkxstart );*/
tlcblkystart = opj_int_floordivpow2(l_current_precinct->y0, (OPJ_INT32)cblkheightexpn) << cblkheightexpn;
/*fprintf(stderr, "\t tlcblkystart =%d\n",tlcblkystart );*/
brcblkxend = opj_int_ceildivpow2(l_current_precinct->x1, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
/*fprintf(stderr, "\t brcblkxend =%d\n",brcblkxend );*/
brcblkyend = opj_int_ceildivpow2(l_current_precinct->y1, (OPJ_INT32)cblkheightexpn) << cblkheightexpn;
/*fprintf(stderr, "\t brcblkyend =%d\n",brcblkyend );*/
l_current_precinct->cw = (OPJ_UINT32)((brcblkxend - tlcblkxstart) >> cblkwidthexpn);
l_current_precinct->ch = (OPJ_UINT32)((brcblkyend - tlcblkystart) >> cblkheightexpn);
l_nb_code_blocks = l_current_precinct->cw * l_current_precinct->ch;
/*fprintf(stderr, "\t\t\t\t precinct_cw = %d x recinct_ch = %d\n",l_current_precinct->cw, l_current_precinct->ch); */
l_nb_code_blocks_size = l_nb_code_blocks * (OPJ_UINT32)sizeof_block;
if (! l_current_precinct->cblks.blocks) {
l_current_precinct->cblks.blocks = opj_malloc(l_nb_code_blocks_size);
if (! l_current_precinct->cblks.blocks ) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\t\t\t\tAllocate cblks of a precinct (opj_tcd_cblk_dec_t): %d\n",l_nb_code_blocks_size);*/
memset(l_current_precinct->cblks.blocks,0,l_nb_code_blocks_size);
l_current_precinct->block_size = l_nb_code_blocks_size;
}
else if (l_nb_code_blocks_size > l_current_precinct->block_size) {
void *new_blocks = opj_realloc(l_current_precinct->cblks.blocks, l_nb_code_blocks_size);
if (! new_blocks) {
opj_free(l_current_precinct->cblks.blocks);
l_current_precinct->cblks.blocks = NULL;
l_current_precinct->block_size = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for current precinct codeblock element\n"); */
fprintf(stderr, "Not enough memory for current precinct codeblock element\n");
return OPJ_FALSE;
}
l_current_precinct->cblks.blocks = new_blocks;
/*fprintf(stderr, "\t\t\t\tReallocate cblks of a precinct (opj_tcd_cblk_dec_t): from %d to %d\n",l_current_precinct->block_size, l_nb_code_blocks_size); */
memset(((OPJ_BYTE *) l_current_precinct->cblks.blocks) + l_current_precinct->block_size
,0
,l_nb_code_blocks_size - l_current_precinct->block_size);
l_current_precinct->block_size = l_nb_code_blocks_size;
}
if (! l_current_precinct->incltree) {
l_current_precinct->incltree = opj_tgt_create(l_current_precinct->cw,
l_current_precinct->ch);
}
else{
l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree,
l_current_precinct->cw,
l_current_precinct->ch);
}
if (! l_current_precinct->incltree) {
fprintf(stderr, "WARNING: No incltree created.\n");
/*return OPJ_FALSE;*/
}
if (! l_current_precinct->imsbtree) {
l_current_precinct->imsbtree = opj_tgt_create(
l_current_precinct->cw,
l_current_precinct->ch);
}
else {
l_current_precinct->imsbtree = opj_tgt_init(
l_current_precinct->imsbtree,
l_current_precinct->cw,
l_current_precinct->ch);
}
if (! l_current_precinct->imsbtree) {
fprintf(stderr, "WARNING: No imsbtree created.\n");
/*return OPJ_FALSE;*/
}
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
OPJ_INT32 cblkxstart = tlcblkxstart + (OPJ_INT32)(cblkno % l_current_precinct->cw) * (1 << cblkwidthexpn);
OPJ_INT32 cblkystart = tlcblkystart + (OPJ_INT32)(cblkno / l_current_precinct->cw) * (1 << cblkheightexpn);
OPJ_INT32 cblkxend = cblkxstart + (1 << cblkwidthexpn);
OPJ_INT32 cblkyend = cblkystart + (1 << cblkheightexpn);
if (isEncoder) {
opj_tcd_cblk_enc_t* l_code_block = l_current_precinct->cblks.enc + cblkno;
if (! opj_tcd_code_block_enc_allocate(l_code_block)) {
return OPJ_FALSE;
}
/* code-block size (global) */
l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
if (! opj_tcd_code_block_enc_allocate_data(l_code_block)) {
return OPJ_FALSE;
}
} else {
opj_tcd_cblk_dec_t* l_code_block = l_current_precinct->cblks.dec + cblkno;
if (! opj_tcd_code_block_dec_allocate(l_code_block)) {
return OPJ_FALSE;
}
/* code-block size (global) */
l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
}
}
++l_current_precinct;
} /* precno */
++l_band;
++l_step_size;
} /* bandno */
++l_res;
--l_level_no;
} /* resno */
++l_tccp;
++l_tilec;
++l_image_comp;
} /* compno */
return OPJ_TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': '[trunk] fixed a buffer overflow in opj_tcd_init_decode_tile
Update issue 431'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void opj_pi_emit_error(opj_pi_iterator_t * pi, const char* msg)
{
(void)pi;
(void)msg;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Revert "[MJ2] Avoid index out of bounds access to pi->include[]"
This reverts commit c277159986c80142180fbe5efb256bbf3bdf3edc.
The commit didn't compile. include_size is not defined in openmj2'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Revert "[MJ2] Avoid index out of bounds access to pi->include[]"
This reverts commit c277159986c80142180fbe5efb256bbf3bdf3edc.
The commit didn't compile. include_size is not defined in openmj2'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static opj_bool pi_next_cprl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Revert "[MJ2] Avoid index out of bounds access to pi->include[]"
This reverts commit c277159986c80142180fbe5efb256bbf3bdf3edc.
The commit didn't compile. include_size is not defined in openmj2'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xsltFormatNumberConversion(xsltDecimalFormatPtr self,
xmlChar *format,
double number,
xmlChar **result)
{
xmlXPathError status = XPATH_EXPRESSION_OK;
xmlBufferPtr buffer;
xmlChar *the_format, *prefix = NULL, *suffix = NULL;
xmlChar *nprefix, *nsuffix = NULL;
xmlChar pchar;
int prefix_length, suffix_length = 0, nprefix_length, nsuffix_length;
double scale;
int j, len;
int self_grouping_len;
xsltFormatNumberInfo format_info;
/*
* delayed_multiplier allows a 'trailing' percent or
* permille to be treated as suffix
*/
int delayed_multiplier = 0;
/* flag to show no -ve format present for -ve number */
char default_sign = 0;
/* flag to show error found, should use default format */
char found_error = 0;
if (xmlStrlen(format) <= 0) {
xsltTransformError(NULL, NULL, NULL,
"xsltFormatNumberConversion : "
"Invalid format (0-length)\n");
}
*result = NULL;
switch (xmlXPathIsInf(number)) {
case -1:
if (self->minusSign == NULL)
*result = xmlStrdup(BAD_CAST "-");
else
*result = xmlStrdup(self->minusSign);
/* no-break on purpose */
case 1:
if ((self == NULL) || (self->infinity == NULL))
*result = xmlStrcat(*result, BAD_CAST "Infinity");
else
*result = xmlStrcat(*result, self->infinity);
return(status);
default:
if (xmlXPathIsNaN(number)) {
if ((self == NULL) || (self->noNumber == NULL))
*result = xmlStrdup(BAD_CAST "NaN");
else
*result = xmlStrdup(self->noNumber);
return(status);
}
}
buffer = xmlBufferCreate();
if (buffer == NULL) {
return XPATH_MEMORY_ERROR;
}
format_info.integer_hash = 0;
format_info.integer_digits = 0;
format_info.frac_digits = 0;
format_info.frac_hash = 0;
format_info.group = -1;
format_info.multiplier = 1;
format_info.add_decimal = FALSE;
format_info.is_multiplier_set = FALSE;
format_info.is_negative_pattern = FALSE;
the_format = format;
/*
* First we process the +ve pattern to get percent / permille,
* as well as main format
*/
prefix = the_format;
prefix_length = xsltFormatNumberPreSuffix(self, &the_format, &format_info);
if (prefix_length < 0) {
found_error = 1;
goto OUTPUT_NUMBER;
}
/*
* Here we process the "number" part of the format. It gets
* a little messy because of the percent/per-mille - if that
* appears at the end, it may be part of the suffix instead
* of part of the number, so the variable delayed_multiplier
* is used to handle it
*/
self_grouping_len = xmlStrlen(self->grouping);
while ((*the_format != 0) &&
(xsltUTF8Charcmp(the_format, self->decimalPoint) != 0) &&
(xsltUTF8Charcmp(the_format, self->patternSeparator) != 0)) {
if (delayed_multiplier != 0) {
format_info.multiplier = delayed_multiplier;
format_info.is_multiplier_set = TRUE;
delayed_multiplier = 0;
}
if (xsltUTF8Charcmp(the_format, self->digit) == 0) {
if (format_info.integer_digits > 0) {
found_error = 1;
goto OUTPUT_NUMBER;
}
format_info.integer_hash++;
if (format_info.group >= 0)
format_info.group++;
} else if (xsltUTF8Charcmp(the_format, self->zeroDigit) == 0) {
format_info.integer_digits++;
if (format_info.group >= 0)
format_info.group++;
} else if ((self_grouping_len > 0) &&
(!xmlStrncmp(the_format, self->grouping, self_grouping_len))) {
/* Reset group count */
format_info.group = 0;
the_format += self_grouping_len;
continue;
} else if (xsltUTF8Charcmp(the_format, self->percent) == 0) {
if (format_info.is_multiplier_set) {
found_error = 1;
goto OUTPUT_NUMBER;
}
delayed_multiplier = 100;
} else if (xsltUTF8Charcmp(the_format, self->permille) == 0) {
if (format_info.is_multiplier_set) {
found_error = 1;
goto OUTPUT_NUMBER;
}
delayed_multiplier = 1000;
} else
break; /* while */
if ((len=xmlUTF8Strsize(the_format, 1)) < 1) {
found_error = 1;
goto OUTPUT_NUMBER;
}
the_format += len;
}
/* We have finished the integer part, now work on fraction */
if ( (*the_format != 0) &&
(xsltUTF8Charcmp(the_format, self->decimalPoint) == 0) ) {
format_info.add_decimal = TRUE;
if ((len = xmlUTF8Strsize(the_format, 1)) < 1) {
found_error = 1;
goto OUTPUT_NUMBER;
}
the_format += len; /* Skip over the decimal */
}
while (*the_format != 0) {
if (xsltUTF8Charcmp(the_format, self->zeroDigit) == 0) {
if (format_info.frac_hash != 0) {
found_error = 1;
goto OUTPUT_NUMBER;
}
format_info.frac_digits++;
} else if (xsltUTF8Charcmp(the_format, self->digit) == 0) {
format_info.frac_hash++;
} else if (xsltUTF8Charcmp(the_format, self->percent) == 0) {
if (format_info.is_multiplier_set) {
found_error = 1;
goto OUTPUT_NUMBER;
}
delayed_multiplier = 100;
if ((len = xmlUTF8Strsize(the_format, 1)) < 1) {
found_error = 1;
goto OUTPUT_NUMBER;
}
the_format += len;
continue; /* while */
} else if (xsltUTF8Charcmp(the_format, self->permille) == 0) {
if (format_info.is_multiplier_set) {
found_error = 1;
goto OUTPUT_NUMBER;
}
delayed_multiplier = 1000;
if ((len = xmlUTF8Strsize(the_format, 1)) < 1) {
found_error = 1;
goto OUTPUT_NUMBER;
}
the_format += len;
continue; /* while */
} else if (xsltUTF8Charcmp(the_format, self->grouping) != 0) {
break; /* while */
}
if ((len = xmlUTF8Strsize(the_format, 1)) < 1) {
found_error = 1;
goto OUTPUT_NUMBER;
}
the_format += len;
if (delayed_multiplier != 0) {
format_info.multiplier = delayed_multiplier;
delayed_multiplier = 0;
format_info.is_multiplier_set = TRUE;
}
}
/*
* If delayed_multiplier is set after processing the
* "number" part, should be in suffix
*/
if (delayed_multiplier != 0) {
the_format -= len;
delayed_multiplier = 0;
}
suffix = the_format;
suffix_length = xsltFormatNumberPreSuffix(self, &the_format, &format_info);
if ( (suffix_length < 0) ||
((*the_format != 0) &&
(xsltUTF8Charcmp(the_format, self->patternSeparator) != 0)) ) {
found_error = 1;
goto OUTPUT_NUMBER;
}
/*
* We have processed the +ve prefix, number part and +ve suffix.
* If the number is -ve, we must substitute the -ve prefix / suffix
*/
if (number < 0) {
/*
* Note that j is the number of UTF8 chars before the separator,
* not the number of bytes! (bug 151975)
*/
j = xmlUTF8Strloc(format, self->patternSeparator);
if (j < 0) {
/* No -ve pattern present, so use default signing */
default_sign = 1;
}
else {
/* Skip over pattern separator (accounting for UTF8) */
the_format = (xmlChar *)xmlUTF8Strpos(format, j + 1);
/*
* Flag changes interpretation of percent/permille
* in -ve pattern
*/
format_info.is_negative_pattern = TRUE;
format_info.is_multiplier_set = FALSE;
/* First do the -ve prefix */
nprefix = the_format;
nprefix_length = xsltFormatNumberPreSuffix(self,
&the_format, &format_info);
if (nprefix_length<0) {
found_error = 1;
goto OUTPUT_NUMBER;
}
while (*the_format != 0) {
if ( (xsltUTF8Charcmp(the_format, (self)->percent) == 0) ||
(xsltUTF8Charcmp(the_format, (self)->permille)== 0) ) {
if (format_info.is_multiplier_set) {
found_error = 1;
goto OUTPUT_NUMBER;
}
format_info.is_multiplier_set = TRUE;
delayed_multiplier = 1;
}
else if (IS_SPECIAL(self, the_format))
delayed_multiplier = 0;
else
break; /* while */
if ((len = xmlUTF8Strsize(the_format, 1)) < 1) {
found_error = 1;
goto OUTPUT_NUMBER;
}
the_format += len;
}
if (delayed_multiplier != 0) {
format_info.is_multiplier_set = FALSE;
the_format -= len;
}
/* Finally do the -ve suffix */
if (*the_format != 0) {
nsuffix = the_format;
nsuffix_length = xsltFormatNumberPreSuffix(self,
&the_format, &format_info);
if (nsuffix_length < 0) {
found_error = 1;
goto OUTPUT_NUMBER;
}
}
else
nsuffix_length = 0;
if (*the_format != 0) {
found_error = 1;
goto OUTPUT_NUMBER;
}
/*
* Here's another Java peculiarity:
* if -ve prefix/suffix == +ve ones, discard & use default
*/
if ((nprefix_length != prefix_length) ||
(nsuffix_length != suffix_length) ||
((nprefix_length > 0) &&
(xmlStrncmp(nprefix, prefix, prefix_length) !=0 )) ||
((nsuffix_length > 0) &&
(xmlStrncmp(nsuffix, suffix, suffix_length) !=0 ))) {
prefix = nprefix;
prefix_length = nprefix_length;
suffix = nsuffix;
suffix_length = nsuffix_length;
} /* else {
default_sign = 1;
}
*/
}
}
OUTPUT_NUMBER:
if (found_error != 0) {
xsltTransformError(NULL, NULL, NULL,
"xsltFormatNumberConversion : "
"error in format string '%s', using default\n", format);
default_sign = (number < 0.0) ? 1 : 0;
prefix_length = suffix_length = 0;
format_info.integer_hash = 0;
format_info.integer_digits = 1;
format_info.frac_digits = 1;
format_info.frac_hash = 4;
format_info.group = -1;
format_info.multiplier = 1;
format_info.add_decimal = TRUE;
}
/* Ready to output our number. First see if "default sign" is required */
if (default_sign != 0)
xmlBufferAdd(buffer, self->minusSign, xmlUTF8Strsize(self->minusSign, 1));
/* Put the prefix into the buffer */
for (j = 0; j < prefix_length; j++) {
if ((pchar = *prefix++) == SYMBOL_QUOTE) {
len = xmlUTF8Strsize(prefix, 1);
xmlBufferAdd(buffer, prefix, len);
prefix += len;
j += len - 1; /* length of symbol less length of quote */
} else
xmlBufferAdd(buffer, &pchar, 1);
}
/* Next do the integer part of the number */
number = fabs(number) * (double)format_info.multiplier;
scale = pow(10.0, (double)(format_info.frac_digits + format_info.frac_hash));
number = floor((scale * number + 0.5)) / scale;
if ((self->grouping != NULL) &&
(self->grouping[0] != 0)) {
len = xmlStrlen(self->grouping);
pchar = xsltGetUTF8Char(self->grouping, &len);
xsltNumberFormatDecimal(buffer, floor(number), self->zeroDigit[0],
format_info.integer_digits,
format_info.group,
pchar, len);
} else
xsltNumberFormatDecimal(buffer, floor(number), self->zeroDigit[0],
format_info.integer_digits,
format_info.group,
',', 1);
/* Special case: java treats '.#' like '.0', '.##' like '.0#', etc. */
if ((format_info.integer_digits + format_info.integer_hash +
format_info.frac_digits == 0) && (format_info.frac_hash > 0)) {
++format_info.frac_digits;
--format_info.frac_hash;
}
/* Add leading zero, if required */
if ((floor(number) == 0) &&
(format_info.integer_digits + format_info.frac_digits == 0)) {
xmlBufferAdd(buffer, self->zeroDigit, xmlUTF8Strsize(self->zeroDigit, 1));
}
/* Next the fractional part, if required */
if (format_info.frac_digits + format_info.frac_hash == 0) {
if (format_info.add_decimal)
xmlBufferAdd(buffer, self->decimalPoint,
xmlUTF8Strsize(self->decimalPoint, 1));
}
else {
number -= floor(number);
if ((number != 0) || (format_info.frac_digits != 0)) {
xmlBufferAdd(buffer, self->decimalPoint,
xmlUTF8Strsize(self->decimalPoint, 1));
number = floor(scale * number + 0.5);
for (j = format_info.frac_hash; j > 0; j--) {
if (fmod(number, 10.0) >= 1.0)
break; /* for */
number /= 10.0;
}
xsltNumberFormatDecimal(buffer, floor(number), self->zeroDigit[0],
format_info.frac_digits + j,
0, 0, 0);
}
}
/* Put the suffix into the buffer */
for (j = 0; j < suffix_length; j++) {
if ((pchar = *suffix++) == SYMBOL_QUOTE) {
len = xmlUTF8Strsize(suffix, 1);
xmlBufferAdd(buffer, suffix, len);
suffix += len;
j += len - 1; /* length of symbol less length of escape */
} else
xmlBufferAdd(buffer, &pchar, 1);
}
*result = xmlStrdup(xmlBufferContent(buffer));
xmlBufferFree(buffer);
return status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-843'], 'message': 'Fix uninitialized read with UTF-8 grouping chars
The character type in xsltFormatNumberConversion was too narrow and
an invalid character/length combination could be passed to
xsltNumberFormatDecimal, resulting in an uninitialized read.
Found by OSS-Fuzz.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: g_keyfile_settings_backend_keyfile_write (GKeyfileSettingsBackend *kfsb)
{
gchar *contents;
gsize length;
contents = g_key_file_to_data (kfsb->keyfile, &length, NULL);
g_file_replace_contents (kfsb->file, contents, length, NULL, FALSE,
G_FILE_CREATE_REPLACE_DESTINATION,
NULL, NULL, NULL);
compute_checksum (kfsb->digest, contents, length);
g_free (contents);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-732'], 'message': 'keyfile settings: Use tighter permissions
When creating directories, create them with 700 permissions,
instead of 777.
Closes: #1658'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: compile_length_bag_node(BagNode* node, regex_t* reg)
{
int len;
int tlen;
if (node->type == BAG_OPTION)
return compile_length_option_node(node, reg);
if (NODE_BAG_BODY(node)) {
tlen = compile_length_tree(NODE_BAG_BODY(node), reg);
if (tlen < 0) return tlen;
}
else
tlen = 0;
switch (node->type) {
case BAG_MEMORY:
#ifdef USE_CALL
if (node->m.regnum == 0 && NODE_IS_CALLED(node)) {
len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN;
return len;
}
if (NODE_IS_CALLED(node)) {
len = SIZE_OP_MEMORY_START_PUSH + tlen
+ SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN;
if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum))
len += (NODE_IS_RECURSION(node)
? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH);
else
len += (NODE_IS_RECURSION(node)
? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END);
}
else if (NODE_IS_RECURSION(node)) {
len = SIZE_OP_MEMORY_START_PUSH;
len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)
? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC);
}
else
#endif
{
if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum))
len = SIZE_OP_MEMORY_START_PUSH;
else
len = SIZE_OP_MEMORY_START;
len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)
? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END);
}
break;
case BAG_STOP_BACKTRACK:
if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) {
int v;
QuantNode* qn;
qn = QUANT_(NODE_BAG_BODY(node));
tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
v = onig_positive_int_multiply(qn->lower, tlen);
if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP;
}
else {
len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END;
}
break;
case BAG_IF_ELSE:
{
Node* cond = NODE_BAG_BODY(node);
Node* Then = node->te.Then;
Node* Else = node->te.Else;
len = compile_length_tree(cond, reg);
if (len < 0) return len;
len += SIZE_OP_PUSH;
len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END;
if (IS_NOT_NULL(Then)) {
tlen = compile_length_tree(Then, reg);
if (tlen < 0) return tlen;
len += tlen;
}
if (IS_NOT_NULL(Else)) {
len += SIZE_OP_JUMP;
tlen = compile_length_tree(Else, reg);
if (tlen < 0) return tlen;
len += tlen;
}
}
break;
case BAG_OPTION:
/* never come here, but set for escape warning */
len = 0;
break;
}
return len;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'Fix CVE-2019-13225: problem in converting if-then-else pattern to bytecode.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int MemIo::seek(int64 offset, Position pos )
{
int64 newIdx = 0;
switch (pos) {
case BasicIo::cur:
newIdx = p_->idx_ + offset;
break;
case BasicIo::beg:
newIdx = offset;
break;
case BasicIo::end:
newIdx = p_->size_ + offset;
break;
}
if (newIdx < 0)
return 1;
p_->idx_ = static_cast<long>(newIdx); //not very sure about this. need more test!! - note by Shawn [email protected] //TODO
p_->eof_ = false;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Add bounds check to MemIo::seek(). (#944)
- Regression test for missing bounds check in MemIo::seek()
- Add bounds check to MemIo::seek(), this fixes CVE-2019-13504'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int MemIo::seek( int64_t offset, Position pos )
{
uint64_t newIdx = 0;
switch (pos) {
case BasicIo::cur: newIdx = p_->idx_ + offset; break;
case BasicIo::beg: newIdx = offset; break;
case BasicIo::end: newIdx = p_->size_ + offset; break;
}
p_->idx_ = static_cast<long>(newIdx); //not very sure about this. need more test!! - note by Shawn [email protected] //TODO
p_->eof_ = false;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Add bounds check to MemIo::seek(). (#944)
- Regression test for missing bounds check in MemIo::seek()
- Add bounds check to MemIo::seek(), this fixes CVE-2019-13504
(cherry picked from commit bd0afe0390439b2c424d881c8c6eb0c5624e31d9)
Additional fixes for 0.27:
- Add fix for the linux variant of MemIo::seek
- Change type of variable from unsigned to signed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,
const int argc,const char **argv,Image **images,ExceptionInfo *exception)
{
const char
*option;
ImageInfo
*mogrify_info;
MagickStatusType
status;
PixelInterpolateMethod
interpolate_method;
QuantizeInfo
*quantize_info;
register ssize_t
i;
ssize_t
count,
index;
/*
Apply options to the image list.
*/
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(images != (Image **) NULL);
assert((*images)->previous == (Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
if ((argc <= 0) || (*argv == (char *) NULL))
return(MagickTrue);
interpolate_method=UndefinedInterpolatePixel;
mogrify_info=CloneImageInfo(image_info);
quantize_info=AcquireQuantizeInfo(mogrify_info);
status=MagickTrue;
for (i=0; i < (ssize_t) argc; i++)
{
if (*images == (Image *) NULL)
break;
option=argv[i];
if (IsCommandOption(option) == MagickFalse)
continue;
count=ParseCommandOption(MagickCommandOptions,MagickFalse,option);
count=MagickMax(count,0L);
if ((i+count) >= (ssize_t) argc)
break;
status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception);
switch (*(option+1))
{
case 'a':
{
if (LocaleCompare("affinity",option+1) == 0)
{
(void) SyncImagesSettings(mogrify_info,*images,exception);
if (*option == '+')
{
(void) RemapImages(quantize_info,*images,(Image *) NULL,
exception);
break;
}
i++;
break;
}
if (LocaleCompare("append",option+1) == 0)
{
Image
*append_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
append_image=AppendImages(*images,*option == '-' ? MagickTrue :
MagickFalse,exception);
if (append_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=append_image;
break;
}
if (LocaleCompare("average",option+1) == 0)
{
Image
*average_image;
/*
Average an image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
average_image=EvaluateImages(*images,MeanEvaluateOperator,
exception);
if (average_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=average_image;
break;
}
break;
}
case 'c':
{
if (LocaleCompare("channel-fx",option+1) == 0)
{
Image
*channel_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
channel_image=ChannelFxImage(*images,argv[i+1],exception);
if (channel_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=channel_image;
break;
}
if (LocaleCompare("clut",option+1) == 0)
{
Image
*clut_image,
*image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
image=RemoveFirstImageFromList(images);
clut_image=RemoveFirstImageFromList(images);
if (clut_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) ClutImage(image,clut_image,interpolate_method,exception);
clut_image=DestroyImage(clut_image);
*images=DestroyImageList(*images);
*images=image;
break;
}
if (LocaleCompare("coalesce",option+1) == 0)
{
Image
*coalesce_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
coalesce_image=CoalesceImages(*images,exception);
if (coalesce_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=coalesce_image;
break;
}
if (LocaleCompare("combine",option+1) == 0)
{
ColorspaceType
colorspace;
Image
*combine_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
colorspace=(*images)->colorspace;
if ((*images)->number_channels < GetImageListLength(*images))
colorspace=sRGBColorspace;
if (*option == '+')
colorspace=(ColorspaceType) ParseCommandOption(
MagickColorspaceOptions,MagickFalse,argv[i+1]);
combine_image=CombineImages(*images,colorspace,exception);
if (combine_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=combine_image;
break;
}
if (LocaleCompare("compare",option+1) == 0)
{
double
distortion;
Image
*difference_image,
*image,
*reconstruct_image;
MetricType
metric;
/*
Mathematically and visually annotate the difference between an
image and its reconstruction.
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
image=RemoveFirstImageFromList(images);
reconstruct_image=RemoveFirstImageFromList(images);
if (reconstruct_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
metric=UndefinedErrorMetric;
option=GetImageOption(mogrify_info,"metric");
if (option != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,option);
difference_image=CompareImages(image,reconstruct_image,metric,
&distortion,exception);
if (difference_image == (Image *) NULL)
break;
reconstruct_image=DestroyImage(reconstruct_image);
image=DestroyImage(image);
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=difference_image;
break;
}
if (LocaleCompare("complex",option+1) == 0)
{
ComplexOperator
op;
Image
*complex_images;
(void) SyncImageSettings(mogrify_info,*images,exception);
op=(ComplexOperator) ParseCommandOption(MagickComplexOptions,
MagickFalse,argv[i+1]);
complex_images=ComplexImages(*images,op,exception);
if (complex_images == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=complex_images;
break;
}
if (LocaleCompare("composite",option+1) == 0)
{
CompositeOperator
compose;
const char*
value;
MagickBooleanType
clip_to_self;
Image
*mask_image,
*new_images,
*source_image;
RectangleInfo
geometry;
/* Compose value from "-compose" option only */
(void) SyncImageSettings(mogrify_info,*images,exception);
value=GetImageOption(mogrify_info,"compose");
if (value == (const char *) NULL)
compose=OverCompositeOp; /* use Over not source_image->compose */
else
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,value);
/* Get "clip-to-self" expert setting (false is normal) */
clip_to_self=GetCompositeClipToSelf(compose);
value=GetImageOption(mogrify_info,"compose:clip-to-self");
if (value != (const char *) NULL)
clip_to_self=IsStringTrue(value);
value=GetImageOption(mogrify_info,"compose:outside-overlay");
if (value != (const char *) NULL)
clip_to_self=IsStringFalse(value); /* deprecated */
new_images=RemoveFirstImageFromList(images);
source_image=RemoveFirstImageFromList(images);
if (source_image == (Image *) NULL)
break; /* FUTURE - produce Exception, rather than silent fail */
/* FUTURE: this should not be here! - should be part of -geometry */
if (source_image->geometry != (char *) NULL)
{
RectangleInfo
resize_geometry;
(void) ParseRegionGeometry(source_image,source_image->geometry,
&resize_geometry,exception);
if ((source_image->columns != resize_geometry.width) ||
(source_image->rows != resize_geometry.height))
{
Image
*resize_image;
resize_image=ResizeImage(source_image,resize_geometry.width,
resize_geometry.height,source_image->filter,exception);
if (resize_image != (Image *) NULL)
{
source_image=DestroyImage(source_image);
source_image=resize_image;
}
}
}
SetGeometry(source_image,&geometry);
(void) ParseAbsoluteGeometry(source_image->geometry,&geometry);
GravityAdjustGeometry(new_images->columns,new_images->rows,
new_images->gravity,&geometry);
mask_image=RemoveFirstImageFromList(images);
if (mask_image == (Image *) NULL)
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,exception);
else
{
if ((compose == DisplaceCompositeOp) ||
(compose == DistortCompositeOp))
{
status&=CompositeImage(source_image,mask_image,
CopyGreenCompositeOp,MagickTrue,0,0,exception);
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,exception);
}
else
{
Image
*clone_image;
clone_image=CloneImage(new_images,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
break;
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,exception);
status&=CompositeImage(new_images,mask_image,
CopyAlphaCompositeOp,MagickTrue,0,0,exception);
status&=CompositeImage(clone_image,new_images,
OverCompositeOp,clip_to_self,0,0,exception);
new_images=DestroyImageList(new_images);
new_images=clone_image;
}
mask_image=DestroyImage(mask_image);
}
source_image=DestroyImage(source_image);
*images=DestroyImageList(*images);
*images=new_images;
break;
}
if (LocaleCompare("copy",option+1) == 0)
{
Image
*source_image;
OffsetInfo
offset;
RectangleInfo
geometry;
/*
Copy image pixels.
*/
(void) SyncImageSettings(mogrify_info,*images,exception);
(void) ParsePageGeometry(*images,argv[i+2],&geometry,exception);
offset.x=geometry.x;
offset.y=geometry.y;
source_image=(*images);
if (source_image->next != (Image *) NULL)
source_image=source_image->next;
(void) ParsePageGeometry(source_image,argv[i+1],&geometry,
exception);
status=CopyImagePixels(*images,source_image,&geometry,&offset,
exception);
break;
}
break;
}
case 'd':
{
if (LocaleCompare("deconstruct",option+1) == 0)
{
Image
*deconstruct_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer,
exception);
if (deconstruct_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=deconstruct_image;
break;
}
if (LocaleCompare("delete",option+1) == 0)
{
if (*option == '+')
DeleteImages(images,"-1",exception);
else
DeleteImages(images,argv[i+1],exception);
break;
}
if (LocaleCompare("dither",option+1) == 0)
{
if (*option == '+')
{
quantize_info->dither_method=NoDitherMethod;
break;
}
quantize_info->dither_method=(DitherMethod) ParseCommandOption(
MagickDitherOptions,MagickFalse,argv[i+1]);
break;
}
if (LocaleCompare("duplicate",option+1) == 0)
{
Image
*duplicate_images;
if (*option == '+')
duplicate_images=DuplicateImages(*images,1,"-1",exception);
else
{
const char
*p;
size_t
number_duplicates;
number_duplicates=(size_t) StringToLong(argv[i+1]);
p=strchr(argv[i+1],',');
if (p == (const char *) NULL)
duplicate_images=DuplicateImages(*images,number_duplicates,
"-1",exception);
else
duplicate_images=DuplicateImages(*images,number_duplicates,p,
exception);
}
AppendImageToList(images, duplicate_images);
(void) SyncImagesSettings(mogrify_info,*images,exception);
break;
}
break;
}
case 'e':
{
if (LocaleCompare("evaluate-sequence",option+1) == 0)
{
Image
*evaluate_image;
MagickEvaluateOperator
op;
(void) SyncImageSettings(mogrify_info,*images,exception);
op=(MagickEvaluateOperator) ParseCommandOption(
MagickEvaluateOptions,MagickFalse,argv[i+1]);
evaluate_image=EvaluateImages(*images,op,exception);
if (evaluate_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=evaluate_image;
break;
}
break;
}
case 'f':
{
if (LocaleCompare("fft",option+1) == 0)
{
Image
*fourier_image;
/*
Implements the discrete Fourier transform (DFT).
*/
(void) SyncImageSettings(mogrify_info,*images,exception);
fourier_image=ForwardFourierTransformImage(*images,*option == '-' ?
MagickTrue : MagickFalse,exception);
if (fourier_image == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=fourier_image;
break;
}
if (LocaleCompare("flatten",option+1) == 0)
{
Image
*flatten_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
flatten_image=MergeImageLayers(*images,FlattenLayer,exception);
if (flatten_image == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=flatten_image;
break;
}
if (LocaleCompare("fx",option+1) == 0)
{
Image
*fx_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
fx_image=FxImage(*images,argv[i+1],exception);
if (fx_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=fx_image;
break;
}
break;
}
case 'h':
{
if (LocaleCompare("hald-clut",option+1) == 0)
{
Image
*hald_image,
*image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
image=RemoveFirstImageFromList(images);
hald_image=RemoveFirstImageFromList(images);
if (hald_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) HaldClutImage(image,hald_image,exception);
hald_image=DestroyImage(hald_image);
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=image;
break;
}
break;
}
case 'i':
{
if (LocaleCompare("ift",option+1) == 0)
{
Image
*fourier_image,
*magnitude_image,
*phase_image;
/*
Implements the inverse fourier discrete Fourier transform (DFT).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
magnitude_image=RemoveFirstImageFromList(images);
phase_image=RemoveFirstImageFromList(images);
if (phase_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
fourier_image=InverseFourierTransformImage(magnitude_image,
phase_image,*option == '-' ? MagickTrue : MagickFalse,exception);
if (fourier_image == (Image *) NULL)
break;
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=fourier_image;
break;
}
if (LocaleCompare("insert",option+1) == 0)
{
Image
*p,
*q;
index=0;
if (*option != '+')
index=(ssize_t) StringToLong(argv[i+1]);
p=RemoveLastImageFromList(images);
if (p == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",argv[i+1]);
status=MagickFalse;
break;
}
q=p;
if (index == 0)
PrependImageToList(images,q);
else
if (index == (ssize_t) GetImageListLength(*images))
AppendImageToList(images,q);
else
{
q=GetImageFromList(*images,index-1);
if (q == (Image *) NULL)
{
p=DestroyImage(p);
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",argv[i+1]);
status=MagickFalse;
break;
}
InsertImageInList(&q,p);
}
*images=GetFirstImageInList(q);
break;
}
if (LocaleCompare("interpolate",option+1) == 0)
{
interpolate_method=(PixelInterpolateMethod) ParseCommandOption(
MagickInterpolateOptions,MagickFalse,argv[i+1]);
break;
}
break;
}
case 'l':
{
if (LocaleCompare("layers",option+1) == 0)
{
Image
*layers;
LayerMethod
method;
(void) SyncImagesSettings(mogrify_info,*images,exception);
layers=(Image *) NULL;
method=(LayerMethod) ParseCommandOption(MagickLayerOptions,
MagickFalse,argv[i+1]);
switch (method)
{
case CoalesceLayer:
{
layers=CoalesceImages(*images,exception);
break;
}
case CompareAnyLayer:
case CompareClearLayer:
case CompareOverlayLayer:
default:
{
layers=CompareImagesLayers(*images,method,exception);
break;
}
case MergeLayer:
case FlattenLayer:
case MosaicLayer:
case TrimBoundsLayer:
{
layers=MergeImageLayers(*images,method,exception);
break;
}
case DisposeLayer:
{
layers=DisposeImages(*images,exception);
break;
}
case OptimizeImageLayer:
{
layers=OptimizeImageLayers(*images,exception);
break;
}
case OptimizePlusLayer:
{
layers=OptimizePlusImageLayers(*images,exception);
break;
}
case OptimizeTransLayer:
{
OptimizeImageTransparency(*images,exception);
break;
}
case RemoveDupsLayer:
{
RemoveDuplicateLayers(images,exception);
break;
}
case RemoveZeroLayer:
{
RemoveZeroDelayLayers(images,exception);
break;
}
case OptimizeLayer:
{
/*
General Purpose, GIF Animation Optimizer.
*/
layers=CoalesceImages(*images,exception);
if (layers == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=layers;
layers=OptimizeImageLayers(*images,exception);
if (layers == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=layers;
layers=(Image *) NULL;
OptimizeImageTransparency(*images,exception);
(void) RemapImages(quantize_info,*images,(Image *) NULL,
exception);
break;
}
case CompositeLayer:
{
CompositeOperator
compose;
Image
*source;
RectangleInfo
geometry;
/*
Split image sequence at the first 'NULL:' image.
*/
source=(*images);
while (source != (Image *) NULL)
{
source=GetNextImageInList(source);
if ((source != (Image *) NULL) &&
(LocaleCompare(source->magick,"NULL") == 0))
break;
}
if (source != (Image *) NULL)
{
if ((GetPreviousImageInList(source) == (Image *) NULL) ||
(GetNextImageInList(source) == (Image *) NULL))
source=(Image *) NULL;
else
{
/*
Separate the two lists, junk the null: image.
*/
source=SplitImageList(source->previous);
DeleteImageFromList(&source);
}
}
if (source == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"MissingNullSeparator","layers Composite");
status=MagickFalse;
break;
}
/*
Adjust offset with gravity and virtual canvas.
*/
SetGeometry(*images,&geometry);
(void) ParseAbsoluteGeometry((*images)->geometry,&geometry);
geometry.width=source->page.width != 0 ?
source->page.width : source->columns;
geometry.height=source->page.height != 0 ?
source->page.height : source->rows;
GravityAdjustGeometry((*images)->page.width != 0 ?
(*images)->page.width : (*images)->columns,
(*images)->page.height != 0 ? (*images)->page.height :
(*images)->rows,(*images)->gravity,&geometry);
compose=OverCompositeOp;
option=GetImageOption(mogrify_info,"compose");
if (option != (const char *) NULL)
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,option);
CompositeLayers(*images,compose,source,geometry.x,geometry.y,
exception);
source=DestroyImageList(source);
break;
}
}
if (layers == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=layers;
break;
}
break;
}
case 'm':
{
if (LocaleCompare("map",option+1) == 0)
{
(void) SyncImagesSettings(mogrify_info,*images,exception);
if (*option == '+')
{
(void) RemapImages(quantize_info,*images,(Image *) NULL,
exception);
break;
}
i++;
break;
}
if (LocaleCompare("maximum",option+1) == 0)
{
Image
*maximum_image;
/*
Maximum image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception);
if (maximum_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=maximum_image;
break;
}
if (LocaleCompare("minimum",option+1) == 0)
{
Image
*minimum_image;
/*
Minimum image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception);
if (minimum_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=minimum_image;
break;
}
if (LocaleCompare("morph",option+1) == 0)
{
Image
*morph_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]),
exception);
if (morph_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=morph_image;
break;
}
if (LocaleCompare("mosaic",option+1) == 0)
{
Image
*mosaic_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
mosaic_image=MergeImageLayers(*images,MosaicLayer,exception);
if (mosaic_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=mosaic_image;
break;
}
break;
}
case 'p':
{
if (LocaleCompare("poly",option+1) == 0)
{
char
*args,
token[MagickPathExtent];
const char
*p;
double
*arguments;
Image
*polynomial_image;
register ssize_t
x;
size_t
number_arguments;
/*
Polynomial image.
*/
(void) SyncImageSettings(mogrify_info,*images,exception);
args=InterpretImageProperties(mogrify_info,*images,argv[i+1],
exception);
if (args == (char *) NULL)
break;
p=(char *) args;
for (x=0; *p != '\0'; x++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
}
number_arguments=(size_t) x;
arguments=(double *) AcquireQuantumMemory(number_arguments,
sizeof(*arguments));
if (arguments == (double *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,
"MemoryAllocationFailed",(*images)->filename);
(void) memset(arguments,0,number_arguments*
sizeof(*arguments));
p=(char *) args;
for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
arguments[x]=StringToDouble(token,(char **) NULL);
}
args=DestroyString(args);
polynomial_image=PolynomialImage(*images,number_arguments >> 1,
arguments,exception);
arguments=(double *) RelinquishMagickMemory(arguments);
if (polynomial_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=polynomial_image;
}
if (LocaleCompare("print",option+1) == 0)
{
char
*string;
(void) SyncImagesSettings(mogrify_info,*images,exception);
string=InterpretImageProperties(mogrify_info,*images,argv[i+1],
exception);
if (string == (char *) NULL)
break;
(void) FormatLocaleFile(stdout,"%s",string);
string=DestroyString(string);
}
if (LocaleCompare("process",option+1) == 0)
{
char
**arguments;
int
j,
number_arguments;
(void) SyncImagesSettings(mogrify_info,*images,exception);
arguments=StringToArgv(argv[i+1],&number_arguments);
if (arguments == (char **) NULL)
break;
if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL))
{
char
breaker,
quote,
*token;
const char
*argument;
int
next,
token_status;
size_t
length;
TokenInfo
*token_info;
/*
Support old style syntax, filter="-option arg".
*/
length=strlen(argv[i+1]);
token=(char *) NULL;
if (~length >= (MagickPathExtent-1))
token=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*token));
if (token == (char *) NULL)
break;
next=0;
argument=argv[i+1];
token_info=AcquireTokenInfo();
token_status=Tokenizer(token_info,0,token,length,argument,"",
"=","\"",'\0',&breaker,&next,"e);
token_info=DestroyTokenInfo(token_info);
if (token_status == 0)
{
const char
*arg;
arg=(&(argument[next]));
(void) InvokeDynamicImageFilter(token,&(*images),1,&arg,
exception);
}
token=DestroyString(token);
break;
}
(void) SubstituteString(&arguments[1],"-","");
(void) InvokeDynamicImageFilter(arguments[1],&(*images),
number_arguments-2,(const char **) arguments+2,exception);
for (j=0; j < number_arguments; j++)
arguments[j]=DestroyString(arguments[j]);
arguments=(char **) RelinquishMagickMemory(arguments);
break;
}
break;
}
case 'r':
{
if (LocaleCompare("reverse",option+1) == 0)
{
ReverseImageList(images);
break;
}
break;
}
case 's':
{
if (LocaleCompare("smush",option+1) == 0)
{
Image
*smush_image;
ssize_t
offset;
(void) SyncImagesSettings(mogrify_info,*images,exception);
offset=(ssize_t) StringToLong(argv[i+1]);
smush_image=SmushImages(*images,*option == '-' ? MagickTrue :
MagickFalse,offset,exception);
if (smush_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=smush_image;
break;
}
if (LocaleCompare("swap",option+1) == 0)
{
Image
*p,
*q,
*u,
*v;
ssize_t
swap_index;
index=(-1);
swap_index=(-2);
if (*option != '+')
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
swap_index=(-1);
flags=ParseGeometry(argv[i+1],&geometry_info);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) != 0)
swap_index=(ssize_t) geometry_info.sigma;
}
p=GetImageFromList(*images,index);
q=GetImageFromList(*images,swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",(*images)->filename);
status=MagickFalse;
break;
}
if (p == q)
break;
u=CloneImage(p,0,0,MagickTrue,exception);
if (u == (Image *) NULL)
break;
v=CloneImage(q,0,0,MagickTrue,exception);
if (v == (Image *) NULL)
{
u=DestroyImage(u);
break;
}
ReplaceImageInList(&p,v);
ReplaceImageInList(&q,u);
*images=GetFirstImageInList(q);
break;
}
break;
}
case 'w':
{
if (LocaleCompare("write",option+1) == 0)
{
char
key[MagickPathExtent];
Image
*write_images;
ImageInfo
*write_info;
(void) SyncImagesSettings(mogrify_info,*images,exception);
(void) FormatLocaleString(key,MagickPathExtent,"cache:%s",
argv[i+1]);
(void) DeleteImageRegistry(key);
write_images=(*images);
if (*option == '+')
write_images=CloneImageList(*images,exception);
write_info=CloneImageInfo(mogrify_info);
status&=WriteImages(write_info,write_images,argv[i+1],exception);
write_info=DestroyImageInfo(write_info);
if (*option == '+')
write_images=DestroyImageList(write_images);
break;
}
break;
}
default:
break;
}
i+=count;
}
quantize_info=DestroyQuantizeInfo(quantize_info);
mogrify_info=DestroyImageInfo(mogrify_info);
status&=MogrifyImageInfo(image_info,argc,argv,exception);
return(status != 0 ? MagickTrue : MagickFalse);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1623'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,
const int argc,const char **argv,Image **images,ExceptionInfo *exception)
{
ChannelType
channel;
const char
*option;
ImageInfo
*mogrify_info;
MagickStatusType
status;
QuantizeInfo
*quantize_info;
register ssize_t
i;
ssize_t
count,
index;
/*
Apply options to the image list.
*/
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(images != (Image **) NULL);
assert((*images)->previous == (Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
if ((argc <= 0) || (*argv == (char *) NULL))
return(MagickTrue);
mogrify_info=CloneImageInfo(image_info);
quantize_info=AcquireQuantizeInfo(mogrify_info);
channel=mogrify_info->channel;
status=MagickTrue;
for (i=0; i < (ssize_t) argc; i++)
{
if (*images == (Image *) NULL)
break;
option=argv[i];
if (IsCommandOption(option) == MagickFalse)
continue;
count=ParseCommandOption(MagickCommandOptions,MagickFalse,option);
count=MagickMax(count,0L);
if ((i+count) >= (ssize_t) argc)
break;
status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception);
switch (*(option+1))
{
case 'a':
{
if (LocaleCompare("affinity",option+1) == 0)
{
(void) SyncImagesSettings(mogrify_info,*images);
if (*option == '+')
{
(void) RemapImages(quantize_info,*images,(Image *) NULL);
InheritException(exception,&(*images)->exception);
break;
}
i++;
break;
}
if (LocaleCompare("append",option+1) == 0)
{
Image
*append_image;
(void) SyncImagesSettings(mogrify_info,*images);
append_image=AppendImages(*images,*option == '-' ? MagickTrue :
MagickFalse,exception);
if (append_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=append_image;
break;
}
if (LocaleCompare("average",option+1) == 0)
{
Image
*average_image;
/*
Average an image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images);
average_image=EvaluateImages(*images,MeanEvaluateOperator,
exception);
if (average_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=average_image;
break;
}
break;
}
case 'c':
{
if (LocaleCompare("channel",option+1) == 0)
{
if (*option == '+')
{
channel=DefaultChannels;
break;
}
channel=(ChannelType) ParseChannelOption(argv[i+1]);
break;
}
if (LocaleCompare("clut",option+1) == 0)
{
Image
*clut_image,
*image;
(void) SyncImagesSettings(mogrify_info,*images);
image=RemoveFirstImageFromList(images);
clut_image=RemoveFirstImageFromList(images);
if (clut_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) ClutImageChannel(image,channel,clut_image);
clut_image=DestroyImage(clut_image);
InheritException(exception,&image->exception);
*images=DestroyImageList(*images);
*images=image;
break;
}
if (LocaleCompare("coalesce",option+1) == 0)
{
Image
*coalesce_image;
(void) SyncImagesSettings(mogrify_info,*images);
coalesce_image=CoalesceImages(*images,exception);
if (coalesce_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=coalesce_image;
break;
}
if (LocaleCompare("combine",option+1) == 0)
{
Image
*combine_image;
(void) SyncImagesSettings(mogrify_info,*images);
combine_image=CombineImages(*images,channel,exception);
if (combine_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=combine_image;
break;
}
if (LocaleCompare("compare",option+1) == 0)
{
const char
*option;
double
distortion;
Image
*difference_image,
*image,
*reconstruct_image;
MetricType
metric;
/*
Mathematically and visually annotate the difference between an
image and its reconstruction.
*/
(void) SyncImagesSettings(mogrify_info,*images);
image=RemoveFirstImageFromList(images);
reconstruct_image=RemoveFirstImageFromList(images);
if (reconstruct_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
metric=UndefinedMetric;
option=GetImageOption(image_info,"metric");
if (option != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,option);
difference_image=CompareImageChannels(image,reconstruct_image,
channel,metric,&distortion,exception);
if (difference_image == (Image *) NULL)
break;
reconstruct_image=DestroyImage(reconstruct_image);
image=DestroyImage(image);
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=difference_image;
break;
}
if (LocaleCompare("complex",option+1) == 0)
{
ComplexOperator
op;
Image
*complex_images;
(void) SyncImageSettings(mogrify_info,*images);
op=(ComplexOperator) ParseCommandOption(MagickComplexOptions,
MagickFalse,argv[i+1]);
complex_images=ComplexImages(*images,op,exception);
if (complex_images == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=complex_images;
break;
}
if (LocaleCompare("composite",option+1) == 0)
{
Image
*mask_image,
*composite_image,
*image;
RectangleInfo
geometry;
(void) SyncImagesSettings(mogrify_info,*images);
image=RemoveFirstImageFromList(images);
composite_image=RemoveFirstImageFromList(images);
if (composite_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) TransformImage(&composite_image,(char *) NULL,
composite_image->geometry);
SetGeometry(composite_image,&geometry);
(void) ParseAbsoluteGeometry(composite_image->geometry,&geometry);
GravityAdjustGeometry(image->columns,image->rows,image->gravity,
&geometry);
mask_image=RemoveFirstImageFromList(images);
if (mask_image != (Image *) NULL)
{
if ((image->compose == DisplaceCompositeOp) ||
(image->compose == DistortCompositeOp))
{
/*
Merge Y displacement into X displacement image.
*/
(void) CompositeImage(composite_image,CopyGreenCompositeOp,
mask_image,0,0);
mask_image=DestroyImage(mask_image);
}
else
{
/*
Set a blending mask for the composition.
*/
if (image->mask != (Image *) NULL)
image->mask=DestroyImage(image->mask);
image->mask=mask_image;
(void) NegateImage(image->mask,MagickFalse);
}
}
(void) CompositeImageChannel(image,channel,image->compose,
composite_image,geometry.x,geometry.y);
if (mask_image != (Image *) NULL)
{
image->mask=DestroyImage(image->mask);
mask_image=image->mask;
}
composite_image=DestroyImage(composite_image);
InheritException(exception,&image->exception);
*images=DestroyImageList(*images);
*images=image;
break;
}
if (LocaleCompare("copy",option+1) == 0)
{
Image
*source_image;
OffsetInfo
offset;
RectangleInfo
geometry;
/*
Copy image pixels.
*/
(void) SyncImageSettings(mogrify_info,*images);
(void) ParsePageGeometry(*images,argv[i+2],&geometry,exception);
offset.x=geometry.x;
offset.y=geometry.y;
source_image=(*images);
if (source_image->next != (Image *) NULL)
source_image=source_image->next;
(void) ParsePageGeometry(source_image,argv[i+1],&geometry,
exception);
status=CopyImagePixels(*images,source_image,&geometry,&offset,
exception);
break;
}
break;
}
case 'd':
{
if (LocaleCompare("deconstruct",option+1) == 0)
{
Image
*deconstruct_image;
(void) SyncImagesSettings(mogrify_info,*images);
deconstruct_image=DeconstructImages(*images,exception);
if (deconstruct_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=deconstruct_image;
break;
}
if (LocaleCompare("delete",option+1) == 0)
{
if (*option == '+')
DeleteImages(images,"-1",exception);
else
DeleteImages(images,argv[i+1],exception);
break;
}
if (LocaleCompare("dither",option+1) == 0)
{
if (*option == '+')
{
quantize_info->dither=MagickFalse;
break;
}
quantize_info->dither=MagickTrue;
quantize_info->dither_method=(DitherMethod) ParseCommandOption(
MagickDitherOptions,MagickFalse,argv[i+1]);
break;
}
if (LocaleCompare("duplicate",option+1) == 0)
{
Image
*duplicate_images;
if (*option == '+')
duplicate_images=DuplicateImages(*images,1,"-1",exception);
else
{
const char
*p;
size_t
number_duplicates;
number_duplicates=(size_t) StringToLong(argv[i+1]);
p=strchr(argv[i+1],',');
if (p == (const char *) NULL)
duplicate_images=DuplicateImages(*images,number_duplicates,
"-1",exception);
else
duplicate_images=DuplicateImages(*images,number_duplicates,p,
exception);
}
AppendImageToList(images, duplicate_images);
(void) SyncImagesSettings(mogrify_info,*images);
break;
}
break;
}
case 'e':
{
if (LocaleCompare("evaluate-sequence",option+1) == 0)
{
Image
*evaluate_image;
MagickEvaluateOperator
op;
(void) SyncImageSettings(mogrify_info,*images);
op=(MagickEvaluateOperator) ParseCommandOption(
MagickEvaluateOptions,MagickFalse,argv[i+1]);
evaluate_image=EvaluateImages(*images,op,exception);
if (evaluate_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=evaluate_image;
break;
}
break;
}
case 'f':
{
if (LocaleCompare("fft",option+1) == 0)
{
Image
*fourier_image;
/*
Implements the discrete Fourier transform (DFT).
*/
(void) SyncImageSettings(mogrify_info,*images);
fourier_image=ForwardFourierTransformImage(*images,*option == '-' ?
MagickTrue : MagickFalse,exception);
if (fourier_image == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=fourier_image;
break;
}
if (LocaleCompare("flatten",option+1) == 0)
{
Image
*flatten_image;
(void) SyncImagesSettings(mogrify_info,*images);
flatten_image=MergeImageLayers(*images,FlattenLayer,exception);
if (flatten_image == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=flatten_image;
break;
}
if (LocaleCompare("fx",option+1) == 0)
{
Image
*fx_image;
(void) SyncImagesSettings(mogrify_info,*images);
fx_image=FxImageChannel(*images,channel,argv[i+1],exception);
if (fx_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=fx_image;
break;
}
break;
}
case 'h':
{
if (LocaleCompare("hald-clut",option+1) == 0)
{
Image
*hald_image,
*image;
(void) SyncImagesSettings(mogrify_info,*images);
image=RemoveFirstImageFromList(images);
hald_image=RemoveFirstImageFromList(images);
if (hald_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) HaldClutImageChannel(image,channel,hald_image);
hald_image=DestroyImage(hald_image);
InheritException(exception,&image->exception);
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=image;
break;
}
break;
}
case 'i':
{
if (LocaleCompare("ift",option+1) == 0)
{
Image
*fourier_image,
*magnitude_image,
*phase_image;
/*
Implements the inverse fourier discrete Fourier transform (DFT).
*/
(void) SyncImagesSettings(mogrify_info,*images);
magnitude_image=RemoveFirstImageFromList(images);
phase_image=RemoveFirstImageFromList(images);
if (phase_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
fourier_image=InverseFourierTransformImage(magnitude_image,
phase_image,*option == '-' ? MagickTrue : MagickFalse,exception);
if (fourier_image == (Image *) NULL)
break;
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=fourier_image;
break;
}
if (LocaleCompare("insert",option+1) == 0)
{
Image
*p,
*q;
index=0;
if (*option != '+')
index=(ssize_t) StringToLong(argv[i+1]);
p=RemoveLastImageFromList(images);
if (p == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",argv[i+1]);
status=MagickFalse;
break;
}
q=p;
if (index == 0)
PrependImageToList(images,q);
else
if (index == (ssize_t) GetImageListLength(*images))
AppendImageToList(images,q);
else
{
q=GetImageFromList(*images,index-1);
if (q == (Image *) NULL)
{
p=DestroyImage(p);
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",argv[i+1]);
status=MagickFalse;
break;
}
InsertImageInList(&q,p);
}
*images=GetFirstImageInList(q);
break;
}
break;
}
case 'l':
{
if (LocaleCompare("layers",option+1) == 0)
{
Image
*layers;
ImageLayerMethod
method;
(void) SyncImagesSettings(mogrify_info,*images);
layers=(Image *) NULL;
method=(ImageLayerMethod) ParseCommandOption(MagickLayerOptions,
MagickFalse,argv[i+1]);
switch (method)
{
case CoalesceLayer:
{
layers=CoalesceImages(*images,exception);
break;
}
case CompareAnyLayer:
case CompareClearLayer:
case CompareOverlayLayer:
default:
{
layers=CompareImageLayers(*images,method,exception);
break;
}
case MergeLayer:
case FlattenLayer:
case MosaicLayer:
case TrimBoundsLayer:
{
layers=MergeImageLayers(*images,method,exception);
break;
}
case DisposeLayer:
{
layers=DisposeImages(*images,exception);
break;
}
case OptimizeImageLayer:
{
layers=OptimizeImageLayers(*images,exception);
break;
}
case OptimizePlusLayer:
{
layers=OptimizePlusImageLayers(*images,exception);
break;
}
case OptimizeTransLayer:
{
OptimizeImageTransparency(*images,exception);
break;
}
case RemoveDupsLayer:
{
RemoveDuplicateLayers(images,exception);
break;
}
case RemoveZeroLayer:
{
RemoveZeroDelayLayers(images,exception);
break;
}
case OptimizeLayer:
{
/*
General Purpose, GIF Animation Optimizer.
*/
layers=CoalesceImages(*images,exception);
if (layers == (Image *) NULL)
{
status=MagickFalse;
break;
}
InheritException(exception,&layers->exception);
*images=DestroyImageList(*images);
*images=layers;
layers=OptimizeImageLayers(*images,exception);
if (layers == (Image *) NULL)
{
status=MagickFalse;
break;
}
InheritException(exception,&layers->exception);
*images=DestroyImageList(*images);
*images=layers;
layers=(Image *) NULL;
OptimizeImageTransparency(*images,exception);
InheritException(exception,&(*images)->exception);
(void) RemapImages(quantize_info,*images,(Image *) NULL);
break;
}
case CompositeLayer:
{
CompositeOperator
compose;
Image
*source;
RectangleInfo
geometry;
/*
Split image sequence at the first 'NULL:' image.
*/
source=(*images);
while (source != (Image *) NULL)
{
source=GetNextImageInList(source);
if ((source != (Image *) NULL) &&
(LocaleCompare(source->magick,"NULL") == 0))
break;
}
if (source != (Image *) NULL)
{
if ((GetPreviousImageInList(source) == (Image *) NULL) ||
(GetNextImageInList(source) == (Image *) NULL))
source=(Image *) NULL;
else
{
/*
Separate the two lists, junk the null: image.
*/
source=SplitImageList(source->previous);
DeleteImageFromList(&source);
}
}
if (source == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"MissingNullSeparator","layers Composite");
status=MagickFalse;
break;
}
/*
Adjust offset with gravity and virtual canvas.
*/
SetGeometry(*images,&geometry);
(void) ParseAbsoluteGeometry((*images)->geometry,&geometry);
geometry.width=source->page.width != 0 ?
source->page.width : source->columns;
geometry.height=source->page.height != 0 ?
source->page.height : source->rows;
GravityAdjustGeometry((*images)->page.width != 0 ?
(*images)->page.width : (*images)->columns,
(*images)->page.height != 0 ? (*images)->page.height :
(*images)->rows,(*images)->gravity,&geometry);
compose=OverCompositeOp;
option=GetImageOption(mogrify_info,"compose");
if (option != (const char *) NULL)
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,option);
CompositeLayers(*images,compose,source,geometry.x,geometry.y,
exception);
source=DestroyImageList(source);
break;
}
}
if (layers == (Image *) NULL)
break;
InheritException(exception,&layers->exception);
*images=DestroyImageList(*images);
*images=layers;
break;
}
break;
}
case 'm':
{
if (LocaleCompare("map",option+1) == 0)
{
(void) SyncImagesSettings(mogrify_info,*images);
if (*option == '+')
{
(void) RemapImages(quantize_info,*images,(Image *) NULL);
InheritException(exception,&(*images)->exception);
break;
}
i++;
break;
}
if (LocaleCompare("maximum",option+1) == 0)
{
Image
*maximum_image;
/*
Maximum image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images);
maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception);
if (maximum_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=maximum_image;
break;
}
if (LocaleCompare("minimum",option+1) == 0)
{
Image
*minimum_image;
/*
Minimum image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images);
minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception);
if (minimum_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=minimum_image;
break;
}
if (LocaleCompare("morph",option+1) == 0)
{
Image
*morph_image;
(void) SyncImagesSettings(mogrify_info,*images);
morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]),
exception);
if (morph_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=morph_image;
break;
}
if (LocaleCompare("mosaic",option+1) == 0)
{
Image
*mosaic_image;
(void) SyncImagesSettings(mogrify_info,*images);
mosaic_image=MergeImageLayers(*images,MosaicLayer,exception);
if (mosaic_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=mosaic_image;
break;
}
break;
}
case 'p':
{
if (LocaleCompare("poly",option+1) == 0)
{
char
*args,
token[MaxTextExtent];
const char
*p;
double
*arguments;
Image
*polynomial_image;
register ssize_t
x;
size_t
number_arguments;
/*
Polynomial image.
*/
(void) SyncImageSettings(mogrify_info,*images);
args=InterpretImageProperties(mogrify_info,*images,argv[i+1]);
InheritException(exception,&(*images)->exception);
if (args == (char *) NULL)
break;
p=(char *) args;
for (x=0; *p != '\0'; x++)
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
}
number_arguments=(size_t) x;
arguments=(double *) AcquireQuantumMemory(number_arguments,
sizeof(*arguments));
if (arguments == (double *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,
"MemoryAllocationFailed",(*images)->filename);
(void) memset(arguments,0,number_arguments*
sizeof(*arguments));
p=(char *) args;
for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++)
{
GetNextToken(p,&p,MaxTextExtent,token);
if (*token == ',')
GetNextToken(p,&p,MaxTextExtent,token);
arguments[x]=StringToDouble(token,(char **) NULL);
}
args=DestroyString(args);
polynomial_image=PolynomialImageChannel(*images,channel,
number_arguments >> 1,arguments,exception);
arguments=(double *) RelinquishMagickMemory(arguments);
if (polynomial_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=polynomial_image;
break;
}
if (LocaleCompare("print",option+1) == 0)
{
char
*string;
(void) SyncImagesSettings(mogrify_info,*images);
string=InterpretImageProperties(mogrify_info,*images,argv[i+1]);
if (string == (char *) NULL)
break;
InheritException(exception,&(*images)->exception);
(void) FormatLocaleFile(stdout,"%s",string);
string=DestroyString(string);
}
if (LocaleCompare("process",option+1) == 0)
{
char
**arguments;
int
j,
number_arguments;
(void) SyncImagesSettings(mogrify_info,*images);
arguments=StringToArgv(argv[i+1],&number_arguments);
if (arguments == (char **) NULL)
break;
if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL))
{
char
breaker,
quote,
*token;
const char
*arguments;
int
next,
status;
size_t
length;
TokenInfo
*token_info;
/*
Support old style syntax, filter="-option arg".
*/
length=strlen(argv[i+1]);
token=(char *) NULL;
if (~length >= (MaxTextExtent-1))
token=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*token));
if (token == (char *) NULL)
break;
next=0;
arguments=argv[i+1];
token_info=AcquireTokenInfo();
status=Tokenizer(token_info,0,token,length,arguments,"","=",
"\"",'\0',&breaker,&next,"e);
token_info=DestroyTokenInfo(token_info);
if (status == 0)
{
const char
*argv;
argv=(&(arguments[next]));
(void) InvokeDynamicImageFilter(token,&(*images),1,&argv,
exception);
}
token=DestroyString(token);
break;
}
(void) SubstituteString(&arguments[1],"-","");
(void) InvokeDynamicImageFilter(arguments[1],&(*images),
number_arguments-2,(const char **) arguments+2,exception);
for (j=0; j < number_arguments; j++)
arguments[j]=DestroyString(arguments[j]);
arguments=(char **) RelinquishMagickMemory(arguments);
break;
}
break;
}
case 'r':
{
if (LocaleCompare("reverse",option+1) == 0)
{
ReverseImageList(images);
InheritException(exception,&(*images)->exception);
break;
}
break;
}
case 's':
{
if (LocaleCompare("smush",option+1) == 0)
{
Image
*smush_image;
ssize_t
offset;
(void) SyncImagesSettings(mogrify_info,*images);
offset=(ssize_t) StringToLong(argv[i+1]);
smush_image=SmushImages(*images,*option == '-' ? MagickTrue :
MagickFalse,offset,exception);
if (smush_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=smush_image;
break;
}
if (LocaleCompare("swap",option+1) == 0)
{
Image
*p,
*q,
*u,
*v;
ssize_t
swap_index;
index=(-1);
swap_index=(-2);
if (*option != '+')
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
swap_index=(-1);
flags=ParseGeometry(argv[i+1],&geometry_info);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) != 0)
swap_index=(ssize_t) geometry_info.sigma;
}
p=GetImageFromList(*images,index);
q=GetImageFromList(*images,swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",(*images)->filename);
status=MagickFalse;
break;
}
if (p == q)
break;
u=CloneImage(p,0,0,MagickTrue,exception);
if (u == (Image *) NULL)
break;
v=CloneImage(q,0,0,MagickTrue,exception);
if (v == (Image *) NULL)
{
u=DestroyImage(u);
break;
}
ReplaceImageInList(&p,v);
ReplaceImageInList(&q,u);
*images=GetFirstImageInList(q);
break;
}
break;
}
case 'w':
{
if (LocaleCompare("write",option+1) == 0)
{
char
key[MaxTextExtent];
Image
*write_images;
ImageInfo
*write_info;
(void) SyncImagesSettings(mogrify_info,*images);
(void) FormatLocaleString(key,MaxTextExtent,"cache:%s",argv[i+1]);
(void) DeleteImageRegistry(key);
write_images=(*images);
if (*option == '+')
write_images=CloneImageList(*images,exception);
write_info=CloneImageInfo(mogrify_info);
status&=WriteImages(write_info,write_images,argv[i+1],exception);
write_info=DestroyImageInfo(write_info);
if (*option == '+')
write_images=DestroyImageList(write_images);
break;
}
break;
}
default:
break;
}
i+=count;
}
quantize_info=DestroyQuantizeInfo(quantize_info);
mogrify_info=DestroyImageInfo(mogrify_info);
status&=MogrifyImageInfo(image_info,argc,argv,exception);
return(status != 0 ? MagickTrue : MagickFalse);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1623'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,
const int argc,const char **argv,Image **images,ExceptionInfo *exception)
{
const char
*option;
ImageInfo
*mogrify_info;
MagickStatusType
status;
PixelInterpolateMethod
interpolate_method;
QuantizeInfo
*quantize_info;
register ssize_t
i;
ssize_t
count,
index;
/*
Apply options to the image list.
*/
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(images != (Image **) NULL);
assert((*images)->previous == (Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
if ((argc <= 0) || (*argv == (char *) NULL))
return(MagickTrue);
interpolate_method=UndefinedInterpolatePixel;
mogrify_info=CloneImageInfo(image_info);
quantize_info=AcquireQuantizeInfo(mogrify_info);
status=MagickTrue;
for (i=0; i < (ssize_t) argc; i++)
{
if (*images == (Image *) NULL)
break;
option=argv[i];
if (IsCommandOption(option) == MagickFalse)
continue;
count=ParseCommandOption(MagickCommandOptions,MagickFalse,option);
count=MagickMax(count,0L);
if ((i+count) >= (ssize_t) argc)
break;
status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception);
switch (*(option+1))
{
case 'a':
{
if (LocaleCompare("affinity",option+1) == 0)
{
(void) SyncImagesSettings(mogrify_info,*images,exception);
if (*option == '+')
{
(void) RemapImages(quantize_info,*images,(Image *) NULL,
exception);
break;
}
i++;
break;
}
if (LocaleCompare("append",option+1) == 0)
{
Image
*append_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
append_image=AppendImages(*images,*option == '-' ? MagickTrue :
MagickFalse,exception);
if (append_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=append_image;
break;
}
if (LocaleCompare("average",option+1) == 0)
{
Image
*average_image;
/*
Average an image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
average_image=EvaluateImages(*images,MeanEvaluateOperator,
exception);
if (average_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=average_image;
break;
}
break;
}
case 'c':
{
if (LocaleCompare("channel-fx",option+1) == 0)
{
Image
*channel_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
channel_image=ChannelFxImage(*images,argv[i+1],exception);
if (channel_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=channel_image;
break;
}
if (LocaleCompare("clut",option+1) == 0)
{
Image
*clut_image,
*image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
image=RemoveFirstImageFromList(images);
clut_image=RemoveFirstImageFromList(images);
if (clut_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) ClutImage(image,clut_image,interpolate_method,exception);
clut_image=DestroyImage(clut_image);
*images=DestroyImageList(*images);
*images=image;
break;
}
if (LocaleCompare("coalesce",option+1) == 0)
{
Image
*coalesce_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
coalesce_image=CoalesceImages(*images,exception);
if (coalesce_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=coalesce_image;
break;
}
if (LocaleCompare("combine",option+1) == 0)
{
ColorspaceType
colorspace;
Image
*combine_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
colorspace=(*images)->colorspace;
if ((*images)->number_channels < GetImageListLength(*images))
colorspace=sRGBColorspace;
if (*option == '+')
colorspace=(ColorspaceType) ParseCommandOption(
MagickColorspaceOptions,MagickFalse,argv[i+1]);
combine_image=CombineImages(*images,colorspace,exception);
if (combine_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=combine_image;
break;
}
if (LocaleCompare("compare",option+1) == 0)
{
double
distortion;
Image
*difference_image,
*image,
*reconstruct_image;
MetricType
metric;
/*
Mathematically and visually annotate the difference between an
image and its reconstruction.
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
image=RemoveFirstImageFromList(images);
reconstruct_image=RemoveFirstImageFromList(images);
if (reconstruct_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
metric=UndefinedErrorMetric;
option=GetImageOption(mogrify_info,"metric");
if (option != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,option);
difference_image=CompareImages(image,reconstruct_image,metric,
&distortion,exception);
if (difference_image == (Image *) NULL)
break;
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=difference_image;
break;
}
if (LocaleCompare("complex",option+1) == 0)
{
ComplexOperator
op;
Image
*complex_images;
(void) SyncImageSettings(mogrify_info,*images,exception);
op=(ComplexOperator) ParseCommandOption(MagickComplexOptions,
MagickFalse,argv[i+1]);
complex_images=ComplexImages(*images,op,exception);
if (complex_images == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=complex_images;
break;
}
if (LocaleCompare("composite",option+1) == 0)
{
CompositeOperator
compose;
const char*
value;
MagickBooleanType
clip_to_self;
Image
*mask_image,
*new_images,
*source_image;
RectangleInfo
geometry;
/* Compose value from "-compose" option only */
(void) SyncImageSettings(mogrify_info,*images,exception);
value=GetImageOption(mogrify_info,"compose");
if (value == (const char *) NULL)
compose=OverCompositeOp; /* use Over not source_image->compose */
else
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,value);
/* Get "clip-to-self" expert setting (false is normal) */
clip_to_self=GetCompositeClipToSelf(compose);
value=GetImageOption(mogrify_info,"compose:clip-to-self");
if (value != (const char *) NULL)
clip_to_self=IsStringTrue(value);
value=GetImageOption(mogrify_info,"compose:outside-overlay");
if (value != (const char *) NULL)
clip_to_self=IsStringFalse(value); /* deprecated */
new_images=RemoveFirstImageFromList(images);
source_image=RemoveFirstImageFromList(images);
if (source_image == (Image *) NULL)
break; /* FUTURE - produce Exception, rather than silent fail */
/* FUTURE: this should not be here! - should be part of -geometry */
if (source_image->geometry != (char *) NULL)
{
RectangleInfo
resize_geometry;
(void) ParseRegionGeometry(source_image,source_image->geometry,
&resize_geometry,exception);
if ((source_image->columns != resize_geometry.width) ||
(source_image->rows != resize_geometry.height))
{
Image
*resize_image;
resize_image=ResizeImage(source_image,resize_geometry.width,
resize_geometry.height,source_image->filter,exception);
if (resize_image != (Image *) NULL)
{
source_image=DestroyImage(source_image);
source_image=resize_image;
}
}
}
SetGeometry(source_image,&geometry);
(void) ParseAbsoluteGeometry(source_image->geometry,&geometry);
GravityAdjustGeometry(new_images->columns,new_images->rows,
new_images->gravity,&geometry);
mask_image=RemoveFirstImageFromList(images);
if (mask_image == (Image *) NULL)
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,exception);
else
{
if ((compose == DisplaceCompositeOp) ||
(compose == DistortCompositeOp))
{
status&=CompositeImage(source_image,mask_image,
CopyGreenCompositeOp,MagickTrue,0,0,exception);
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,exception);
}
else
{
Image
*clone_image;
clone_image=CloneImage(new_images,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
break;
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,exception);
status&=CompositeImage(new_images,mask_image,
CopyAlphaCompositeOp,MagickTrue,0,0,exception);
status&=CompositeImage(clone_image,new_images,
OverCompositeOp,clip_to_self,0,0,exception);
new_images=DestroyImageList(new_images);
new_images=clone_image;
}
mask_image=DestroyImage(mask_image);
}
source_image=DestroyImage(source_image);
*images=DestroyImageList(*images);
*images=new_images;
break;
}
if (LocaleCompare("copy",option+1) == 0)
{
Image
*source_image;
OffsetInfo
offset;
RectangleInfo
geometry;
/*
Copy image pixels.
*/
(void) SyncImageSettings(mogrify_info,*images,exception);
(void) ParsePageGeometry(*images,argv[i+2],&geometry,exception);
offset.x=geometry.x;
offset.y=geometry.y;
source_image=(*images);
if (source_image->next != (Image *) NULL)
source_image=source_image->next;
(void) ParsePageGeometry(source_image,argv[i+1],&geometry,
exception);
status=CopyImagePixels(*images,source_image,&geometry,&offset,
exception);
break;
}
break;
}
case 'd':
{
if (LocaleCompare("deconstruct",option+1) == 0)
{
Image
*deconstruct_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer,
exception);
if (deconstruct_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=deconstruct_image;
break;
}
if (LocaleCompare("delete",option+1) == 0)
{
if (*option == '+')
DeleteImages(images,"-1",exception);
else
DeleteImages(images,argv[i+1],exception);
break;
}
if (LocaleCompare("dither",option+1) == 0)
{
if (*option == '+')
{
quantize_info->dither_method=NoDitherMethod;
break;
}
quantize_info->dither_method=(DitherMethod) ParseCommandOption(
MagickDitherOptions,MagickFalse,argv[i+1]);
break;
}
if (LocaleCompare("duplicate",option+1) == 0)
{
Image
*duplicate_images;
if (*option == '+')
duplicate_images=DuplicateImages(*images,1,"-1",exception);
else
{
const char
*p;
size_t
number_duplicates;
number_duplicates=(size_t) StringToLong(argv[i+1]);
p=strchr(argv[i+1],',');
if (p == (const char *) NULL)
duplicate_images=DuplicateImages(*images,number_duplicates,
"-1",exception);
else
duplicate_images=DuplicateImages(*images,number_duplicates,p,
exception);
}
AppendImageToList(images, duplicate_images);
(void) SyncImagesSettings(mogrify_info,*images,exception);
break;
}
break;
}
case 'e':
{
if (LocaleCompare("evaluate-sequence",option+1) == 0)
{
Image
*evaluate_image;
MagickEvaluateOperator
op;
(void) SyncImageSettings(mogrify_info,*images,exception);
op=(MagickEvaluateOperator) ParseCommandOption(
MagickEvaluateOptions,MagickFalse,argv[i+1]);
evaluate_image=EvaluateImages(*images,op,exception);
if (evaluate_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=evaluate_image;
break;
}
break;
}
case 'f':
{
if (LocaleCompare("fft",option+1) == 0)
{
Image
*fourier_image;
/*
Implements the discrete Fourier transform (DFT).
*/
(void) SyncImageSettings(mogrify_info,*images,exception);
fourier_image=ForwardFourierTransformImage(*images,*option == '-' ?
MagickTrue : MagickFalse,exception);
if (fourier_image == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=fourier_image;
break;
}
if (LocaleCompare("flatten",option+1) == 0)
{
Image
*flatten_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
flatten_image=MergeImageLayers(*images,FlattenLayer,exception);
if (flatten_image == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=flatten_image;
break;
}
if (LocaleCompare("fx",option+1) == 0)
{
Image
*fx_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
fx_image=FxImage(*images,argv[i+1],exception);
if (fx_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=fx_image;
break;
}
break;
}
case 'h':
{
if (LocaleCompare("hald-clut",option+1) == 0)
{
Image
*hald_image,
*image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
image=RemoveFirstImageFromList(images);
hald_image=RemoveFirstImageFromList(images);
if (hald_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
(void) HaldClutImage(image,hald_image,exception);
hald_image=DestroyImage(hald_image);
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=image;
break;
}
break;
}
case 'i':
{
if (LocaleCompare("ift",option+1) == 0)
{
Image
*fourier_image,
*magnitude_image,
*phase_image;
/*
Implements the inverse fourier discrete Fourier transform (DFT).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
magnitude_image=RemoveFirstImageFromList(images);
phase_image=RemoveFirstImageFromList(images);
if (phase_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
fourier_image=InverseFourierTransformImage(magnitude_image,
phase_image,*option == '-' ? MagickTrue : MagickFalse,exception);
if (fourier_image == (Image *) NULL)
break;
if (*images != (Image *) NULL)
*images=DestroyImageList(*images);
*images=fourier_image;
break;
}
if (LocaleCompare("insert",option+1) == 0)
{
Image
*p,
*q;
index=0;
if (*option != '+')
index=(ssize_t) StringToLong(argv[i+1]);
p=RemoveLastImageFromList(images);
if (p == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",argv[i+1]);
status=MagickFalse;
break;
}
q=p;
if (index == 0)
PrependImageToList(images,q);
else
if (index == (ssize_t) GetImageListLength(*images))
AppendImageToList(images,q);
else
{
q=GetImageFromList(*images,index-1);
if (q == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",argv[i+1]);
status=MagickFalse;
break;
}
InsertImageInList(&q,p);
}
*images=GetFirstImageInList(q);
break;
}
if (LocaleCompare("interpolate",option+1) == 0)
{
interpolate_method=(PixelInterpolateMethod) ParseCommandOption(
MagickInterpolateOptions,MagickFalse,argv[i+1]);
break;
}
break;
}
case 'l':
{
if (LocaleCompare("layers",option+1) == 0)
{
Image
*layers;
LayerMethod
method;
(void) SyncImagesSettings(mogrify_info,*images,exception);
layers=(Image *) NULL;
method=(LayerMethod) ParseCommandOption(MagickLayerOptions,
MagickFalse,argv[i+1]);
switch (method)
{
case CoalesceLayer:
{
layers=CoalesceImages(*images,exception);
break;
}
case CompareAnyLayer:
case CompareClearLayer:
case CompareOverlayLayer:
default:
{
layers=CompareImagesLayers(*images,method,exception);
break;
}
case MergeLayer:
case FlattenLayer:
case MosaicLayer:
case TrimBoundsLayer:
{
layers=MergeImageLayers(*images,method,exception);
break;
}
case DisposeLayer:
{
layers=DisposeImages(*images,exception);
break;
}
case OptimizeImageLayer:
{
layers=OptimizeImageLayers(*images,exception);
break;
}
case OptimizePlusLayer:
{
layers=OptimizePlusImageLayers(*images,exception);
break;
}
case OptimizeTransLayer:
{
OptimizeImageTransparency(*images,exception);
break;
}
case RemoveDupsLayer:
{
RemoveDuplicateLayers(images,exception);
break;
}
case RemoveZeroLayer:
{
RemoveZeroDelayLayers(images,exception);
break;
}
case OptimizeLayer:
{
/*
General Purpose, GIF Animation Optimizer.
*/
layers=CoalesceImages(*images,exception);
if (layers == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=layers;
layers=OptimizeImageLayers(*images,exception);
if (layers == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=layers;
layers=(Image *) NULL;
OptimizeImageTransparency(*images,exception);
(void) RemapImages(quantize_info,*images,(Image *) NULL,
exception);
break;
}
case CompositeLayer:
{
CompositeOperator
compose;
Image
*source;
RectangleInfo
geometry;
/*
Split image sequence at the first 'NULL:' image.
*/
source=(*images);
while (source != (Image *) NULL)
{
source=GetNextImageInList(source);
if ((source != (Image *) NULL) &&
(LocaleCompare(source->magick,"NULL") == 0))
break;
}
if (source != (Image *) NULL)
{
if ((GetPreviousImageInList(source) == (Image *) NULL) ||
(GetNextImageInList(source) == (Image *) NULL))
source=(Image *) NULL;
else
{
/*
Separate the two lists, junk the null: image.
*/
source=SplitImageList(source->previous);
DeleteImageFromList(&source);
}
}
if (source == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"MissingNullSeparator","layers Composite");
status=MagickFalse;
break;
}
/*
Adjust offset with gravity and virtual canvas.
*/
SetGeometry(*images,&geometry);
(void) ParseAbsoluteGeometry((*images)->geometry,&geometry);
geometry.width=source->page.width != 0 ?
source->page.width : source->columns;
geometry.height=source->page.height != 0 ?
source->page.height : source->rows;
GravityAdjustGeometry((*images)->page.width != 0 ?
(*images)->page.width : (*images)->columns,
(*images)->page.height != 0 ? (*images)->page.height :
(*images)->rows,(*images)->gravity,&geometry);
compose=OverCompositeOp;
option=GetImageOption(mogrify_info,"compose");
if (option != (const char *) NULL)
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,option);
CompositeLayers(*images,compose,source,geometry.x,geometry.y,
exception);
source=DestroyImageList(source);
break;
}
}
if (layers == (Image *) NULL)
break;
*images=DestroyImageList(*images);
*images=layers;
break;
}
break;
}
case 'm':
{
if (LocaleCompare("map",option+1) == 0)
{
(void) SyncImagesSettings(mogrify_info,*images,exception);
if (*option == '+')
{
(void) RemapImages(quantize_info,*images,(Image *) NULL,
exception);
break;
}
i++;
break;
}
if (LocaleCompare("maximum",option+1) == 0)
{
Image
*maximum_image;
/*
Maximum image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception);
if (maximum_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=maximum_image;
break;
}
if (LocaleCompare("minimum",option+1) == 0)
{
Image
*minimum_image;
/*
Minimum image sequence (deprecated).
*/
(void) SyncImagesSettings(mogrify_info,*images,exception);
minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception);
if (minimum_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=minimum_image;
break;
}
if (LocaleCompare("morph",option+1) == 0)
{
Image
*morph_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]),
exception);
if (morph_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=morph_image;
break;
}
if (LocaleCompare("mosaic",option+1) == 0)
{
Image
*mosaic_image;
(void) SyncImagesSettings(mogrify_info,*images,exception);
mosaic_image=MergeImageLayers(*images,MosaicLayer,exception);
if (mosaic_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=mosaic_image;
break;
}
break;
}
case 'p':
{
if (LocaleCompare("poly",option+1) == 0)
{
char
*args,
token[MagickPathExtent];
const char
*p;
double
*arguments;
Image
*polynomial_image;
register ssize_t
x;
size_t
number_arguments;
/*
Polynomial image.
*/
(void) SyncImageSettings(mogrify_info,*images,exception);
args=InterpretImageProperties(mogrify_info,*images,argv[i+1],
exception);
if (args == (char *) NULL)
break;
p=(char *) args;
for (x=0; *p != '\0'; x++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
}
number_arguments=(size_t) x;
arguments=(double *) AcquireQuantumMemory(number_arguments,
sizeof(*arguments));
if (arguments == (double *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,
"MemoryAllocationFailed",(*images)->filename);
(void) memset(arguments,0,number_arguments*
sizeof(*arguments));
p=(char *) args;
for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
arguments[x]=StringToDouble(token,(char **) NULL);
}
args=DestroyString(args);
polynomial_image=PolynomialImage(*images,number_arguments >> 1,
arguments,exception);
arguments=(double *) RelinquishMagickMemory(arguments);
if (polynomial_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=polynomial_image;
}
if (LocaleCompare("print",option+1) == 0)
{
char
*string;
(void) SyncImagesSettings(mogrify_info,*images,exception);
string=InterpretImageProperties(mogrify_info,*images,argv[i+1],
exception);
if (string == (char *) NULL)
break;
(void) FormatLocaleFile(stdout,"%s",string);
string=DestroyString(string);
}
if (LocaleCompare("process",option+1) == 0)
{
char
**arguments;
int
j,
number_arguments;
(void) SyncImagesSettings(mogrify_info,*images,exception);
arguments=StringToArgv(argv[i+1],&number_arguments);
if (arguments == (char **) NULL)
break;
if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL))
{
char
breaker,
quote,
*token;
const char
*argument;
int
next,
token_status;
size_t
length;
TokenInfo
*token_info;
/*
Support old style syntax, filter="-option arg".
*/
length=strlen(argv[i+1]);
token=(char *) NULL;
if (~length >= (MagickPathExtent-1))
token=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*token));
if (token == (char *) NULL)
break;
next=0;
argument=argv[i+1];
token_info=AcquireTokenInfo();
token_status=Tokenizer(token_info,0,token,length,argument,"",
"=","\"",'\0',&breaker,&next,"e);
token_info=DestroyTokenInfo(token_info);
if (token_status == 0)
{
const char
*arg;
arg=(&(argument[next]));
(void) InvokeDynamicImageFilter(token,&(*images),1,&arg,
exception);
}
token=DestroyString(token);
break;
}
(void) SubstituteString(&arguments[1],"-","");
(void) InvokeDynamicImageFilter(arguments[1],&(*images),
number_arguments-2,(const char **) arguments+2,exception);
for (j=0; j < number_arguments; j++)
arguments[j]=DestroyString(arguments[j]);
arguments=(char **) RelinquishMagickMemory(arguments);
break;
}
break;
}
case 'r':
{
if (LocaleCompare("reverse",option+1) == 0)
{
ReverseImageList(images);
break;
}
break;
}
case 's':
{
if (LocaleCompare("smush",option+1) == 0)
{
Image
*smush_image;
ssize_t
offset;
(void) SyncImagesSettings(mogrify_info,*images,exception);
offset=(ssize_t) StringToLong(argv[i+1]);
smush_image=SmushImages(*images,*option == '-' ? MagickTrue :
MagickFalse,offset,exception);
if (smush_image == (Image *) NULL)
{
status=MagickFalse;
break;
}
*images=DestroyImageList(*images);
*images=smush_image;
break;
}
if (LocaleCompare("swap",option+1) == 0)
{
Image
*p,
*q,
*u,
*v;
ssize_t
swap_index;
index=(-1);
swap_index=(-2);
if (*option != '+')
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
swap_index=(-1);
flags=ParseGeometry(argv[i+1],&geometry_info);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) != 0)
swap_index=(ssize_t) geometry_info.sigma;
}
p=GetImageFromList(*images,index);
q=GetImageFromList(*images,swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"NoSuchImage","`%s'",(*images)->filename);
status=MagickFalse;
break;
}
if (p == q)
break;
u=CloneImage(p,0,0,MagickTrue,exception);
if (u == (Image *) NULL)
break;
v=CloneImage(q,0,0,MagickTrue,exception);
if (v == (Image *) NULL)
{
u=DestroyImage(u);
break;
}
ReplaceImageInList(&p,v);
ReplaceImageInList(&q,u);
*images=GetFirstImageInList(q);
break;
}
break;
}
case 'w':
{
if (LocaleCompare("write",option+1) == 0)
{
char
key[MagickPathExtent];
Image
*write_images;
ImageInfo
*write_info;
(void) SyncImagesSettings(mogrify_info,*images,exception);
(void) FormatLocaleString(key,MagickPathExtent,"cache:%s",
argv[i+1]);
(void) DeleteImageRegistry(key);
write_images=(*images);
if (*option == '+')
write_images=CloneImageList(*images,exception);
write_info=CloneImageInfo(mogrify_info);
status&=WriteImages(write_info,write_images,argv[i+1],exception);
write_info=DestroyImageInfo(write_info);
if (*option == '+')
write_images=DestroyImageList(write_images);
break;
}
break;
}
default:
break;
}
i+=count;
}
quantize_info=DestroyQuantizeInfo(quantize_info);
mogrify_info=DestroyImageInfo(mogrify_info);
status&=MogrifyImageInfo(image_info,argc,argv,exception);
return(status != 0 ? MagickTrue : MagickFalse);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1616'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image,
const size_t data_size,ExceptionInfo *exception)
{
#define MaxCode(number_bits) ((one << (number_bits))-1)
#define MaxHashTable 5003
#define MaxGIFBits 12UL
#define MaxGIFTable (1UL << MaxGIFBits)
#define GIFOutputCode(code) \
{ \
/* \
Emit a code. \
*/ \
if (bits > 0) \
datum|=(size_t) (code) << bits; \
else \
datum=(size_t) (code); \
bits+=number_bits; \
while (bits >= 8) \
{ \
/* \
Add a character to current packet. \
*/ \
packet[length++]=(unsigned char) (datum & 0xff); \
if (length >= 254) \
{ \
(void) WriteBlobByte(image,(unsigned char) length); \
(void) WriteBlob(image,length,packet); \
length=0; \
} \
datum>>=8; \
bits-=8; \
} \
if (free_code > max_code) \
{ \
number_bits++; \
if (number_bits == MaxGIFBits) \
max_code=MaxGIFTable; \
else \
max_code=MaxCode(number_bits); \
} \
}
Quantum
index;
short
*hash_code,
*hash_prefix,
waiting_code;
size_t
bits,
clear_code,
datum,
end_of_information_code,
free_code,
length,
max_code,
next_pixel,
number_bits,
one,
pass;
ssize_t
displacement,
offset,
k,
y;
unsigned char
*packet,
*hash_suffix;
/*
Allocate encoder tables.
*/
assert(image != (Image *) NULL);
one=1;
packet=(unsigned char *) AcquireQuantumMemory(256,sizeof(*packet));
hash_code=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_code));
hash_prefix=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_prefix));
hash_suffix=(unsigned char *) AcquireQuantumMemory(MaxHashTable,
sizeof(*hash_suffix));
if ((packet == (unsigned char *) NULL) || (hash_code == (short *) NULL) ||
(hash_prefix == (short *) NULL) ||
(hash_suffix == (unsigned char *) NULL))
{
if (packet != (unsigned char *) NULL)
packet=(unsigned char *) RelinquishMagickMemory(packet);
if (hash_code != (short *) NULL)
hash_code=(short *) RelinquishMagickMemory(hash_code);
if (hash_prefix != (short *) NULL)
hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
if (hash_suffix != (unsigned char *) NULL)
hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
return(MagickFalse);
}
/*
Initialize GIF encoder.
*/
(void) memset(packet,0,256*sizeof(*packet));
(void) memset(hash_code,0,MaxHashTable*sizeof(*hash_code));
(void) memset(hash_prefix,0,MaxHashTable*sizeof(*hash_prefix));
(void) memset(hash_suffix,0,MaxHashTable*sizeof(*hash_suffix));
number_bits=data_size;
max_code=MaxCode(number_bits);
clear_code=((short) one << (data_size-1));
end_of_information_code=clear_code+1;
free_code=clear_code+2;
length=0;
datum=0;
bits=0;
GIFOutputCode(clear_code);
/*
Encode pixels.
*/
offset=0;
pass=0;
waiting_code=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,offset,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (y == 0)
{
waiting_code=(short) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
for (x=(ssize_t) (y == 0 ? 1 : 0); x < (ssize_t) image->columns; x++)
{
/*
Probe hash table.
*/
index=(Quantum) ((size_t) GetPixelIndex(image,p) & 0xff);
p+=GetPixelChannels(image);
k=(ssize_t) (((size_t) index << (MaxGIFBits-8))+waiting_code);
if (k >= MaxHashTable)
k-=MaxHashTable;
next_pixel=MagickFalse;
displacement=1;
if (hash_code[k] > 0)
{
if ((hash_prefix[k] == waiting_code) &&
(hash_suffix[k] == (unsigned char) index))
{
waiting_code=hash_code[k];
continue;
}
if (k != 0)
displacement=MaxHashTable-k;
for ( ; ; )
{
k-=displacement;
if (k < 0)
k+=MaxHashTable;
if (hash_code[k] == 0)
break;
if ((hash_prefix[k] == waiting_code) &&
(hash_suffix[k] == (unsigned char) index))
{
waiting_code=hash_code[k];
next_pixel=MagickTrue;
break;
}
}
if (next_pixel != MagickFalse)
continue;
}
GIFOutputCode(waiting_code);
if (free_code < MaxGIFTable)
{
hash_code[k]=(short) free_code++;
hash_prefix[k]=waiting_code;
hash_suffix[k]=(unsigned char) index;
}
else
{
/*
Fill the hash table with empty entries.
*/
for (k=0; k < MaxHashTable; k++)
hash_code[k]=0;
/*
Reset compressor and issue a clear code.
*/
free_code=clear_code+2;
GIFOutputCode(clear_code);
number_bits=data_size;
max_code=MaxCode(number_bits);
}
waiting_code=(short) index;
}
if (image_info->interlace == NoInterlace)
offset++;
else
switch (pass)
{
case 0:
default:
{
offset+=8;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=4;
}
break;
}
case 1:
{
offset+=8;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=2;
}
break;
}
case 2:
{
offset+=4;
if (offset >= (ssize_t) image->rows)
{
pass++;
offset=1;
}
break;
}
case 3:
{
offset+=2;
break;
}
}
}
/*
Flush out the buffered code.
*/
GIFOutputCode(waiting_code);
GIFOutputCode(end_of_information_code);
if (bits > 0)
{
/*
Add a character to current packet.
*/
packet[length++]=(unsigned char) (datum & 0xff);
if (length >= 254)
{
(void) WriteBlobByte(image,(unsigned char) length);
(void) WriteBlob(image,length,packet);
length=0;
}
}
/*
Flush accumulated data.
*/
if (length > 0)
{
(void) WriteBlobByte(image,(unsigned char) length);
(void) WriteBlob(image,length,packet);
}
/*
Free encoder memory.
*/
hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix);
hash_prefix=(short *) RelinquishMagickMemory(hash_prefix);
hash_code=(short *) RelinquishMagickMemory(hash_code);
packet=(unsigned char *) RelinquishMagickMemory(packet);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-703', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1595'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(images,complex_images,images->rows,1L)
#endif
for (y=0; y < (ssize_t) images->rows; y++)
{
register const PixelPacket
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register PixelPacket
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,
MagickMax(Ar_image->columns,Cr_image->columns),1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,
MagickMax(Ai_image->columns,Ci_image->columns),1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,
MagickMax(Br_image->columns,Cr_image->columns),1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,
MagickMax(Bi_image->columns,Ci_image->columns),1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const PixelPacket *) NULL) ||
(Ai == (const PixelPacket *) NULL) ||
(Br == (const PixelPacket *) NULL) ||
(Bi == (const PixelPacket *) NULL) ||
(Cr == (PixelPacket *) NULL) || (Ci == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) images->columns; x++)
{
switch (op)
{
case AddComplexOperator:
{
Cr->red=Ar->red+Br->red;
Ci->red=Ai->red+Bi->red;
Cr->green=Ar->green+Br->green;
Ci->green=Ai->green+Bi->green;
Cr->blue=Ar->blue+Br->blue;
Ci->blue=Ai->blue+Bi->blue;
if (images->matte != MagickFalse)
{
Cr->opacity=Ar->opacity+Br->opacity;
Ci->opacity=Ai->opacity+Bi->opacity;
}
break;
}
case ConjugateComplexOperator:
default:
{
Cr->red=Ar->red;
Ci->red=(-Bi->red);
Cr->green=Ar->green;
Ci->green=(-Bi->green);
Cr->blue=Ar->blue;
Ci->blue=(-Bi->blue);
if (images->matte != MagickFalse)
{
Cr->opacity=Ar->opacity;
Ci->opacity=(-Bi->opacity);
}
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal(Br->red*Br->red+Bi->red*Bi->red+snr);
Cr->red=gamma*(Ar->red*Br->red+Ai->red*Bi->red);
Ci->red=gamma*(Ai->red*Br->red-Ar->red*Bi->red);
gamma=PerceptibleReciprocal(Br->green*Br->green+Bi->green*Bi->green+
snr);
Cr->green=gamma*(Ar->green*Br->green+Ai->green*Bi->green);
Ci->green=gamma*(Ai->green*Br->green-Ar->green*Bi->green);
gamma=PerceptibleReciprocal(Br->blue*Br->blue+Bi->blue*Bi->blue+snr);
Cr->blue=gamma*(Ar->blue*Br->blue+Ai->blue*Bi->blue);
Ci->blue=gamma*(Ai->blue*Br->blue-Ar->blue*Bi->blue);
if (images->matte != MagickFalse)
{
gamma=PerceptibleReciprocal(Br->opacity*Br->opacity+Bi->opacity*
Bi->opacity+snr);
Cr->opacity=gamma*(Ar->opacity*Br->opacity+Ai->opacity*
Bi->opacity);
Ci->opacity=gamma*(Ai->opacity*Br->opacity-Ar->opacity*
Bi->opacity);
}
break;
}
case MagnitudePhaseComplexOperator:
{
Cr->red=sqrt(Ar->red*Ar->red+Ai->red*Ai->red);
Ci->red=atan2(Ai->red,Ar->red)/(2.0*MagickPI)+0.5;
Cr->green=sqrt(Ar->green*Ar->green+Ai->green*Ai->green);
Ci->green=atan2(Ai->green,Ar->green)/(2.0*MagickPI)+0.5;
Cr->blue=sqrt(Ar->blue*Ar->blue+Ai->blue*Ai->blue);
Ci->blue=atan2(Ai->blue,Ar->blue)/(2.0*MagickPI)+0.5;
if (images->matte != MagickFalse)
{
Cr->opacity=sqrt(Ar->opacity*Ar->opacity+Ai->opacity*Ai->opacity);
Ci->opacity=atan2(Ai->opacity,Ar->opacity)/(2.0*MagickPI)+0.5;
}
break;
}
case MultiplyComplexOperator:
{
Cr->red=QuantumScale*(Ar->red*Br->red-Ai->red*Bi->red);
Ci->red=QuantumScale*(Ai->red*Br->red+Ar->red*Bi->red);
Cr->green=QuantumScale*(Ar->green*Br->green-Ai->green*Bi->green);
Ci->green=QuantumScale*(Ai->green*Br->green+Ar->green*Bi->green);
Cr->blue=QuantumScale*(Ar->blue*Br->blue-Ai->blue*Bi->blue);
Ci->blue=QuantumScale*(Ai->blue*Br->blue+Ar->blue*Bi->blue);
if (images->matte != MagickFalse)
{
Cr->opacity=QuantumScale*(Ar->opacity*Br->opacity-Ai->opacity*
Bi->opacity);
Ci->opacity=QuantumScale*(Ai->opacity*Br->opacity+Ar->opacity*
Bi->opacity);
}
break;
}
case RealImaginaryComplexOperator:
{
Cr->red=Ar->red*cos(2.0*MagickPI*(Ai->red-0.5));
Ci->red=Ar->red*sin(2.0*MagickPI*(Ai->red-0.5));
Cr->green=Ar->green*cos(2.0*MagickPI*(Ai->green-0.5));
Ci->green=Ar->green*sin(2.0*MagickPI*(Ai->green-0.5));
Cr->blue=Ar->blue*cos(2.0*MagickPI*(Ai->blue-0.5));
Ci->blue=Ar->blue*sin(2.0*MagickPI*(Ai->blue-0.5));
if (images->matte != MagickFalse)
{
Cr->opacity=Ar->opacity*cos(2.0*MagickPI*(Ai->opacity-0.5));
Ci->opacity=Ar->opacity*sin(2.0*MagickPI*(Ai->opacity-0.5));
}
break;
}
case SubtractComplexOperator:
{
Cr->red=Ar->red-Br->red;
Ci->red=Ai->red-Bi->red;
Cr->green=Ar->green-Br->green;
Ci->green=Ai->green-Bi->green;
Cr->blue=Ar->blue-Br->blue;
Ci->blue=Ai->blue-Bi->blue;
if (images->matte != MagickFalse)
{
Cr->opacity=Ar->opacity-Br->opacity;
Ci->opacity=Ai->opacity-Bi->opacity;
}
break;
}
}
Ar++;
Ai++;
Br++;
Bi++;
Cr++;
Ci++;
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1595'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickPixelPacket **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
MagickPixelPacket
**pixels;
register ssize_t
i,
j;
size_t
columns,
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (MagickPixelPacket **) NULL)
return((MagickPixelPacket **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
columns=images->columns;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns,
sizeof(**pixels));
if (pixels[i] == (MagickPixelPacket *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
GetMagickPixelPacket(images,&pixels[i][j]);
}
return(pixels);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1615'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
format,
magick[MaxTextExtent];
const char
*value;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*pixels,
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
max_value=GetQuantumRange(image->depth);
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MaxTextExtent);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,&image->exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MaxTextExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,&image->exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MaxTextExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent);
if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MaxTextExtent);
break;
}
}
if (image->matte != MagickFalse)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n",
type);
(void) WriteBlobString(image,buffer);
}
/*
Convert to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)),
ScaleQuantumToChar(GetPixelGreen(p)),
ScaleQuantumToChar(GetPixelBlue(p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)),
ScaleQuantumToShort(GetPixelGreen(p)),
ScaleQuantumToShort(GetPixelBlue(p)));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)),
ScaleQuantumToLong(GetPixelGreen(p)),
ScaleQuantumToLong(GetPixelBlue(p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 32)
pixel=ScaleQuantumToLong(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1612'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
format,
magick[MagickPathExtent];
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
Quantum
index;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MagickPathExtent);
max_value=GetQuantumRange(image->depth);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MagickPathExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MagickPathExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent);
if (IdentifyImageMonochrome(image,exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MagickPathExtent);
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"TUPLTYPE %s\nENDHDR\n",type);
(void) WriteBlobString(image,buffer);
}
/*
Convert runextent encoded to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)),
ScaleQuantumToChar(GetPixelGreen(image,p)),
ScaleQuantumToChar(GetPixelBlue(image,p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)),
ScaleQuantumToShort(GetPixelGreen(image,p)),
ScaleQuantumToShort(GetPixelBlue(image,p)));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)),
ScaleQuantumToLong(GetPixelGreen(image,p)),
ScaleQuantumToLong(GetPixelBlue(image,p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
register unsigned char
*pixels;
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
register unsigned char
*pixels;
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)),
max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToLong(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
register unsigned char
*pixels;
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register unsigned char
*pixels;
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
register unsigned char
*pixels;
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1613'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
format,
magick[MaxTextExtent];
const char
*value;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*pixels,
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
max_value=GetQuantumRange(image->depth);
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MaxTextExtent);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,&image->exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MaxTextExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,&image->exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MaxTextExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent);
if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MaxTextExtent);
break;
}
}
if (image->matte != MagickFalse)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n",
type);
(void) WriteBlobString(image,buffer);
}
/*
Convert to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToLong(index));
extent=(size_t) count;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
(void) strncpy((char *) q,buffer,extent);
q+=extent;
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)),
ScaleQuantumToChar(GetPixelGreen(p)),
ScaleQuantumToChar(GetPixelBlue(p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)),
ScaleQuantumToShort(GetPixelGreen(p)),
ScaleQuantumToShort(GetPixelBlue(p)));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)),
ScaleQuantumToLong(GetPixelGreen(p)),
ScaleQuantumToLong(GetPixelBlue(p)));
extent=(size_t) count;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
(void) strncpy((char *) q,buffer,extent);
q+=extent;
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 32)
pixel=ScaleQuantumToLong(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1614'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire)
{
unsigned int section, name_len, x, errors, num_chunks;
unsigned char buf[0x54], *chunk = NULL, *name, *p, *end;
struct mschmd_file *fi, *link = NULL;
off_t offset, length;
int num_entries;
/* initialise pointers */
chm->files = NULL;
chm->sysfiles = NULL;
chm->chunk_cache = NULL;
chm->sec0.base.chm = chm;
chm->sec0.base.id = 0;
chm->sec1.base.chm = chm;
chm->sec1.base.id = 1;
chm->sec1.content = NULL;
chm->sec1.control = NULL;
chm->sec1.spaninfo = NULL;
chm->sec1.rtable = NULL;
/* read the first header */
if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check ITSF signature */
if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) {
return MSPACK_ERR_SIGNATURE;
}
/* check both header GUIDs */
if (memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) {
D(("incorrect GUIDs"))
return MSPACK_ERR_SIGNATURE;
}
chm->version = EndGetI32(&buf[chmhead_Version]);
chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]);
chm->language = EndGetI32(&buf[chmhead_LanguageID]);
if (chm->version > 3) {
sys->message(fh, "WARNING; CHM version > 3");
}
/* read the header section table */
if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) {
return MSPACK_ERR_READ;
}
/* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files.
* The offset will be corrected later, once HS1 is read.
*/
if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) ||
read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) ||
read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh))
{
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 0 */
if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 0 */
if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) {
return MSPACK_ERR_READ;
}
if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) {
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 1 */
if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 1 */
if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) {
return MSPACK_ERR_READ;
}
chm->dir_offset = sys->tell(fh);
chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]);
chm->density = EndGetI32(&buf[chmhs1_Density]);
chm->depth = EndGetI32(&buf[chmhs1_Depth]);
chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]);
chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]);
chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]);
chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]);
if (chm->version < 3) {
/* versions before 3 don't have chmhst3_OffsetCS0 */
chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks);
}
/* check if content offset or file size is wrong */
if (chm->sec0.offset > chm->length) {
D(("content section begins after file has ended"))
return MSPACK_ERR_DATAFORMAT;
}
/* ensure there are chunks and that chunk size is
* large enough for signature and num_entries */
if (chm->chunk_size < (pmgl_Entries + 2)) {
D(("chunk size not large enough"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->num_chunks == 0) {
D(("no chunks"))
return MSPACK_ERR_DATAFORMAT;
}
/* The chunk_cache data structure is not great; large values for num_chunks
* or num_chunks*chunk_size can exhaust all memory. Until a better chunk
* cache is implemented, put arbitrary limits on num_chunks and chunk size.
*/
if (chm->num_chunks > 100000) {
D(("more than 100,000 chunks"))
return MSPACK_ERR_DATAFORMAT;
}
if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) {
D(("chunks larger than entire file"))
return MSPACK_ERR_DATAFORMAT;
}
/* common sense checks on header section 1 fields */
if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) {
sys->message(fh, "WARNING; chunk size is not a power of two");
}
if (chm->first_pmgl != 0) {
sys->message(fh, "WARNING; first PMGL chunk is not zero");
}
if (chm->first_pmgl > chm->last_pmgl) {
D(("first pmgl chunk is after last pmgl chunk"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) {
D(("index_root outside valid range"))
return MSPACK_ERR_DATAFORMAT;
}
/* if we are doing a quick read, stop here! */
if (!entire) {
return MSPACK_ERR_OK;
}
/* seek to the first PMGL chunk, and reduce the number of chunks to read */
if ((x = chm->first_pmgl) != 0) {
if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) {
return MSPACK_ERR_SEEK;
}
}
num_chunks = chm->last_pmgl - x + 1;
if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) {
return MSPACK_ERR_NOMEMORY;
}
/* read and process all chunks from FirstPMGL to LastPMGL */
errors = 0;
while (num_chunks--) {
/* read next chunk */
if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) {
sys->free(chunk);
return MSPACK_ERR_READ;
}
/* process only directory (PMGL) chunks */
if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue;
if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) {
sys->message(fh, "WARNING; PMGL quickref area is too small");
}
if (EndGetI32(&chunk[pmgl_QuickRefSize]) >
((int)chm->chunk_size - pmgl_Entries))
{
sys->message(fh, "WARNING; PMGL quickref area is too large");
}
p = &chunk[pmgl_Entries];
end = &chunk[chm->chunk_size - 2];
num_entries = EndGetI16(end);
while (num_entries--) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
name = p; p += name_len;
READ_ENCINT(section);
READ_ENCINT(offset);
READ_ENCINT(length);
/* ignore blank or one-char (e.g. "/") filenames we'd return as blank */
if (name_len < 2 || !name[0] || !name[1]) continue;
/* empty files and directory names are stored as a file entry at
* offset 0 with length 0. We want to keep empty files, but not
* directory names, which end with a "/" */
if ((offset == 0) && (length == 0)) {
if ((name_len > 0) && (name[name_len-1] == '/')) continue;
}
if (section > 1) {
sys->message(fh, "invalid section number '%u'.", section);
continue;
}
if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) {
sys->free(chunk);
return MSPACK_ERR_NOMEMORY;
}
fi->next = NULL;
fi->filename = (char *) &fi[1];
fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0)
: (struct mschmd_section *) (&chm->sec1));
fi->offset = offset;
fi->length = length;
sys->copy(name, fi->filename, (size_t) name_len);
fi->filename[name_len] = '\0';
if (name[0] == ':' && name[1] == ':') {
/* system file */
if (memcmp(&name[2], &content_name[2], 31L) == 0) {
if (memcmp(&name[33], &content_name[33], 8L) == 0) {
chm->sec1.content = fi;
}
else if (memcmp(&name[33], &control_name[33], 11L) == 0) {
chm->sec1.control = fi;
}
else if (memcmp(&name[33], &spaninfo_name[33], 8L) == 0) {
chm->sec1.spaninfo = fi;
}
else if (memcmp(&name[33], &rtable_name[33], 72L) == 0) {
chm->sec1.rtable = fi;
}
}
fi->next = chm->sysfiles;
chm->sysfiles = fi;
}
else {
/* normal file */
if (link) link->next = fi; else chm->files = fi;
link = fi;
}
}
/* this is reached either when num_entries runs out, or if
* reading data from the chunk reached a premature end of chunk */
chunk_end:
if (num_entries >= 0) {
D(("chunk ended before all entries could be read"))
errors++;
}
}
sys->free(chunk);
return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'length checks when looking for control files'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport MagickBooleanType AnnotateImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
char
*p,
primitive[MagickPathExtent],
*text,
**textlist;
DrawInfo
*annotate,
*annotate_info;
GeometryInfo
geometry_info;
MagickBooleanType
status;
PointInfo
offset;
RectangleInfo
geometry;
register ssize_t
i;
TypeMetric
metrics;
size_t
height,
number_lines;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->text == (char *) NULL)
return(MagickFalse);
if (*draw_info->text == '\0')
return(MagickTrue);
annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info);
text=annotate->text;
annotate->text=(char *) NULL;
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
number_lines=1;
for (p=text; *p != '\0'; p++)
if (*p == '\n')
number_lines++;
textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist));
if (textlist == (char **) NULL)
return(MagickFalse);
p=text;
for (i=0; i < number_lines; i++)
{
char
*q;
textlist[i]=p;
for (q=p; *q != '\0'; q++)
if ((*q == '\r') || (*q == '\n'))
break;
if (*q == '\r')
{
*q='\0';
q++;
}
*q='\0';
p=q+1;
}
textlist[i]=(char *) NULL;
SetGeometry(image,&geometry);
SetGeometryInfo(&geometry_info);
if (annotate_info->geometry != (char *) NULL)
{
(void) ParsePageGeometry(image,annotate_info->geometry,&geometry,
exception);
(void) ParseGeometry(annotate_info->geometry,&geometry_info);
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
(void) memset(&metrics,0,sizeof(metrics));
for (i=0; textlist[i] != (char *) NULL; i++)
{
if (*textlist[i] == '\0')
continue;
/*
Position text relative to image.
*/
annotate_info->affine.tx=geometry_info.xi-image->page.x;
annotate_info->affine.ty=geometry_info.psi-image->page.y;
(void) CloneString(&annotate->text,textlist[i]);
if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity))
(void) GetTypeMetrics(image,annotate,&metrics,exception);
height=(ssize_t) (metrics.ascent-metrics.descent+
draw_info->interline_spacing+0.5);
switch (annotate->gravity)
{
case UndefinedGravity:
default:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case NorthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent;
break;
}
case NorthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width/2.0;
break;
}
case NorthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+annotate_info->affine.ry*
(metrics.ascent+metrics.descent)-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width;
break;
}
case WestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case CenterGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
break;
}
case EastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+
annotate_info->affine.ry*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case SouthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height-annotate_info->affine.ry*
(number_lines-1.0)*height;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0-
annotate_info->affine.ry*(number_lines-1.0)*height/2.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width-
annotate_info->affine.ry*(number_lines-1.0)*height-1.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
}
switch (annotate->align)
{
case LeftAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case CenterAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0;
break;
}
case RightAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width;
break;
}
default:
break;
}
if (draw_info->undercolor.alpha != TransparentAlpha)
{
DrawInfo
*undercolor_info;
/*
Text box.
*/
undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL);
undercolor_info->fill=draw_info->undercolor;
undercolor_info->affine=draw_info->affine;
undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent;
undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent;
(void) FormatLocaleString(primitive,MagickPathExtent,
"rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height);
(void) CloneString(&undercolor_info->primitive,primitive);
(void) DrawImage(image,undercolor_info,exception);
(void) DestroyDrawInfo(undercolor_info);
}
annotate_info->affine.tx=offset.x;
annotate_info->affine.ty=offset.y;
(void) FormatLocaleString(primitive,MagickPathExtent,"stroke-width %g "
"line 0,0 %g,0",metrics.underline_thickness,metrics.width);
if (annotate->decorate == OverlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+
metrics.descent-metrics.underline_position));
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
else
if (annotate->decorate == UnderlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*
metrics.underline_position);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
/*
Annotate image with text.
*/
status=RenderType(image,annotate,&offset,&metrics,exception);
if (status == MagickFalse)
break;
if (annotate->decorate == LineThroughDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(height+
metrics.underline_position+metrics.descent)/2.0);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
}
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
return(status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1589'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static PixelChannels **AcquirePixelThreadSet(const Image *image)
{
PixelChannels
**pixels;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(PixelChannels **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (PixelChannels **) NULL)
return((PixelChannels **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
register ssize_t
j;
pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns,
sizeof(**pixels));
if (pixels[i] == (PixelChannels *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) image->columns; j++)
{
register ssize_t
k;
for (k=0; k < MaxPixelChannels; k++)
pixels[i][j].channel[k]=0.0;
}
}
return(pixels);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1586'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline Quantum GetPixelChannel(const Image *magick_restrict image,
const PixelChannel channel,const Quantum *magick_restrict pixel)
{
if (image->channel_map[channel].traits == UndefinedPixelTrait)
return((Quantum) 0);
return(pixel[image->channel_map[channel].offset]);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1610'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline Quantum GetPixelChannel(const Image *magick_restrict image,
const PixelChannel channel,const Quantum *magick_restrict pixel)
{
if (image->channel_map[image->channel_map[channel].offset].traits == UndefinedPixelTrait)
return((Quantum) 0);
return(pixel[image->channel_map[channel].offset]);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1611'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const double bias,
ExceptionInfo *exception)
{
#define AdaptiveThresholdImageTag "AdaptiveThreshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickSizeType
number_pixels;
ssize_t
y;
/*
Initialize threshold image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (width == 0)
return(threshold_image);
status=SetImageStorageClass(threshold_image,DirectClass,exception);
if (status == MagickFalse)
{
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Threshold image.
*/
status=MagickTrue;
progress=0;
number_pixels=(MagickSizeType) width*height;
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
channel_bias[MaxPixelChannels],
channel_sum[MaxPixelChannels];
register const Quantum
*magick_restrict p,
*magick_restrict pixels;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
center,
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(height/2L),image->columns+width,height,exception);
q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+
GetPixelChannels(image)*(width/2);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
pixels=p;
channel_bias[channel]=0.0;
channel_sum[channel]=0.0;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
channel_bias[channel]+=pixels[i];
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image);
}
pixels+=GetPixelChannels(image)*image->columns;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
mean;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
channel_sum[channel]-=channel_bias[channel];
channel_bias[channel]=0.0;
pixels=p;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias[channel]+=pixels[i];
pixels+=(width-1)*GetPixelChannels(image);
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image)*(image->columns+1);
}
mean=(double) (channel_sum[channel]/number_pixels+bias);
SetPixelChannel(threshold_image,channel,(Quantum) ((double)
p[center+i] <= mean ? 0 : QuantumRange),q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(threshold_image);
}
if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_image->type=image->type;
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1609'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const double bias,
ExceptionInfo *exception)
{
#define AdaptiveThresholdImageTag "AdaptiveThreshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickSizeType
number_pixels;
ssize_t
y;
/*
Initialize threshold image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
status=SetImageStorageClass(threshold_image,DirectClass,exception);
if (status == MagickFalse)
{
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Threshold image.
*/
status=MagickTrue;
progress=0;
number_pixels=(MagickSizeType) width*height;
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
channel_bias[MaxPixelChannels],
channel_sum[MaxPixelChannels];
register const Quantum
*magick_restrict p,
*magick_restrict pixels;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
center,
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(height/2L),image->columns+width,height,exception);
q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+
GetPixelChannels(image)*(width/2);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
pixels=p;
channel_bias[channel]=0.0;
channel_sum[channel]=0.0;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
channel_bias[channel]+=pixels[i];
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image);
}
pixels+=GetPixelChannels(image)*image->columns;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
mean;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
channel_sum[channel]-=channel_bias[channel];
channel_bias[channel]=0.0;
pixels=p;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias[channel]+=pixels[i];
pixels+=(width-1)*GetPixelChannels(image);
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image)*(image->columns+1);
}
mean=(double) (channel_sum[channel]/number_pixels+bias);
SetPixelChannel(threshold_image,channel,(Quantum) ((double)
p[center+i] <= mean ? 0 : QuantumRange),q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(threshold_image);
}
if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_image->type=image->type;
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1608'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void ptrace_link(struct task_struct *child, struct task_struct *new_parent)
{
rcu_read_lock();
__ptrace_link(child, new_parent, __task_cred(new_parent));
rcu_read_unlock();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264', 'CWE-269'], 'message': 'ptrace: Fix ->ptracer_cred handling for PTRACE_TRACEME
Fix two issues:
When called for PTRACE_TRACEME, ptrace_link() would obtain an RCU
reference to the parent's objective credentials, then give that pointer
to get_cred(). However, the object lifetime rules for things like
struct cred do not permit unconditionally turning an RCU reference into
a stable reference.
PTRACE_TRACEME records the parent's credentials as if the parent was
acting as the subject, but that's not the case. If a malicious
unprivileged child uses PTRACE_TRACEME and the parent is privileged, and
at a later point, the parent process becomes attacker-controlled
(because it drops privileges and calls execve()), the attacker ends up
with control over two processes with a privileged ptrace relationship,
which can be abused to ptrace a suid binary and obtain root privileges.
Fix both of these by always recording the credentials of the process
that is requesting the creation of the ptrace relationship:
current_cred() can't change under us, and current is the proper subject
for access control.
This change is theoretically userspace-visible, but I am not aware of
any code that it will actually break.
Fixes: 64b875f7ac8a ("ptrace: Capture the ptracer's creds not PT_PTRACE_CAP")
Signed-off-by: Jann Horn <[email protected]>
Acked-by: Oleg Nesterov <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadVIDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ClientName "montage"
char
**filelist,
*label,
**list;
Image
*image,
*images,
*montage_image,
*next_image,
*thumbnail_image;
ImageInfo
*read_info;
int
number_files;
MagickBooleanType
status;
MontageInfo
*montage_info;
RectangleInfo
geometry;
register ssize_t
i;
/*
Expand the filename.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
list=(char **) AcquireMagickMemory(sizeof(*filelist));
if (list == (char **) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
list[0]=ConstantString(image_info->filename);
filelist=list;
number_files=1;
status=ExpandFilenames(&number_files,&filelist);
list[0]=DestroyString(list[0]);
list=(char **) RelinquishMagickMemory(list);
if ((status == MagickFalse) || (number_files == 0))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImage(image);
/*
Read each image and convert them to a tile.
*/
images=NewImageList();
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,
(void *) NULL);
if (read_info->size == (char *) NULL)
(void) CloneString(&read_info->size,DefaultTileGeometry);
for (i=0; i < (ssize_t) number_files; i++)
{
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"name: %s",
filelist[i]);
(void) CopyMagickString(read_info->filename,filelist[i],MaxTextExtent);
filelist[i]=DestroyString(filelist[i]);
*read_info->magick='\0';
next_image=ReadImage(read_info,exception);
CatchException(exception);
if (next_image == (Image *) NULL)
break;
label=InterpretImageProperties(image_info,next_image,DefaultTileLabel);
(void) SetImageProperty(next_image,"label",label);
label=DestroyString(label);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"geometry: %.20gx%.20g",(double) next_image->columns,(double)
next_image->rows);
SetGeometry(next_image,&geometry);
(void) ParseMetaGeometry(read_info->size,&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
thumbnail_image=ThumbnailImage(next_image,geometry.width,geometry.height,
exception);
if (thumbnail_image != (Image *) NULL)
{
next_image=DestroyImage(next_image);
next_image=thumbnail_image;
}
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"thumbnail geometry: %.20gx%.20g",(double) next_image->columns,(double)
next_image->rows);
AppendImageToList(&images,next_image);
status=SetImageProgress(images,LoadImagesTag,i,number_files);
if (status == MagickFalse)
break;
}
read_info=DestroyImageInfo(read_info);
filelist=(char **) RelinquishMagickMemory(filelist);
if (images == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
/*
Create the visual image directory.
*/
montage_info=CloneMontageInfo(image_info,(MontageInfo *) NULL);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"creating montage");
montage_image=MontageImageList(image_info,montage_info,
GetFirstImageInList(images),exception);
montage_info=DestroyMontageInfo(montage_info);
images=DestroyImageList(images);
return(montage_image);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1515'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadVIDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ClientName "montage"
char
**filelist,
*label,
**list;
Image
*image,
*images,
*montage_image,
*next_image,
*thumbnail_image;
ImageInfo
*read_info;
int
number_files;
MagickBooleanType
status;
MontageInfo
*montage_info;
RectangleInfo
geometry;
register ssize_t
i;
/*
Expand the filename.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
list=(char **) AcquireMagickMemory(sizeof(*filelist));
if (list == (char **) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
list[0]=ConstantString(image_info->filename);
filelist=list;
number_files=1;
status=ExpandFilenames(&number_files,&filelist);
list[0]=DestroyString(list[0]);
list=(char **) RelinquishMagickMemory(list);
if ((status == MagickFalse) || (number_files == 0))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImage(image);
/*
Read each image and convert them to a tile.
*/
images=NewImageList();
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,
(void *) NULL);
if (read_info->size == (char *) NULL)
(void) CloneString(&read_info->size,DefaultTileGeometry);
for (i=0; i < (ssize_t) number_files; i++)
{
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"name: %s",
filelist[i]);
(void) CopyMagickString(read_info->filename,filelist[i],MagickPathExtent);
filelist[i]=DestroyString(filelist[i]);
*read_info->magick='\0';
next_image=ReadImage(read_info,exception);
CatchException(exception);
if (next_image == (Image *) NULL)
break;
label=InterpretImageProperties((ImageInfo *) image_info,next_image,
DefaultTileLabel,exception);
(void) SetImageProperty(next_image,"label",label,exception);
label=DestroyString(label);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"geometry: %.20gx%.20g",(double) next_image->columns,(double)
next_image->rows);
SetGeometry(next_image,&geometry);
(void) ParseMetaGeometry(read_info->size,&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
thumbnail_image=ThumbnailImage(next_image,geometry.width,geometry.height,
exception);
if (thumbnail_image != (Image *) NULL)
{
next_image=DestroyImage(next_image);
next_image=thumbnail_image;
}
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"thumbnail geometry: %.20gx%.20g",(double) next_image->columns,(double)
next_image->rows);
AppendImageToList(&images,next_image);
status=SetImageProgress(images,LoadImagesTag,i,number_files);
if (status == MagickFalse)
break;
}
read_info=DestroyImageInfo(read_info);
filelist=(char **) RelinquishMagickMemory(filelist);
if (images == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
/*
Create the visual image directory.
*/
montage_info=CloneMontageInfo(image_info,(MontageInfo *) NULL);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"creating montage");
montage_image=MontageImageList(image_info,montage_info,
GetFirstImageInList(images),exception);
montage_info=DestroyMontageInfo(montage_info);
images=DestroyImageList(images);
return(montage_image);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1515'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickBooleanType WriteDPXImage(const ImageInfo *image_info,
Image *image)
{
const char
*value;
const StringInfo
*profile;
DPXInfo
dpx;
MagickBooleanType
status;
MagickOffsetType
offset;
MagickStatusType
flags;
GeometryInfo
geometry_info;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register const PixelPacket
*p;
register ssize_t
i;
ssize_t
count,
horizontal_factor,
vertical_factor,
y;
size_t
channels,
extent;
time_t
seconds;
unsigned char
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
horizontal_factor=4;
vertical_factor=4;
if (image_info->sampling_factor != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(image_info->sampling_factor,&geometry_info);
horizontal_factor=(ssize_t) geometry_info.rho;
vertical_factor=(ssize_t) geometry_info.sigma;
if ((flags & SigmaValue) == 0)
vertical_factor=horizontal_factor;
if ((horizontal_factor != 1) && (horizontal_factor != 2) &&
(horizontal_factor != 4) && (vertical_factor != 1) &&
(vertical_factor != 2) && (vertical_factor != 4))
ThrowWriterException(CorruptImageError,"UnexpectedSamplingFactor");
}
if ((image->colorspace == YCbCrColorspace) &&
((horizontal_factor == 2) || (vertical_factor == 2)))
if ((image->columns % 2) != 0)
image->columns++;
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Write file header.
*/
(void) memset(&dpx,0,sizeof(dpx));
offset=0;
dpx.file.magic=0x53445058U;
offset+=WriteBlobLong(image,dpx.file.magic);
dpx.file.image_offset=0x2000U;
profile=GetImageProfile(image,"dpx:user-data");
if (profile != (StringInfo *) NULL)
{
if (GetStringInfoLength(profile) > 1048576)
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
dpx.file.image_offset+=(unsigned int) GetStringInfoLength(profile);
dpx.file.image_offset=(((dpx.file.image_offset+0x2000-1)/0x2000)*0x2000);
}
offset+=WriteBlobLong(image,dpx.file.image_offset);
(void) strncpy(dpx.file.version,"V2.0",sizeof(dpx.file.version)-1);
offset+=WriteBlob(image,8,(unsigned char *) &dpx.file.version);
channels=1;
if (IsGrayImage(image,&image->exception) == MagickFalse)
channels=3;
if (image->matte != MagickFalse)
channels++;
dpx.file.file_size=(unsigned int) (channels*image->columns*image->rows+
dpx.file.image_offset);
offset+=WriteBlobLong(image,dpx.file.file_size);
dpx.file.ditto_key=1U; /* new frame */
offset+=WriteBlobLong(image,dpx.file.ditto_key);
dpx.file.generic_size=0x00000680U;
offset+=WriteBlobLong(image,dpx.file.generic_size);
dpx.file.industry_size=0x00000180U;
offset+=WriteBlobLong(image,dpx.file.industry_size);
dpx.file.user_size=0;
if (profile != (StringInfo *) NULL)
{
dpx.file.user_size+=(unsigned int) GetStringInfoLength(profile);
dpx.file.user_size=(((dpx.file.user_size+0x2000-1)/0x2000)*0x2000);
}
offset+=WriteBlobLong(image,dpx.file.user_size);
value=GetDPXProperty(image,"dpx:file.filename");
if (value != (const char *) NULL)
(void) strncpy(dpx.file.filename,value,sizeof(dpx.file.filename)-1);
offset+=WriteBlob(image,sizeof(dpx.file.filename),(unsigned char *)
dpx.file.filename);
seconds=time((time_t *) NULL);
(void) FormatMagickTime(seconds,sizeof(dpx.file.timestamp),
dpx.file.timestamp);
offset+=WriteBlob(image,sizeof(dpx.file.timestamp),(unsigned char *)
dpx.file.timestamp);
(void) strncpy(dpx.file.creator,MagickAuthoritativeURL,
sizeof(dpx.file.creator)-1);
value=GetDPXProperty(image,"dpx:file.creator");
if (value != (const char *) NULL)
(void) strncpy(dpx.file.creator,value,sizeof(dpx.file.creator)-1);
offset+=WriteBlob(image,sizeof(dpx.file.creator),(unsigned char *)
dpx.file.creator);
value=GetDPXProperty(image,"dpx:file.project");
if (value != (const char *) NULL)
(void) strncpy(dpx.file.project,value,sizeof(dpx.file.project)-1);
offset+=WriteBlob(image,sizeof(dpx.file.project),(unsigned char *)
dpx.file.project);
value=GetDPXProperty(image,"dpx:file.copyright");
if (value != (const char *) NULL)
(void) strncpy(dpx.file.copyright,value,sizeof(dpx.file.copyright)-1);
offset+=WriteBlob(image,sizeof(dpx.file.copyright),(unsigned char *)
dpx.file.copyright);
dpx.file.encrypt_key=(~0U);
offset+=WriteBlobLong(image,dpx.file.encrypt_key);
offset+=WriteBlob(image,sizeof(dpx.file.reserve),(unsigned char *)
dpx.file.reserve);
/*
Write image header.
*/
switch (image->orientation)
{
default:
case TopLeftOrientation: dpx.image.orientation=0; break;
case TopRightOrientation: dpx.image.orientation=1; break;
case BottomLeftOrientation: dpx.image.orientation=2; break;
case BottomRightOrientation: dpx.image.orientation=3; break;
case LeftTopOrientation: dpx.image.orientation=4; break;
case RightTopOrientation: dpx.image.orientation=5; break;
case LeftBottomOrientation: dpx.image.orientation=6; break;
case RightBottomOrientation: dpx.image.orientation=7; break;
}
offset+=WriteBlobShort(image,dpx.image.orientation);
dpx.image.number_elements=1;
offset+=WriteBlobShort(image,dpx.image.number_elements);
if ((image->columns != (unsigned int) image->columns) ||
(image->rows != (unsigned int) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
offset+=WriteBlobLong(image,(unsigned int) image->columns);
offset+=WriteBlobLong(image,(unsigned int) image->rows);
for (i=0; i < 8; i++)
{
dpx.image.image_element[i].data_sign=0U;
offset+=WriteBlobLong(image,dpx.image.image_element[i].data_sign);
dpx.image.image_element[i].low_data=0U;
offset+=WriteBlobLong(image,dpx.image.image_element[i].low_data);
dpx.image.image_element[i].low_quantity=0.0f;
offset+=WriteBlobFloat(image,dpx.image.image_element[i].low_quantity);
dpx.image.image_element[i].high_data=0U;
offset+=WriteBlobLong(image,dpx.image.image_element[i].high_data);
dpx.image.image_element[i].high_quantity=0.0f;
offset+=WriteBlobFloat(image,dpx.image.image_element[i].high_quantity);
dpx.image.image_element[i].descriptor=0;
if (i == 0)
switch (image->colorspace)
{
case Rec601YCbCrColorspace:
case Rec709YCbCrColorspace:
case YCbCrColorspace:
{
dpx.image.image_element[i].descriptor=CbYCr444ComponentType;
if (image->matte != MagickFalse)
dpx.image.image_element[i].descriptor=CbYCrA4444ComponentType;
break;
}
default:
{
dpx.image.image_element[i].descriptor=RGBComponentType;
if (image->matte != MagickFalse)
dpx.image.image_element[i].descriptor=RGBAComponentType;
if ((image_info->type != TrueColorType) &&
(image->matte == MagickFalse) &&
(SetImageGray(image,&image->exception) != MagickFalse))
dpx.image.image_element[i].descriptor=LumaComponentType;
break;
}
}
offset+=WriteBlobByte(image,dpx.image.image_element[i].descriptor);
dpx.image.image_element[i].transfer_characteristic=0;
if (image->colorspace == LogColorspace)
dpx.image.image_element[0].transfer_characteristic=
PrintingDensityColorimetric;
offset+=WriteBlobByte(image,
dpx.image.image_element[i].transfer_characteristic);
dpx.image.image_element[i].colorimetric=0;
offset+=WriteBlobByte(image,dpx.image.image_element[i].colorimetric);
dpx.image.image_element[i].bit_size=0;
if (i == 0)
dpx.image.image_element[i].bit_size=(unsigned char) image->depth;
offset+=WriteBlobByte(image,dpx.image.image_element[i].bit_size);
dpx.image.image_element[i].packing=0;
if ((image->depth == 10) || (image->depth == 12))
dpx.image.image_element[i].packing=1;
offset+=WriteBlobShort(image,dpx.image.image_element[i].packing);
dpx.image.image_element[i].encoding=0;
offset+=WriteBlobShort(image,dpx.image.image_element[i].encoding);
dpx.image.image_element[i].data_offset=0U;
if (i == 0)
dpx.image.image_element[i].data_offset=dpx.file.image_offset;
offset+=WriteBlobLong(image,dpx.image.image_element[i].data_offset);
dpx.image.image_element[i].end_of_line_padding=0U;
offset+=WriteBlobLong(image,dpx.image.image_element[i].end_of_line_padding);
offset+=WriteBlobLong(image,
dpx.image.image_element[i].end_of_image_padding);
offset+=WriteBlob(image,sizeof(dpx.image.image_element[i].description),
(unsigned char *) dpx.image.image_element[i].description);
}
offset+=WriteBlob(image,sizeof(dpx.image.reserve),(unsigned char *)
dpx.image.reserve);
/*
Write orientation header.
*/
if ((image->rows != image->magick_rows) ||
(image->columns != image->magick_columns))
{
/*
These properties are not valid if image size changed.
*/
(void) DeleteImageProperty(image,"dpx:orientation.x_offset");
(void) DeleteImageProperty(image,"dpx:orientation.y_offset");
(void) DeleteImageProperty(image,"dpx:orientation.x_center");
(void) DeleteImageProperty(image,"dpx:orientation.y_center");
(void) DeleteImageProperty(image,"dpx:orientation.x_size");
(void) DeleteImageProperty(image,"dpx:orientation.y_size");
}
dpx.orientation.x_offset=0U;
value=GetDPXProperty(image,"dpx:orientation.x_offset");
if (value != (const char *) NULL)
dpx.orientation.x_offset=(unsigned int) StringToUnsignedLong(value);
offset+=WriteBlobLong(image,dpx.orientation.x_offset);
dpx.orientation.y_offset=0U;
value=GetDPXProperty(image,"dpx:orientation.y_offset");
if (value != (const char *) NULL)
dpx.orientation.y_offset=(unsigned int) StringToUnsignedLong(value);
offset+=WriteBlobLong(image,dpx.orientation.y_offset);
dpx.orientation.x_center=0.0f;
value=GetDPXProperty(image,"dpx:orientation.x_center");
if (value != (const char *) NULL)
dpx.orientation.x_center=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.orientation.x_center);
dpx.orientation.y_center=0.0f;
value=GetDPXProperty(image,"dpx:orientation.y_center");
if (value != (const char *) NULL)
dpx.orientation.y_center=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.orientation.y_center);
dpx.orientation.x_size=0U;
value=GetDPXProperty(image,"dpx:orientation.x_size");
if (value != (const char *) NULL)
dpx.orientation.x_size=(unsigned int) StringToUnsignedLong(value);
offset+=WriteBlobLong(image,dpx.orientation.x_size);
dpx.orientation.y_size=0U;
value=GetDPXProperty(image,"dpx:orientation.y_size");
if (value != (const char *) NULL)
dpx.orientation.y_size=(unsigned int) StringToUnsignedLong(value);
offset+=WriteBlobLong(image,dpx.orientation.y_size);
value=GetDPXProperty(image,"dpx:orientation.filename");
if (value != (const char *) NULL)
(void) strncpy(dpx.orientation.filename,value,
sizeof(dpx.orientation.filename)-1);
offset+=WriteBlob(image,sizeof(dpx.orientation.filename),(unsigned char *)
dpx.orientation.filename);
offset+=WriteBlob(image,sizeof(dpx.orientation.timestamp),(unsigned char *)
dpx.orientation.timestamp);
value=GetDPXProperty(image,"dpx:orientation.device");
if (value != (const char *) NULL)
(void) strncpy(dpx.orientation.device,value,
sizeof(dpx.orientation.device)-1);
offset+=WriteBlob(image,sizeof(dpx.orientation.device),(unsigned char *)
dpx.orientation.device);
value=GetDPXProperty(image,"dpx:orientation.serial");
if (value != (const char *) NULL)
(void) strncpy(dpx.orientation.serial,value,
sizeof(dpx.orientation.serial)-1);
offset+=WriteBlob(image,sizeof(dpx.orientation.serial),(unsigned char *)
dpx.orientation.serial);
for (i=0; i < 4; i++)
dpx.orientation.border[i]=0;
value=GetDPXProperty(image,"dpx:orientation.border");
if (value != (const char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
dpx.orientation.border[0]=(unsigned short) (geometry_info.rho+0.5);
dpx.orientation.border[1]=(unsigned short) (geometry_info.sigma+0.5);
dpx.orientation.border[2]=(unsigned short) (geometry_info.xi+0.5);
dpx.orientation.border[3]=(unsigned short) (geometry_info.psi+0.5);
}
for (i=0; i < 4; i++)
offset+=WriteBlobShort(image,dpx.orientation.border[i]);
for (i=0; i < 2; i++)
dpx.orientation.aspect_ratio[i]=0U;
value=GetDPXProperty(image,"dpx:orientation.aspect_ratio");
if (value != (const char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
dpx.orientation.aspect_ratio[0]=(unsigned int) (geometry_info.rho+0.5);
dpx.orientation.aspect_ratio[1]=(unsigned int) (geometry_info.sigma+0.5);
}
for (i=0; i < 2; i++)
offset+=WriteBlobLong(image,dpx.orientation.aspect_ratio[i]);
offset+=WriteBlob(image,sizeof(dpx.orientation.reserve),(unsigned char *)
dpx.orientation.reserve);
/*
Write film header.
*/
(void) memset(dpx.film.id,0,sizeof(dpx.film.id));
value=GetDPXProperty(image,"dpx:film.id");
if (value != (const char *) NULL)
(void) strncpy(dpx.film.id,value,sizeof(dpx.film.id)-1);
offset+=WriteBlob(image,sizeof(dpx.film.id),(unsigned char *) dpx.film.id);
(void) memset(dpx.film.type,0,sizeof(dpx.film.type));
value=GetDPXProperty(image,"dpx:film.type");
if (value != (const char *) NULL)
(void) strncpy(dpx.film.type,value,sizeof(dpx.film.type)-1);
offset+=WriteBlob(image,sizeof(dpx.film.type),(unsigned char *)
dpx.film.type);
(void) memset(dpx.film.offset,0,sizeof(dpx.film.offset));
value=GetDPXProperty(image,"dpx:film.offset");
if (value != (const char *) NULL)
(void) strncpy(dpx.film.offset,value,sizeof(dpx.film.offset)-1);
offset+=WriteBlob(image,sizeof(dpx.film.offset),(unsigned char *)
dpx.film.offset);
(void) memset(dpx.film.prefix,0,sizeof(dpx.film.prefix));
value=GetDPXProperty(image,"dpx:film.prefix");
if (value != (const char *) NULL)
(void) strncpy(dpx.film.prefix,value,sizeof(dpx.film.prefix)-1);
offset+=WriteBlob(image,sizeof(dpx.film.prefix),(unsigned char *)
dpx.film.prefix);
(void) memset(dpx.film.count,0,sizeof(dpx.film.count));
value=GetDPXProperty(image,"dpx:film.count");
if (value != (const char *) NULL)
(void) strncpy(dpx.film.count,value,sizeof(dpx.film.count)-1);
offset+=WriteBlob(image,sizeof(dpx.film.count),(unsigned char *)
dpx.film.count);
(void) memset(dpx.film.format,0,sizeof(dpx.film.format));
value=GetDPXProperty(image,"dpx:film.format");
if (value != (const char *) NULL)
(void) strncpy(dpx.film.format,value,sizeof(dpx.film.format)-1);
offset+=WriteBlob(image,sizeof(dpx.film.format),(unsigned char *)
dpx.film.format);
dpx.film.frame_position=0U;
value=GetDPXProperty(image,"dpx:film.frame_position");
if (value != (const char *) NULL)
dpx.film.frame_position=(unsigned int) StringToUnsignedLong(value);
offset+=WriteBlobLong(image,dpx.film.frame_position);
dpx.film.sequence_extent=0U;
value=GetDPXProperty(image,"dpx:film.sequence_extent");
if (value != (const char *) NULL)
dpx.film.sequence_extent=(unsigned int) StringToUnsignedLong(value);
offset+=WriteBlobLong(image,dpx.film.sequence_extent);
dpx.film.held_count=0U;
value=GetDPXProperty(image,"dpx:film.held_count");
if (value != (const char *) NULL)
dpx.film.held_count=(unsigned int) StringToUnsignedLong(value);
offset+=WriteBlobLong(image,dpx.film.held_count);
dpx.film.frame_rate=0.0f;
value=GetDPXProperty(image,"dpx:film.frame_rate");
if (value != (const char *) NULL)
dpx.film.frame_rate=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.film.frame_rate);
dpx.film.shutter_angle=0.0f;
value=GetDPXProperty(image,"dpx:film.shutter_angle");
if (value != (const char *) NULL)
dpx.film.shutter_angle=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.film.shutter_angle);
(void) memset(dpx.film.frame_id,0,sizeof(dpx.film.frame_id));
value=GetDPXProperty(image,"dpx:film.frame_id");
if (value != (const char *) NULL)
(void) strncpy(dpx.film.frame_id,value,sizeof(dpx.film.frame_id)-1);
offset+=WriteBlob(image,sizeof(dpx.film.frame_id),(unsigned char *)
dpx.film.frame_id);
value=GetDPXProperty(image,"dpx:film.slate");
if (value != (const char *) NULL)
(void) strncpy(dpx.film.slate,value,sizeof(dpx.film.slate)-1);
offset+=WriteBlob(image,sizeof(dpx.film.slate),(unsigned char *)
dpx.film.slate);
offset+=WriteBlob(image,sizeof(dpx.film.reserve),(unsigned char *)
dpx.film.reserve);
/*
Write television header.
*/
value=GetDPXProperty(image,"dpx:television.time.code");
if (value != (const char *) NULL)
dpx.television.time_code=StringToTimeCode(value);
offset+=WriteBlobLong(image,dpx.television.time_code);
value=GetDPXProperty(image,"dpx:television.user.bits");
if (value != (const char *) NULL)
dpx.television.user_bits=StringToTimeCode(value);
offset+=WriteBlobLong(image,dpx.television.user_bits);
value=GetDPXProperty(image,"dpx:television.interlace");
if (value != (const char *) NULL)
dpx.television.interlace=(unsigned char) StringToLong(value);
offset+=WriteBlobByte(image,dpx.television.interlace);
value=GetDPXProperty(image,"dpx:television.field_number");
if (value != (const char *) NULL)
dpx.television.field_number=(unsigned char) StringToLong(value);
offset+=WriteBlobByte(image,dpx.television.field_number);
dpx.television.video_signal=0;
value=GetDPXProperty(image,"dpx:television.video_signal");
if (value != (const char *) NULL)
dpx.television.video_signal=(unsigned char) StringToLong(value);
offset+=WriteBlobByte(image,dpx.television.video_signal);
dpx.television.padding=0;
value=GetDPXProperty(image,"dpx:television.padding");
if (value != (const char *) NULL)
dpx.television.padding=(unsigned char) StringToLong(value);
offset+=WriteBlobByte(image,dpx.television.padding);
dpx.television.horizontal_sample_rate=0.0f;
value=GetDPXProperty(image,"dpx:television.horizontal_sample_rate");
if (value != (const char *) NULL)
dpx.television.horizontal_sample_rate=StringToDouble(value,
(char **) NULL);
offset+=WriteBlobFloat(image,dpx.television.horizontal_sample_rate);
dpx.television.vertical_sample_rate=0.0f;
value=GetDPXProperty(image,"dpx:television.vertical_sample_rate");
if (value != (const char *) NULL)
dpx.television.vertical_sample_rate=StringToDouble(value,
(char **) NULL);
offset+=WriteBlobFloat(image,dpx.television.vertical_sample_rate);
dpx.television.frame_rate=0.0f;
value=GetDPXProperty(image,"dpx:television.frame_rate");
if (value != (const char *) NULL)
dpx.television.frame_rate=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.television.frame_rate);
dpx.television.time_offset=0.0f;
value=GetDPXProperty(image,"dpx:television.time_offset");
if (value != (const char *) NULL)
dpx.television.time_offset=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.television.time_offset);
dpx.television.gamma=0.0f;
value=GetDPXProperty(image,"dpx:television.gamma");
if (value != (const char *) NULL)
dpx.television.gamma=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.television.gamma);
dpx.television.black_level=0.0f;
value=GetDPXProperty(image,"dpx:television.black_level");
if (value != (const char *) NULL)
dpx.television.black_level=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.television.black_level);
dpx.television.black_gain=0.0f;
value=GetDPXProperty(image,"dpx:television.black_gain");
if (value != (const char *) NULL)
dpx.television.black_gain=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.television.black_gain);
dpx.television.break_point=0.0f;
value=GetDPXProperty(image,"dpx:television.break_point");
if (value != (const char *) NULL)
dpx.television.break_point=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.television.break_point);
dpx.television.white_level=0.0f;
value=GetDPXProperty(image,"dpx:television.white_level");
if (value != (const char *) NULL)
dpx.television.white_level=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.television.white_level);
dpx.television.integration_times=0.0f;
value=GetDPXProperty(image,"dpx:television.integration_times");
if (value != (const char *) NULL)
dpx.television.integration_times=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,dpx.television.integration_times);
offset+=WriteBlob(image,sizeof(dpx.television.reserve),(unsigned char *)
dpx.television.reserve);
/*
Write user header.
*/
value=GetDPXProperty(image,"dpx:user.id");
if (value != (const char *) NULL)
(void) strncpy(dpx.user.id,value,sizeof(dpx.user.id)-1);
offset+=WriteBlob(image,sizeof(dpx.user.id),(unsigned char *) dpx.user.id);
if (profile != (StringInfo *) NULL)
offset+=WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
while (offset < (MagickOffsetType) dpx.image.image_element[0].data_offset)
{
count=WriteBlobByte(image,0x00);
if (count != 1)
{
ThrowFileException(&image->exception,FileOpenError,"UnableToWriteFile",
image->filename);
break;
}
offset+=count;
}
/*
Convert pixel packets to DPX raster image.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
SetQuantumQuantum(quantum_info,32);
SetQuantumPack(quantum_info,dpx.image.image_element[0].packing == 0 ?
MagickTrue : MagickFalse);
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
if (image->colorspace == YCbCrColorspace)
{
quantum_type=CbYCrQuantum;
if (image->matte != MagickFalse)
quantum_type=CbYCrAQuantum;
if ((horizontal_factor == 2) || (vertical_factor == 2))
quantum_type=CbYCrYQuantum;
}
extent=GetBytesPerRow(image->columns,image->matte != MagickFalse ? 4UL : 3UL,
image->depth,dpx.image.image_element[0].packing == 0 ? MagickFalse :
MagickTrue);
if ((image_info->type != TrueColorType) && (image->matte == MagickFalse) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
quantum_type=GrayQuantum;
extent=GetBytesPerRow(image->columns,1UL,image->depth,
dpx.image.image_element[0].packing == 0 ? MagickFalse : MagickTrue);
}
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
size_t
length;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
quantum_type,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) length)
break;
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (y < (ssize_t) image->rows)
ThrowWriterException(CorruptImageError,"UnableToWriteImageData");
(void) CloseBlob(image);
return(status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1517'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define CropBox "CropBox"
#define DeviceCMYK "DeviceCMYK"
#define MediaBox "MediaBox"
#define RenderPCLText " Rendering PCL... "
char
command[MaxTextExtent],
*density,
filename[MaxTextExtent],
geometry[MaxTextExtent],
*options,
input_filename[MaxTextExtent];
const DelegateInfo
*delegate_info;
Image
*image,
*next_image;
ImageInfo
*read_info;
int
c;
MagickBooleanType
cmyk,
status;
PointInfo
delta;
RectangleInfo
bounding_box,
page;
register char
*p;
SegmentInfo
bounds;
size_t
height,
width;
ssize_t
count;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
/*
Open image file.
*/
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);
if (status == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
image_info->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Set the page density.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
/*
Determine page geometry from the PCL media box.
*/
cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;
count=0;
(void) memset(&bounding_box,0,sizeof(bounding_box));
(void) memset(&bounds,0,sizeof(bounds));
(void) memset(&page,0,sizeof(page));
(void) memset(command,0,sizeof(command));
p=command;
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
if (image_info->page != (char *) NULL)
continue;
/*
Note PCL elements.
*/
*p++=(char) c;
if ((c != (int) '/') && (c != '\n') &&
((size_t) (p-command) < (MaxTextExtent-1)))
continue;
*p='\0';
p=command;
/*
Is this a CMYK document?
*/
if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)
cmyk=MagickTrue;
if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)
{
/*
Note region defined by crop box.
*/
count=(ssize_t) sscanf(command,"CropBox [%lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
if (count != 4)
count=(ssize_t) sscanf(command,"CropBox[%lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
}
if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)
{
/*
Note region defined by media box.
*/
count=(ssize_t) sscanf(command,"MediaBox [%lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
if (count != 4)
count=(ssize_t) sscanf(command,"MediaBox[%lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
}
if (count != 4)
continue;
/*
Set PCL render geometry.
*/
width=(size_t) floor(bounds.x2-bounds.x1+0.5);
height=(size_t) floor(bounds.y2-bounds.y1+0.5);
if (width > page.width)
page.width=width;
if (height > page.height)
page.height=height;
}
(void) CloseBlob(image);
/*
Render PCL with the GhostPCL delegate.
*/
if ((page.width == 0) || (page.height == 0))
(void) ParseAbsoluteGeometry(PSPageGeometry,&page);
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
(void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g",(double)
page.width,(double) page.height);
if (image_info->monochrome != MagickFalse)
delegate_info=GetDelegateInfo("pcl:mono",(char *) NULL,exception);
else
if (cmyk != MagickFalse)
delegate_info=GetDelegateInfo("pcl:cmyk",(char *) NULL,exception);
else
delegate_info=GetDelegateInfo("pcl:color",(char *) NULL,exception);
if (delegate_info == (const DelegateInfo *) NULL)
return((Image *) NULL);
if ((page.width == 0) || (page.height == 0))
(void) ParseAbsoluteGeometry(PSPageGeometry,&page);
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
density=AcquireString("");
options=AcquireString("");
(void) FormatLocaleString(density,MaxTextExtent,"%gx%g",
image->x_resolution,image->y_resolution);
page.width=(size_t) floor((double) page.width*image->x_resolution/delta.x+
0.5);
page.height=(size_t) floor((double) page.height*image->y_resolution/delta.y+
0.5);
(void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double)
page.width,(double) page.height);
image=DestroyImage(image);
read_info=CloneImageInfo(image_info);
*read_info->magick='\0';
if (read_info->number_scenes != 0)
{
if (read_info->number_scenes != 1)
(void) FormatLocaleString(options,MaxTextExtent,"-dLastPage=%.20g",
(double) (read_info->scene+read_info->number_scenes));
else
(void) FormatLocaleString(options,MaxTextExtent,
"-dFirstPage=%.20g -dLastPage=%.20g",(double) read_info->scene+1,
(double) (read_info->scene+read_info->number_scenes));
read_info->number_scenes=0;
if (read_info->scenes != (char *) NULL)
*read_info->scenes='\0';
}
(void) CopyMagickString(filename,read_info->filename,MaxTextExtent);
(void) AcquireUniqueFilename(read_info->filename);
(void) FormatLocaleString(command,MaxTextExtent,
GetDelegateCommands(delegate_info),
read_info->antialias != MagickFalse ? 4 : 1,
read_info->antialias != MagickFalse ? 4 : 1,density,options,
read_info->filename,input_filename);
options=DestroyString(options);
density=DestroyString(density);
status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command,
(char *) NULL,exception) != 0 ? MagickTrue : MagickFalse;
image=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(read_info->filename);
(void) RelinquishUniqueFileResource(input_filename);
read_info=DestroyImageInfo(read_info);
if (image == (Image *) NULL)
ThrowReaderException(DelegateError,"PCLDelegateFailed");
if (LocaleCompare(image->magick,"BMP") == 0)
{
Image
*cmyk_image;
cmyk_image=ConsolidateCMYKImages(image,&image->exception);
if (cmyk_image != (Image *) NULL)
{
image=DestroyImageList(image);
image=cmyk_image;
}
}
do
{
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
image->page=page;
next_image=SyncNextImageInList(image);
if (next_image != (Image *) NULL)
image=next_image;
} while (next_image != (Image *) NULL);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1520'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
const char
*option,
*property;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
OPJ_COLOR_SPACE
jp2_colorspace;
opj_cparameters_t
parameters;
opj_image_cmptparm_t
jp2_info[5];
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned int
channels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
/*
Initialize JPEG 2000 API.
*/
opj_set_default_encoder_parameters(¶meters);
for (i=1; i < 6; i++)
if (((size_t) (1UL << (i+2)) > image->columns) &&
((size_t) (1UL << (i+2)) > image->rows))
break;
parameters.numresolution=i;
option=GetImageOption(image_info,"jp2:number-resolutions");
if (option != (const char *) NULL)
parameters.numresolution=StringToInteger(option);
parameters.tcp_numlayers=1;
parameters.tcp_rates[0]=0; /* lossless */
parameters.cp_disto_alloc=1;
if ((image_info->quality != 0) && (image_info->quality != 100))
{
parameters.tcp_distoratio[0]=(double) image_info->quality;
parameters.cp_fixed_quality=OPJ_TRUE;
}
if (image_info->extract != (char *) NULL)
{
RectangleInfo
geometry;
int
flags;
/*
Set tile size.
*/
flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
parameters.cp_tdx=(int) geometry.width;
parameters.cp_tdy=(int) geometry.width;
if ((flags & HeightValue) != 0)
parameters.cp_tdy=(int) geometry.height;
if ((flags & XValue) != 0)
parameters.cp_tx0=geometry.x;
if ((flags & YValue) != 0)
parameters.cp_ty0=geometry.y;
parameters.tile_size_on=OPJ_TRUE;
}
option=GetImageOption(image_info,"jp2:quality");
if (option != (const char *) NULL)
{
register const char
*p;
/*
Set quality PSNR.
*/
p=option;
for (i=0; sscanf(p,"%f",¶meters.tcp_distoratio[i]) == 1; i++)
{
if (i > 100)
break;
while ((*p != '\0') && (*p != ','))
p++;
if (*p == '\0')
break;
p++;
}
parameters.tcp_numlayers=i+1;
parameters.cp_fixed_quality=OPJ_TRUE;
}
option=GetImageOption(image_info,"jp2:progression-order");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"LRCP") == 0)
parameters.prog_order=OPJ_LRCP;
if (LocaleCompare(option,"RLCP") == 0)
parameters.prog_order=OPJ_RLCP;
if (LocaleCompare(option,"RPCL") == 0)
parameters.prog_order=OPJ_RPCL;
if (LocaleCompare(option,"PCRL") == 0)
parameters.prog_order=OPJ_PCRL;
if (LocaleCompare(option,"CPRL") == 0)
parameters.prog_order=OPJ_CPRL;
}
option=GetImageOption(image_info,"jp2:rate");
if (option != (const char *) NULL)
{
register const char
*p;
/*
Set compression rate.
*/
p=option;
for (i=0; sscanf(p,"%f",¶meters.tcp_rates[i]) == 1; i++)
{
if (i >= 100)
break;
while ((*p != '\0') && (*p != ','))
p++;
if (*p == '\0')
break;
p++;
}
parameters.tcp_numlayers=i+1;
parameters.cp_disto_alloc=OPJ_TRUE;
}
if (image_info->sampling_factor != (const char *) NULL)
(void) sscanf(image_info->sampling_factor,"%d,%d",
¶meters.subsampling_dx,¶meters.subsampling_dy);
property=GetImageProperty(image,"comment",exception);
if (property != (const char *) NULL)
parameters.cp_comment=(char *) property;
channels=3;
jp2_colorspace=OPJ_CLRSPC_SRGB;
if (image->colorspace == YUVColorspace)
{
jp2_colorspace=OPJ_CLRSPC_SYCC;
parameters.subsampling_dx=2;
}
else
{
if (IsGrayColorspace(image->colorspace) != MagickFalse)
{
channels=1;
jp2_colorspace=OPJ_CLRSPC_GRAY;
}
else
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->alpha_trait != UndefinedPixelTrait)
channels++;
}
parameters.tcp_mct=channels == 3 ? 1 : 0;
memset(jp2_info,0,sizeof(jp2_info));
for (i=0; i < (ssize_t) channels; i++)
{
jp2_info[i].prec=(OPJ_UINT32) image->depth;
jp2_info[i].bpp=(OPJ_UINT32) image->depth;
if ((image->depth == 1) &&
((LocaleCompare(image_info->magick,"JPT") == 0) ||
(LocaleCompare(image_info->magick,"JP2") == 0)))
{
jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */
jp2_info[i].bpp++;
}
jp2_info[i].sgnd=0;
jp2_info[i].dx=parameters.subsampling_dx;
jp2_info[i].dy=parameters.subsampling_dy;
jp2_info[i].w=(OPJ_UINT32) image->columns;
jp2_info[i].h=(OPJ_UINT32) image->rows;
}
jp2_image=opj_image_create((OPJ_UINT32) channels,jp2_info,jp2_colorspace);
if (jp2_image == (opj_image_t *) NULL)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
jp2_image->x0=parameters.image_offset_x0;
jp2_image->y0=parameters.image_offset_y0;
jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)*
parameters.subsampling_dx+1);
jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)*
parameters.subsampling_dx+1);
if ((image->depth == 12) &&
((image->columns == 2048) || (image->rows == 1080) ||
(image->columns == 4096) || (image->rows == 2160)))
CinemaProfileCompliance(jp2_image,¶meters);
if (channels == 4)
jp2_image->comps[3].alpha=1;
else
if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY))
jp2_image->comps[1].alpha=1;
/*
Convert to JP2 pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) channels; i++)
{
double
scale;
register int
*q;
scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange;
q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx);
switch (i)
{
case 0:
{
if (jp2_colorspace == OPJ_CLRSPC_GRAY)
{
*q=(int) (scale*GetPixelGray(image,p));
break;
}
*q=(int) (scale*GetPixelRed(image,p));
break;
}
case 1:
{
if (jp2_colorspace == OPJ_CLRSPC_GRAY)
{
*q=(int) (scale*GetPixelAlpha(image,p));
break;
}
*q=(int) (scale*GetPixelGreen(image,p));
break;
}
case 2:
{
*q=(int) (scale*GetPixelBlue(image,p));
break;
}
case 3:
{
*q=(int) (scale*GetPixelAlpha(image,p));
break;
}
}
}
p+=GetPixelChannels(image);
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_compress(OPJ_CODEC_JPT);
else
if (LocaleCompare(image_info->magick,"J2K") == 0)
jp2_codec=opj_create_compress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_compress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
opj_setup_encoder(jp2_codec,¶meters,jp2_image);
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE);
if (jp2_stream == (opj_stream_t *) NULL)
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
}
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream);
if ((jp2_status == 0) || (opj_encode(jp2_codec,jp2_stream) == 0) ||
(opj_end_compress(jp2_codec,jp2_stream) == 0))
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
}
/*
Free resources.
*/
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
(void) CloseBlob(image);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-665'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1518'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadPANGOImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
cairo_font_options_t
*font_options;
cairo_surface_t
*surface;
char
*caption,
*property;
cairo_t
*cairo_image;
const char
*option;
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
MemoryInfo
*pixel_info;
PangoAlignment
align;
PangoContext
*context;
PangoFontDescription
*description;
PangoFontMap
*fontmap;
PangoGravity
gravity;
PangoLayout
*layout;
PangoRectangle
extent;
PixelInfo
fill_color;
RectangleInfo
page;
register unsigned char
*p;
size_t
stride;
ssize_t
y;
unsigned char
*pixels;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
(void) ResetImagePage(image,"0x0+0+0");
/*
Format caption.
*/
option=GetImageOption(image_info,"filename");
if (option == (const char *) NULL)
property=InterpretImageProperties((ImageInfo *) image_info,image,
image_info->filename,exception);
else
if (LocaleNCompare(option,"pango:",6) == 0)
property=InterpretImageProperties((ImageInfo *) image_info,image,option+6,
exception);
else
property=InterpretImageProperties((ImageInfo *) image_info,image,option,
exception);
(void) SetImageProperty(image,"caption",property,exception);
property=DestroyString(property);
caption=ConstantString(GetImageProperty(image,"caption",exception));
/*
Get context.
*/
fontmap=pango_cairo_font_map_new();
pango_cairo_font_map_set_resolution(PANGO_CAIRO_FONT_MAP(fontmap),
image->resolution.x == 0.0 ? DefaultSVGDensity : image->resolution.x);
font_options=cairo_font_options_create();
option=GetImageOption(image_info,"pango:hinting");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"none") != 0)
cairo_font_options_set_hint_style(font_options,CAIRO_HINT_STYLE_NONE);
if (LocaleCompare(option,"full") != 0)
cairo_font_options_set_hint_style(font_options,CAIRO_HINT_STYLE_FULL);
}
context=pango_font_map_create_context(fontmap);
pango_cairo_context_set_font_options(context,font_options);
cairo_font_options_destroy(font_options);
option=GetImageOption(image_info,"pango:language");
if (option != (const char *) NULL)
pango_context_set_language(context,pango_language_from_string(option));
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
pango_context_set_base_dir(context,draw_info->direction ==
RightToLeftDirection ? PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR);
switch (draw_info->gravity)
{
case NorthGravity:
{
gravity=PANGO_GRAVITY_NORTH;
break;
}
case NorthWestGravity:
case WestGravity:
case SouthWestGravity:
{
gravity=PANGO_GRAVITY_WEST;
break;
}
case NorthEastGravity:
case EastGravity:
case SouthEastGravity:
{
gravity=PANGO_GRAVITY_EAST;
break;
}
case SouthGravity:
{
gravity=PANGO_GRAVITY_SOUTH;
break;
}
default:
{
gravity=PANGO_GRAVITY_AUTO;
break;
}
}
pango_context_set_base_gravity(context,gravity);
option=GetImageOption(image_info,"pango:gravity-hint");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"line") == 0)
pango_context_set_gravity_hint(context,PANGO_GRAVITY_HINT_LINE);
if (LocaleCompare(option,"natural") == 0)
pango_context_set_gravity_hint(context,PANGO_GRAVITY_HINT_NATURAL);
if (LocaleCompare(option,"strong") == 0)
pango_context_set_gravity_hint(context,PANGO_GRAVITY_HINT_STRONG);
}
/*
Configure layout.
*/
layout=pango_layout_new(context);
option=GetImageOption(image_info,"pango:auto-dir");
if (option != (const char *) NULL)
pango_layout_set_auto_dir(layout,1);
option=GetImageOption(image_info,"pango:ellipsize");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"end") == 0)
pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_END);
if (LocaleCompare(option,"middle") == 0)
pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_MIDDLE);
if (LocaleCompare(option,"none") == 0)
pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_NONE);
if (LocaleCompare(option,"start") == 0)
pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_START);
}
option=GetImageOption(image_info,"pango:justify");
if (IsStringTrue(option) != MagickFalse)
pango_layout_set_justify(layout,1);
option=GetImageOption(image_info,"pango:single-paragraph");
if (IsStringTrue(option) != MagickFalse)
pango_layout_set_single_paragraph_mode(layout,1);
option=GetImageOption(image_info,"pango:wrap");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"char") == 0)
pango_layout_set_wrap(layout,PANGO_WRAP_CHAR);
if (LocaleCompare(option,"word") == 0)
pango_layout_set_wrap(layout,PANGO_WRAP_WORD);
if (LocaleCompare(option,"word-char") == 0)
pango_layout_set_wrap(layout,PANGO_WRAP_WORD_CHAR);
}
option=GetImageOption(image_info,"pango:indent");
if (option != (const char *) NULL)
pango_layout_set_indent(layout,(int) ((StringToLong(option)*
(image->resolution.x == 0.0 ? DefaultSVGDensity : image->resolution.x)*
PANGO_SCALE+DefaultSVGDensity/2)/DefaultSVGDensity+0.5));
switch (draw_info->align)
{
case CenterAlign: align=PANGO_ALIGN_CENTER; break;
case RightAlign: align=PANGO_ALIGN_RIGHT; break;
case LeftAlign: align=PANGO_ALIGN_LEFT; break;
default:
{
if (draw_info->gravity == CenterGravity)
{
align=PANGO_ALIGN_CENTER;
break;
}
align=PANGO_ALIGN_LEFT;
break;
}
}
if ((align != PANGO_ALIGN_CENTER) &&
(draw_info->direction == RightToLeftDirection))
align=(PangoAlignment) (PANGO_ALIGN_LEFT+PANGO_ALIGN_RIGHT-align);
option=GetImageOption(image_info,"pango:align");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"center") == 0)
align=PANGO_ALIGN_CENTER;
if (LocaleCompare(option,"left") == 0)
align=PANGO_ALIGN_LEFT;
if (LocaleCompare(option,"right") == 0)
align=PANGO_ALIGN_RIGHT;
}
pango_layout_set_alignment(layout,align);
if (draw_info->font == (char *) NULL)
description=pango_font_description_new();
else
description=pango_font_description_from_string(draw_info->font);
pango_font_description_set_size(description,(int) (PANGO_SCALE*
draw_info->pointsize+0.5));
pango_layout_set_font_description(layout,description);
pango_font_description_free(description);
option=GetImageOption(image_info,"pango:markup");
if ((option != (const char *) NULL) && (IsStringTrue(option) == MagickFalse))
pango_layout_set_text(layout,caption,-1);
else
{
GError
*error;
error=(GError *) NULL;
if (pango_parse_markup(caption,-1,0,NULL,NULL,NULL,&error) == 0)
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
error->message,"`%s'",image_info->filename);
pango_layout_set_markup(layout,caption,-1);
}
pango_layout_context_changed(layout);
page.x=0;
page.y=0;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
if (image->columns == 0)
{
pango_layout_get_extents(layout,NULL,&extent);
image->columns=(extent.x+extent.width+PANGO_SCALE/2)/PANGO_SCALE+2*page.x;
}
else
{
image->columns-=2*page.x;
pango_layout_set_width(layout,(int) ((PANGO_SCALE*image->columns*
(image->resolution.x == 0.0 ? DefaultSVGDensity : image->resolution.x)+
DefaultSVGDensity/2)/DefaultSVGDensity+0.5));
}
if (image->rows == 0)
{
pango_layout_get_extents(layout,NULL,&extent);
image->rows=(extent.y+extent.height+PANGO_SCALE/2)/PANGO_SCALE+2*page.y;
}
else
{
image->rows-=2*page.y;
pango_layout_set_height(layout,(int) ((PANGO_SCALE*image->rows*
(image->resolution.y == 0.0 ? DefaultSVGDensity : image->resolution.y)+
DefaultSVGDensity/2)/DefaultSVGDensity+0.5));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Render markup.
*/
stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,
(int) image->columns);
pixel_info=AcquireVirtualMemory(image->rows,stride*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
draw_info=DestroyDrawInfo(draw_info);
caption=DestroyString(caption);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
surface=cairo_image_surface_create_for_data(pixels,CAIRO_FORMAT_ARGB32,
(int) image->columns,(int) image->rows,(int) stride);
cairo_image=cairo_create(surface);
cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR);
cairo_paint(cairo_image);
cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER);
cairo_translate(cairo_image,page.x,page.y);
cairo_set_source_rgba(cairo_image,QuantumScale*draw_info->fill.red,
QuantumScale*draw_info->fill.green,QuantumScale*draw_info->fill.blue,
QuantumScale*draw_info->fill.alpha);
pango_cairo_show_layout(cairo_image,layout);
cairo_destroy(cairo_image);
cairo_surface_destroy(surface);
g_object_unref(layout);
g_object_unref(fontmap);
/*
Convert surface to image.
*/
(void) SetImageBackgroundColor(image,exception);
p=pixels;
GetPixelInfo(image,&fill_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*q;
register ssize_t
x;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
fill_color.blue=(double) ScaleCharToQuantum(*p++);
fill_color.green=(double) ScaleCharToQuantum(*p++);
fill_color.red=(double) ScaleCharToQuantum(*p++);
fill_color.alpha=(double) ScaleCharToQuantum(*p++);
/*
Disassociate alpha.
*/
gamma=QuantumScale*fill_color.alpha;
gamma=PerceptibleReciprocal(gamma);
fill_color.blue*=gamma;
fill_color.green*=gamma;
fill_color.red*=gamma;
CompositePixelOver(image,&fill_color,fill_color.alpha,q,(double)
GetPixelAlpha(image,q),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
/*
Relinquish resources.
*/
pixel_info=RelinquishVirtualMemory(pixel_info);
draw_info=DestroyDrawInfo(draw_info);
caption=DestroyString(caption);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-665'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1519'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport Image *AcquireImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
Image
*image;
MagickStatusType
flags;
/*
Allocate image structure.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
image=(Image *) AcquireCriticalMemory(sizeof(*image));
(void) memset(image,0,sizeof(*image));
/*
Initialize Image structure.
*/
(void) CopyMagickString(image->magick,"MIFF",MagickPathExtent);
image->storage_class=DirectClass;
image->depth=MAGICKCORE_QUANTUM_DEPTH;
image->colorspace=sRGBColorspace;
image->rendering_intent=PerceptualIntent;
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.red_primary.z=0.0300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.green_primary.z=0.1000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.blue_primary.z=0.7900f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
image->chromaticity.white_point.z=0.3583f;
image->interlace=NoInterlace;
image->ticks_per_second=UndefinedTicksPerSecond;
image->compose=OverCompositeOp;
(void) QueryColorCompliance(MatteColor,AllCompliance,&image->matte_color,
exception);
(void) QueryColorCompliance(BackgroundColor,AllCompliance,
&image->background_color,exception);
(void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_color,
exception);
(void) QueryColorCompliance(TransparentColor,AllCompliance,
&image->transparent_color,exception);
GetTimerInfo(&image->timer);
image->cache=AcquirePixelCache(0);
image->channel_mask=DefaultChannels;
image->channel_map=AcquirePixelChannelMap();
image->blob=CloneBlobInfo((BlobInfo *) NULL);
image->timestamp=time((time_t *) NULL);
image->debug=IsEventLogging();
image->reference_count=1;
image->semaphore=AcquireSemaphoreInfo();
image->signature=MagickCoreSignature;
if (image_info == (ImageInfo *) NULL)
return(image);
/*
Transfer image info.
*/
SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue :
MagickFalse);
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,image_info->magick,MagickPathExtent);
if (image_info->size != (char *) NULL)
{
(void) ParseAbsoluteGeometry(image_info->size,&image->extract_info);
image->columns=image->extract_info.width;
image->rows=image->extract_info.height;
image->offset=image->extract_info.x;
image->extract_info.x=0;
image->extract_info.y=0;
}
if (image_info->extract != (char *) NULL)
{
RectangleInfo
geometry;
(void) memset(&geometry,0,sizeof(geometry));
flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
if (((flags & XValue) != 0) || ((flags & YValue) != 0))
{
image->extract_info=geometry;
Swap(image->columns,image->extract_info.width);
Swap(image->rows,image->extract_info.height);
}
}
image->compression=image_info->compression;
image->quality=image_info->quality;
image->endian=image_info->endian;
image->interlace=image_info->interlace;
image->units=image_info->units;
if (image_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(image_info->density,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
if (image_info->page != (char *) NULL)
{
char
*geometry;
image->page=image->extract_info;
geometry=GetPageGeometry(image_info->page);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
}
if (image_info->depth != 0)
image->depth=image_info->depth;
image->dither=image_info->dither;
image->matte_color=image_info->matte_color;
image->background_color=image_info->background_color;
image->border_color=image_info->border_color;
image->transparent_color=image_info->transparent_color;
image->ping=image_info->ping;
image->progress_monitor=image_info->progress_monitor;
image->client_data=image_info->client_data;
if (image_info->cache != (void *) NULL)
ClonePixelCacheMethods(image->cache,image_info->cache);
/*
Set all global options that map to per-image settings.
*/
(void) SyncImageSettings(image_info,image,exception);
/*
Global options that are only set for new images.
*/
option=GetImageOption(image_info,"delay");
if (option != (const char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(option,&geometry_info);
if ((flags & GreaterValue) != 0)
{
if (image->delay > (size_t) floor(geometry_info.rho+0.5))
image->delay=(size_t) floor(geometry_info.rho+0.5);
}
else
if ((flags & LessValue) != 0)
{
if (image->delay < (size_t) floor(geometry_info.rho+0.5))
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
}
else
image->delay=(size_t) floor(geometry_info.rho+0.5);
if ((flags & SigmaValue) != 0)
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
}
option=GetImageOption(image_info,"dispose");
if (option != (const char *) NULL)
image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions,
MagickFalse,option);
return(image);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-665'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1522'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void JPXStream::init()
{
Object oLen, cspace, smaskInData;
if (getDict()) {
oLen = getDict()->lookup("Length");
cspace = getDict()->lookup("ColorSpace");
smaskInData = getDict()->lookup("SMaskInData");
}
int bufSize = BUFFER_INITIAL_SIZE;
if (oLen.isInt()) bufSize = oLen.getInt();
bool indexed = false;
if (cspace.isArray() && cspace.arrayGetLength() > 0) {
const Object cstype = cspace.arrayGet(0);
if (cstype.isName("Indexed")) indexed = true;
}
priv->smaskInData = 0;
if (smaskInData.isInt()) priv->smaskInData = smaskInData.getInt();
int length = 0;
unsigned char *buf = str->toUnsignedChars(&length, bufSize);
priv->init2(OPJ_CODEC_JP2, buf, length, indexed);
gfree(buf);
if (priv->image) {
int numComps = (priv->image) ? priv->image->numcomps : 1;
int alpha = 0;
if (priv->image) {
if (priv->image->color_space == OPJ_CLRSPC_SRGB && numComps == 4) { numComps = 3; alpha = 1; }
else if (priv->image->color_space == OPJ_CLRSPC_SYCC && numComps == 4) { numComps = 3; alpha = 1; }
else if (numComps == 2) { numComps = 1; alpha = 1; }
else if (numComps > 4) { numComps = 4; alpha = 1; }
else { alpha = 0; }
}
priv->npixels = priv->image->comps[0].w * priv->image->comps[0].h;
priv->ncomps = priv->image->numcomps;
if (alpha == 1 && priv->smaskInData == 0) priv->ncomps--;
for (int component = 0; component < priv->ncomps; component++) {
if (priv->image->comps[component].data == nullptr) {
close();
break;
}
const int componentPixels = priv->image->comps[component].w * priv->image->comps[component].h;
if (componentPixels != priv->npixels) {
error(errSyntaxWarning, -1, "Component {0:d} has different WxH than component 0", component);
close();
break;
}
unsigned char *cdata = (unsigned char *)priv->image->comps[component].data;
int adjust = 0;
int depth = priv->image->comps[component].prec;
if (priv->image->comps[component].prec > 8)
adjust = priv->image->comps[component].prec - 8;
int sgndcorr = 0;
if (priv->image->comps[component].sgnd)
sgndcorr = 1 << (priv->image->comps[0].prec - 1);
for (int i = 0; i < priv->npixels; i++) {
int r = priv->image->comps[component].data[i];
*(cdata++) = adjustComp(r, adjust, depth, sgndcorr, indexed);
}
}
} else {
priv->npixels = 0;
}
priv->counter = 0;
priv->ccounter = 0;
priv->inited = true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'JPXStream::init: ignore dict Length if clearly broken
Fixes issue #805'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: copy_to_fd (const char *from, int tofd)
{
int fromfd;
ssize_t i;
if ((fromfd = safe_open (from, O_RDONLY | O_BINARY, 0)) < 0)
pfatal ("Can't reopen file %s", quotearg (from));
while ((i = read (fromfd, buf, bufsize)) != 0)
{
if (i == (ssize_t) -1)
read_fatal ();
if (full_write (tofd, buf, i) != i)
write_fatal ();
}
if (close (fromfd) != 0)
read_fatal ();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59'], 'message': 'Don't follow symlinks unless --follow-symlinks is given
* src/inp.c (plan_a, plan_b), src/util.c (copy_to_fd, copy_file,
append_to_file): Unless the --follow-symlinks option is given, open files with
the O_NOFOLLOW flag to avoid following symlinks. So far, we were only doing
that consistently for input files.
* src/util.c (create_backup): When creating empty backup files, (re)create them
with O_CREAT | O_EXCL to avoid following symlinks in that case as well.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: append_to_file (char const *from, char const *to)
{
int tofd;
if ((tofd = safe_open (to, O_WRONLY | O_BINARY | O_APPEND, 0)) < 0)
pfatal ("Can't reopen file %s", quotearg (to));
copy_to_fd (from, tofd);
if (close (tofd) != 0)
write_fatal ();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59'], 'message': 'Don't follow symlinks unless --follow-symlinks is given
* src/inp.c (plan_a, plan_b), src/util.c (copy_to_fd, copy_file,
append_to_file): Unless the --follow-symlinks option is given, open files with
the O_NOFOLLOW flag to avoid following symlinks. So far, we were only doing
that consistently for input files.
* src/util.c (create_backup): When creating empty backup files, (re)create them
with O_CREAT | O_EXCL to avoid following symlinks in that case as well.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: plan_b (char const *filename)
{
int ifd;
FILE *ifp;
int c;
size_t len;
size_t maxlen;
bool found_revision;
size_t i;
char const *rev;
size_t revlen;
lin line = 1;
if (instat.st_size == 0)
filename = NULL_DEVICE;
if ((ifd = safe_open (filename, O_RDONLY | binary_transput, 0)) < 0
|| ! (ifp = fdopen (ifd, binary_transput ? "rb" : "r")))
pfatal ("Can't open file %s", quotearg (filename));
if (TMPINNAME_needs_removal)
{
/* Reopen the existing temporary file. */
tifd = create_file (TMPINNAME, O_RDWR | O_BINARY, 0, true);
}
else
{
tifd = make_tempfile (&TMPINNAME, 'i', NULL, O_RDWR | O_BINARY,
S_IRUSR | S_IWUSR);
if (tifd == -1)
pfatal ("Can't create temporary file %s", TMPINNAME);
TMPINNAME_needs_removal = true;
}
i = 0;
len = 0;
maxlen = 1;
rev = revision;
found_revision = !rev;
revlen = rev ? strlen (rev) : 0;
while ((c = getc (ifp)) != EOF)
{
if (++len > ((size_t) -1) / 2)
lines_too_long (filename);
if (c == '\n')
{
if (++line < 0)
too_many_lines (filename);
if (maxlen < len)
maxlen = len;
len = 0;
}
if (!found_revision)
{
if (i == revlen)
{
found_revision = ISSPACE ((unsigned char) c);
i = (size_t) -1;
}
else if (i != (size_t) -1)
i = rev[i]==c ? i + 1 : (size_t) -1;
if (i == (size_t) -1 && ISSPACE ((unsigned char) c))
i = 0;
}
}
if (revision)
report_revision (found_revision);
Fseek (ifp, 0, SEEK_SET); /* rewind file */
for (tibufsize = TIBUFSIZE_MINIMUM; tibufsize < maxlen; tibufsize <<= 1)
/* do nothing */ ;
lines_per_buf = tibufsize / maxlen;
tireclen = maxlen;
tibuf[0] = xmalloc (2 * tibufsize);
tibuf[1] = tibuf[0] + tibufsize;
for (line = 1; ; line++)
{
char *p = tibuf[0] + maxlen * (line % lines_per_buf);
char const *p0 = p;
if (! (line % lines_per_buf)) /* new block */
if (write (tifd, tibuf[0], tibufsize) != tibufsize)
write_fatal ();
if ((c = getc (ifp)) == EOF)
break;
for (;;)
{
*p++ = c;
if (c == '\n')
{
last_line_size = p - p0;
break;
}
if ((c = getc (ifp)) == EOF)
{
last_line_size = p - p0;
line++;
goto EOF_reached;
}
}
}
EOF_reached:
if (ferror (ifp) || fclose (ifp) != 0)
read_fatal ();
if (line % lines_per_buf != 0)
if (write (tifd, tibuf[0], tibufsize) != tibufsize)
write_fatal ();
input_lines = line - 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-59'], 'message': 'Don't follow symlinks unless --follow-symlinks is given
* src/inp.c (plan_a, plan_b), src/util.c (copy_to_fd, copy_file,
append_to_file): Unless the --follow-symlinks option is given, open files with
the O_NOFOLLOW flag to avoid following symlinks. So far, we were only doing
that consistently for input files.
* src/util.c (create_backup): When creating empty backup files, (re)create them
with O_CREAT | O_EXCL to avoid following symlinks in that case as well.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: png_read_chunk_header(png_structrp png_ptr)
{
png_byte buf[8];
png_uint_32 length;
#ifdef PNG_IO_STATE_SUPPORTED
png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_HDR;
#endif
/* Read the length and the chunk name.
* This must be performed in a single I/O call.
*/
png_read_data(png_ptr, buf, 8);
length = png_get_uint_31(png_ptr, buf);
/* Put the chunk name into png_ptr->chunk_name. */
png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4);
png_debug2(0, "Reading %lx chunk, length = %lu",
(unsigned long)png_ptr->chunk_name, (unsigned long)length);
/* Reset the crc and run it over the chunk name. */
png_reset_crc(png_ptr);
png_calculate_crc(png_ptr, buf + 4, 4);
/* Check to see if chunk name is valid. */
png_check_chunk_name(png_ptr, png_ptr->chunk_name);
#ifdef PNG_IO_STATE_SUPPORTED
png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA;
#endif
return length;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': '[libng16] Check length of all chunks except IDAT against user limit.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int set_geometry(unsigned int cmd, struct floppy_struct *g,
int drive, int type, struct block_device *bdev)
{
int cnt;
/* sanity checking for parameters. */
if (g->sect <= 0 ||
g->head <= 0 ||
/* check for zero in F_SECT_PER_TRACK */
(unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 ||
g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
/* check if reserved bits are set */
(g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
return -EINVAL;
if (type) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&open_lock);
if (lock_fdc(drive)) {
mutex_unlock(&open_lock);
return -EINTR;
}
floppy_type[type] = *g;
floppy_type[type].name = "user format";
for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
floppy_type[type].size + 1;
process_fd_request();
for (cnt = 0; cnt < N_DRIVE; cnt++) {
struct block_device *bdev = opened_bdev[cnt];
if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
continue;
__invalidate_device(bdev, true);
}
mutex_unlock(&open_lock);
} else {
int oldStretch;
if (lock_fdc(drive))
return -EINTR;
if (cmd != FDDEFPRM) {
/* notice a disk change immediately, else
* we lose our settings immediately*/
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
}
oldStretch = g->stretch;
user_params[drive] = *g;
if (buffer_drive == drive)
SUPBOUND(buffer_max, user_params[drive].sect);
current_type[drive] = &user_params[drive];
floppy_sizes[drive] = user_params[drive].size;
if (cmd == FDDEFPRM)
DRS->keep_data = -1;
else
DRS->keep_data = 1;
/* invalidation. Invalidate only when needed, i.e.
* when there are already sectors in the buffer cache
* whose number will change. This is useful, because
* mtools often changes the geometry of the disk after
* looking at the boot block */
if (DRS->maxblock > user_params[drive].sect ||
DRS->maxtrack ||
((user_params[drive].sect ^ oldStretch) &
(FD_SWAPSIDES | FD_SECTBASEMASK)))
invalidate_drive(bdev);
else
process_fd_request();
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'floppy: fix out-of-bounds read in copy_buffer
This fixes a global out-of-bounds read access in the copy_buffer
function of the floppy driver.
The FDDEFPRM ioctl allows one to set the geometry of a disk. The sect
and head fields (unsigned int) of the floppy_drive structure are used to
compute the max_sector (int) in the make_raw_rw_request function. It is
possible to overflow the max_sector. Next, max_sector is passed to the
copy_buffer function and used in one of the memcpy calls.
An unprivileged user could trigger the bug if the device is accessible,
but requires a floppy disk to be inserted.
The patch adds the check for the .sect * .head multiplication for not
overflowing in the set_geometry function.
The bug was found by syzkaller.
Signed-off-by: Denis Efremov <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int set_geometry(unsigned int cmd, struct floppy_struct *g,
int drive, int type, struct block_device *bdev)
{
int cnt;
/* sanity checking for parameters. */
if (g->sect <= 0 ||
g->head <= 0 ||
g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
/* check if reserved bits are set */
(g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
return -EINVAL;
if (type) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&open_lock);
if (lock_fdc(drive)) {
mutex_unlock(&open_lock);
return -EINTR;
}
floppy_type[type] = *g;
floppy_type[type].name = "user format";
for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
floppy_type[type].size + 1;
process_fd_request();
for (cnt = 0; cnt < N_DRIVE; cnt++) {
struct block_device *bdev = opened_bdev[cnt];
if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
continue;
__invalidate_device(bdev, true);
}
mutex_unlock(&open_lock);
} else {
int oldStretch;
if (lock_fdc(drive))
return -EINTR;
if (cmd != FDDEFPRM) {
/* notice a disk change immediately, else
* we lose our settings immediately*/
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
}
oldStretch = g->stretch;
user_params[drive] = *g;
if (buffer_drive == drive)
SUPBOUND(buffer_max, user_params[drive].sect);
current_type[drive] = &user_params[drive];
floppy_sizes[drive] = user_params[drive].size;
if (cmd == FDDEFPRM)
DRS->keep_data = -1;
else
DRS->keep_data = 1;
/* invalidation. Invalidate only when needed, i.e.
* when there are already sectors in the buffer cache
* whose number will change. This is useful, because
* mtools often changes the geometry of the disk after
* looking at the boot block */
if (DRS->maxblock > user_params[drive].sect ||
DRS->maxtrack ||
((user_params[drive].sect ^ oldStretch) &
(FD_SWAPSIDES | FD_SECTBASEMASK)))
invalidate_drive(bdev);
else
process_fd_request();
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-369'], 'message': 'floppy: fix div-by-zero in setup_format_params
This fixes a divide by zero error in the setup_format_params function of
the floppy driver.
Two consecutive ioctls can trigger the bug: The first one should set the
drive geometry with such .sect and .rate values for the F_SECT_PER_TRACK
to become zero. Next, the floppy format operation should be called.
A floppy disk is not required to be inserted. An unprivileged user
could trigger the bug if the device is accessible.
The patch checks F_SECT_PER_TRACK for a non-zero value in the
set_geometry function. The proper check should involve a reasonable
upper limit for the .sect and .rate fields, but it could change the
UAPI.
The patch also checks F_SECT_PER_TRACK in the setup_format_params, and
cancels the formatting operation in case of zero.
The bug was found by syzkaller.
Signed-off-by: Denis Efremov <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static PCRE2_SPTR SLJIT_FUNC do_extuni_no_utf(jit_arguments *args, PCRE2_SPTR cc)
{
PCRE2_SPTR start_subject = args->begin;
PCRE2_SPTR end_subject = args->end;
int lgb, rgb, ricount;
PCRE2_SPTR bptr;
uint32_t c;
GETCHARINC(c, cc);
lgb = UCD_GRAPHBREAK(c);
while (cc < end_subject)
{
c = *cc;
rgb = UCD_GRAPHBREAK(c);
if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;
/* Not breaking between Regional Indicators is allowed only if there
are an even number of preceding RIs. */
if (lgb == ucp_gbRegionalIndicator && rgb == ucp_gbRegionalIndicator)
{
ricount = 0;
bptr = cc - 1;
/* bptr is pointing to the left-hand character */
while (bptr > start_subject)
{
bptr--;
c = *bptr;
if (UCD_GRAPHBREAK(c) != ucp_gbRegionalIndicator) break;
ricount++;
}
if ((ricount & 1) != 0) break; /* Grapheme break required */
}
/* If Extend or ZWJ follows Extended_Pictographic, do not update lgb; this
allows any number of them before a following Extended_Pictographic. */
if ((rgb != ucp_gbExtend && rgb != ucp_gbZWJ) ||
lgb != ucp_gbExtended_Pictographic)
lgb = rgb;
cc++;
}
return cc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix #78338: Array cross-border reading in PCRE
We backport r1092 from pcre2.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void ImportEPUB::ExtractContainer()
{
int res = 0;
if (!cp437) {
cp437 = new QCodePage437Codec();
}
#ifdef Q_OS_WIN32
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(m_FullFilePath)).c_str(), &ffunc);
#else
unzFile zfile = unzOpen64(QDir::toNativeSeparators(m_FullFilePath).toUtf8().constData());
#endif
if (zfile == NULL) {
throw (EPUBLoadParseError(QString(QObject::tr("Cannot unzip EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
res = unzGoToFirstFile(zfile);
if (res == UNZ_OK) {
do {
// Get the name of the file in the archive.
char file_name[MAX_PATH] = {0};
unz_file_info64 file_info;
unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);
QString qfile_name;
QString cp437_file_name;
qfile_name = QString::fromUtf8(file_name);
if (!(file_info.flag & (1<<11))) {
// General purpose bit 11 says the filename is utf-8 encoded. If not set then
// IBM 437 encoding might be used.
cp437_file_name = cp437->toUnicode(file_name);
}
// If there is no file name then we can't do anything with it.
if (!qfile_name.isEmpty()) {
// for security reasons we need the file path to always be inside the
// target folder and not outside, so we will remove all relative upward
// paths segments ".." from the file path before prepending the target
// folder to create the final target path
qfile_name = qfile_name.replace("../","");
cp437_file_name = cp437_file_name.replace("../","");
// We use the dir object to create the path in the temporary directory.
// Unfortunately, we need a dir ojbect to do this as it's not a static function.
QDir dir(m_ExtractedFolderPath);
// Full file path in the temporary directory.
QString file_path = m_ExtractedFolderPath + "/" + qfile_name;
QFileInfo qfile_info(file_path);
// Is this entry a directory?
if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {
dir.mkpath(qfile_name);
continue;
} else {
dir.mkpath(qfile_info.path());
// add it to the list of files found inside the zip
if (cp437_file_name.isEmpty()) {
m_ZipFilePaths << qfile_name;
} else {
m_ZipFilePaths << cp437_file_name;
}
}
// Open the file entry in the archive for reading.
if (unzOpenCurrentFile(zfile) != UNZ_OK) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// Open the file on disk to write the entry in the archive to.
QFile entry(file_path);
if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// Buffered reading and writing.
char buff[BUFF_SIZE] = {0};
int read = 0;
while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {
entry.write(buff, read);
}
entry.close();
// Read errors are marked by a negative read amount.
if (read < 0) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// The file was read but the CRC did not match.
// We don't check the read file size vs the uncompressed file size
// because if they're different there should be a CRC error.
if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {
QString cp437_file_path = m_ExtractedFolderPath + "/" + cp437_file_name;
QFile::copy(file_path, cp437_file_path);
}
}
} while ((res = unzGoToNextFile(zfile)) == UNZ_OK);
}
if (res != UNZ_END_OF_LIST_OF_FILE) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot open EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
unzClose(zfile);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'further harden against malicious epubs and produce error message'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool Utility::UnZip(const QString &zippath, const QString &destpath)
{
int res = 0;
QDir dir(destpath);
if (!cp437) {
cp437 = new QCodePage437Codec();
}
#ifdef Q_OS_WIN32
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc);
#else
unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData());
#endif
if ((zfile == NULL) || (!IsFileReadable(zippath)) || (!dir.exists())) {
return false;
}
res = unzGoToFirstFile(zfile);
if (res == UNZ_OK) {
do {
// Get the name of the file in the archive.
char file_name[MAX_PATH] = {0};
unz_file_info64 file_info;
unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);
QString qfile_name;
QString cp437_file_name;
qfile_name = QString::fromUtf8(file_name);
if (!(file_info.flag & (1<<11))) {
// General purpose bit 11 says the filename is utf-8 encoded. If not set then
// IBM 437 encoding might be used.
cp437_file_name = cp437->toUnicode(file_name);
}
// If there is no file name then we can't do anything with it.
if (!qfile_name.isEmpty()) {
// We use the dir object to create the path in the temporary directory.
// Unfortunately, we need a dir ojbect to do this as it's not a static function.
// Full file path in the temporary directory.
QString file_path = destpath + "/" + qfile_name;
QFileInfo qfile_info(file_path);
// Is this entry a directory?
if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {
dir.mkpath(qfile_name);
continue;
} else {
dir.mkpath(qfile_info.path());
}
// Open the file entry in the archive for reading.
if (unzOpenCurrentFile(zfile) != UNZ_OK) {
unzClose(zfile);
return false;
}
// Open the file on disk to write the entry in the archive to.
QFile entry(file_path);
if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
return false;
}
// Buffered reading and writing.
char buff[BUFF_SIZE] = {0};
int read = 0;
while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {
entry.write(buff, read);
}
entry.close();
// Read errors are marked by a negative read amount.
if (read < 0) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
return false;
}
// The file was read but the CRC did not match.
// We don't check the read file size vs the uncompressed file size
// because if they're different there should be a CRC error.
if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {
unzClose(zfile);
return false;
}
if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {
QString cp437_file_path = destpath + "/" + cp437_file_name;
QFile::copy(file_path, cp437_file_path);
}
}
} while ((res = unzGoToNextFile(zfile)) == UNZ_OK);
}
if (res != UNZ_END_OF_LIST_OF_FILE) {
unzClose(zfile);
return false;
}
unzClose(zfile);
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-22'], 'message': 'harden plugin unzipping to zip-slip attacks'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: struct se_portal_group *tcm_loop_make_naa_tpg(
struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct tcm_loop_hba *tl_hba = container_of(wwn,
struct tcm_loop_hba, tl_hba_wwn);
struct tcm_loop_tpg *tl_tpg;
char *tpgt_str, *end_ptr;
int ret;
unsigned short int tpgt;
tpgt_str = strstr(name, "tpgt_");
if (!tpgt_str) {
printk(KERN_ERR "Unable to locate \"tpgt_#\" directory"
" group\n");
return ERR_PTR(-EINVAL);
}
tpgt_str += 5; /* Skip ahead of "tpgt_" */
tpgt = (unsigned short int) simple_strtoul(tpgt_str, &end_ptr, 0);
if (tpgt > TL_TPGS_PER_HBA) {
printk(KERN_ERR "Passed tpgt: %hu exceeds TL_TPGS_PER_HBA:"
" %u\n", tpgt, TL_TPGS_PER_HBA);
return ERR_PTR(-EINVAL);
}
tl_tpg = &tl_hba->tl_hba_tpgs[tpgt];
tl_tpg->tl_hba = tl_hba;
tl_tpg->tl_tpgt = tpgt;
/*
* Register the tl_tpg as a emulated SAS TCM Target Endpoint
*/
ret = core_tpg_register(&tcm_loop_fabric_configfs->tf_ops,
wwn, &tl_tpg->tl_se_tpg, tl_tpg,
TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0)
return ERR_PTR(-ENOMEM);
printk(KERN_INFO "TCM_Loop_ConfigFS: Allocated Emulated %s"
" Target Port %s,t,0x%04x\n", tcm_loop_dump_proto_id(tl_hba),
config_item_name(&wwn->wwn_group.cg_item), tpgt);
return &tl_tpg->tl_se_tpg;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'loopback: off by one in tcm_loop_make_naa_tpg()
This is an off by one 'tgpt' check in tcm_loop_make_naa_tpg() that could result
in memory corruption.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Nicholas A. Bellinger <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: nvmet_fc_find_target_queue(struct nvmet_fc_tgtport *tgtport,
u64 connection_id)
{
struct nvmet_fc_tgt_assoc *assoc;
struct nvmet_fc_tgt_queue *queue;
u64 association_id = nvmet_fc_getassociationid(connection_id);
u16 qid = nvmet_fc_getqueueid(connection_id);
unsigned long flags;
spin_lock_irqsave(&tgtport->lock, flags);
list_for_each_entry(assoc, &tgtport->assoc_list, a_list) {
if (association_id == assoc->association_id) {
queue = assoc->queues[qid];
if (queue &&
(!atomic_read(&queue->connected) ||
!nvmet_fc_tgt_q_get(queue)))
queue = NULL;
spin_unlock_irqrestore(&tgtport->lock, flags);
return queue;
}
}
spin_unlock_irqrestore(&tgtport->lock, flags);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'nvmet-fc: ensure target queue id within range.
When searching for queue id's ensure they are within the expected range.
Signed-off-by: James Smart <[email protected]>
Signed-off-by: Christoph Hellwig <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int iwl_process_add_sta_resp(struct iwl_priv *priv,
struct iwl_addsta_cmd *addsta,
struct iwl_rx_packet *pkt)
{
u8 sta_id = addsta->sta.sta_id;
unsigned long flags;
int ret = -EIO;
if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) {
IWL_ERR(priv, "Bad return from REPLY_ADD_STA (0x%08X)\n",
pkt->hdr.flags);
return ret;
}
IWL_DEBUG_INFO(priv, "Processing response for adding station %u\n",
sta_id);
spin_lock_irqsave(&priv->shrd->sta_lock, flags);
switch (pkt->u.add_sta.status) {
case ADD_STA_SUCCESS_MSK:
IWL_DEBUG_INFO(priv, "REPLY_ADD_STA PASSED\n");
iwl_sta_ucode_activate(priv, sta_id);
ret = 0;
break;
case ADD_STA_NO_ROOM_IN_TABLE:
IWL_ERR(priv, "Adding station %d failed, no room in table.\n",
sta_id);
break;
case ADD_STA_NO_BLOCK_ACK_RESOURCE:
IWL_ERR(priv, "Adding station %d failed, no block ack "
"resource.\n", sta_id);
break;
case ADD_STA_MODIFY_NON_EXIST_STA:
IWL_ERR(priv, "Attempting to modify non-existing station %d\n",
sta_id);
break;
default:
IWL_DEBUG_ASSOC(priv, "Received REPLY_ADD_STA:(0x%08X)\n",
pkt->u.add_sta.status);
break;
}
IWL_DEBUG_INFO(priv, "%s station id %u addr %pM\n",
priv->stations[sta_id].sta.mode ==
STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
sta_id, priv->stations[sta_id].sta.sta.addr);
/*
* XXX: The MAC address in the command buffer is often changed from
* the original sent to the device. That is, the MAC address
* written to the command buffer often is not the same MAC address
* read from the command buffer when the command returns. This
* issue has not yet been resolved and this debugging is left to
* observe the problem.
*/
IWL_DEBUG_INFO(priv, "%s station according to cmd buffer %pM\n",
priv->stations[sta_id].sta.mode ==
STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
addsta->sta.addr);
spin_unlock_irqrestore(&priv->shrd->sta_lock, flags);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'iwlwifi: Sanity check for sta_id
On my testing, I saw some strange behavior
[ 421.739708] iwlwifi 0000:01:00.0: ACTIVATE a non DRIVER active station id 148 addr 00:00:00:00:00:00
[ 421.739719] iwlwifi 0000:01:00.0: iwl_sta_ucode_activate Added STA id 148 addr 00:00:00:00:00:00 to uCode
not sure how it happen, but adding the sanity check to prevent memory
corruption
Signed-off-by: Wey-Yi Guy <[email protected]>
Signed-off-by: John W. Linville <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) {
ipfix_template_record_t *ipfix_template_record;
// a template flowset can contain multiple records ( templates )
while ( size_left ) {
uint32_t id;
// map next record.
ipfix_template_record = (ipfix_template_record_t *)DataPtr;
size_left -= 4;
id = ntohs(ipfix_template_record->TemplateID);
// count = ntohs(ipfix_template_record->FieldCount);
if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) {
// withdraw all templates
remove_all_translation_tables(exporter);
ReInitExtensionMapList(fs);
} else {
remove_translation_table(fs, exporter, id);
}
DataPtr = DataPtr + 4;
if ( size_left < 4 ) {
// pading
dbg_printf("Skip %u bytes padding\n", size_left);
size_left = 0;
}
}
} // End of Process_ipfix_template_withdraw ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Fix potential unsigned integer underflow'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int cx24116_send_diseqc_msg(struct dvb_frontend *fe,
struct dvb_diseqc_master_cmd *d)
{
struct cx24116_state *state = fe->demodulator_priv;
int i, ret;
/* Dump DiSEqC message */
if (debug) {
printk(KERN_INFO "cx24116: %s(", __func__);
for (i = 0 ; i < d->msg_len ;) {
printk(KERN_INFO "0x%02x", d->msg[i]);
if (++i < d->msg_len)
printk(KERN_INFO ", ");
}
printk(") toneburst=%d\n", toneburst);
}
/* Validate length */
if (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS))
return -EINVAL;
/* DiSEqC message */
for (i = 0; i < d->msg_len; i++)
state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i];
/* DiSEqC message length */
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len;
/* Command length */
state->dsec_cmd.len = CX24116_DISEQC_MSGOFS +
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN];
/* DiSEqC toneburst */
if (toneburst == CX24116_DISEQC_MESGCACHE)
/* Message is cached */
return 0;
else if (toneburst == CX24116_DISEQC_TONEOFF)
/* Message is sent without burst */
state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0;
else if (toneburst == CX24116_DISEQC_TONECACHE) {
/*
* Message is sent with derived else cached burst
*
* WRITE PORT GROUP COMMAND 38
*
* 0/A/A: E0 10 38 F0..F3
* 1/B/B: E0 10 38 F4..F7
* 2/C/A: E0 10 38 F8..FB
* 3/D/B: E0 10 38 FC..FF
*
* databyte[3]= 8421:8421
* ABCD:WXYZ
* CLR :SET
*
* WX= PORT SELECT 0..3 (X=TONEBURST)
* Y = VOLTAGE (0=13V, 1=18V)
* Z = BAND (0=LOW, 1=HIGH(22K))
*/
if (d->msg_len >= 4 && d->msg[2] == 0x38)
state->dsec_cmd.args[CX24116_DISEQC_BURST] =
((d->msg[3] & 4) >> 2);
if (debug)
dprintk("%s burst=%d\n", __func__,
state->dsec_cmd.args[CX24116_DISEQC_BURST]);
}
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
/* Command */
ret = cx24116_cmd_execute(fe, &state->dsec_cmd);
if (ret != 0)
return ret;
/*
* Wait for send
*
* Eutelsat spec:
* >15ms delay + (XXX determine if FW does this, see set_tone)
* 13.5ms per byte +
* >15ms delay +
* 12.5ms burst +
* >15ms delay (XXX determine if FW does this, see set_tone)
*/
msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) +
((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60));
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-119', 'CWE-125'], 'message': '[media] cx24116: fix a buffer overflow when checking userspace params
The maximum size for a DiSEqC command is 6, according to the
userspace API. However, the code allows to write up much more values:
drivers/media/dvb-frontends/cx24116.c:983 cx24116_send_diseqc_msg() error: buffer overflow 'd->msg' 6 <= 23
Cc: [email protected]
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc,
const char **argv) {
struct passwd *pw = NULL, pw_s;
const char *user = NULL;
cfg_t cfg_st;
cfg_t *cfg = &cfg_st;
char buffer[BUFSIZE];
char *buf = NULL;
char *authfile_dir;
size_t authfile_dir_len;
int pgu_ret, gpn_ret;
int retval = PAM_IGNORE;
device_t *devices = NULL;
unsigned n_devices = 0;
int openasuser;
int should_free_origin = 0;
int should_free_appid = 0;
int should_free_auth_file = 0;
int should_free_authpending_file = 0;
parse_cfg(flags, argc, argv, cfg);
if (!cfg->origin) {
strcpy(buffer, DEFAULT_ORIGIN_PREFIX);
if (gethostname(buffer + strlen(DEFAULT_ORIGIN_PREFIX),
BUFSIZE - strlen(DEFAULT_ORIGIN_PREFIX)) == -1) {
DBG("Unable to get host name");
goto done;
}
DBG("Origin not specified, using \"%s\"", buffer);
cfg->origin = strdup(buffer);
if (!cfg->origin) {
DBG("Unable to allocate memory");
goto done;
} else {
should_free_origin = 1;
}
}
if (!cfg->appid) {
DBG("Appid not specified, using the same value of origin (%s)",
cfg->origin);
cfg->appid = strdup(cfg->origin);
if (!cfg->appid) {
DBG("Unable to allocate memory")
goto done;
} else {
should_free_appid = 1;
}
}
if (cfg->max_devs == 0) {
DBG("Maximum devices number not set. Using default (%d)", MAX_DEVS);
cfg->max_devs = MAX_DEVS;
}
devices = malloc(sizeof(device_t) * cfg->max_devs);
if (!devices) {
DBG("Unable to allocate memory");
retval = PAM_IGNORE;
goto done;
}
pgu_ret = pam_get_user(pamh, &user, NULL);
if (pgu_ret != PAM_SUCCESS || user == NULL) {
DBG("Unable to access user %s", user);
retval = PAM_CONV_ERR;
goto done;
}
DBG("Requesting authentication for user %s", user);
gpn_ret = getpwnam_r(user, &pw_s, buffer, sizeof(buffer), &pw);
if (gpn_ret != 0 || pw == NULL || pw->pw_dir == NULL ||
pw->pw_dir[0] != '/') {
DBG("Unable to retrieve credentials for user %s, (%s)", user,
strerror(errno));
retval = PAM_USER_UNKNOWN;
goto done;
}
DBG("Found user %s", user);
DBG("Home directory for %s is %s", user, pw->pw_dir);
if (!cfg->auth_file) {
buf = NULL;
authfile_dir = secure_getenv(DEFAULT_AUTHFILE_DIR_VAR);
if (!authfile_dir) {
DBG("Variable %s is not set. Using default value ($HOME/.config/)",
DEFAULT_AUTHFILE_DIR_VAR);
authfile_dir_len =
strlen(pw->pw_dir) + strlen("/.config") + strlen(DEFAULT_AUTHFILE) + 1;
buf = malloc(sizeof(char) * (authfile_dir_len));
if (!buf) {
DBG("Unable to allocate memory");
retval = PAM_IGNORE;
goto done;
}
snprintf(buf, authfile_dir_len,
"%s/.config%s", pw->pw_dir, DEFAULT_AUTHFILE);
} else {
DBG("Variable %s set to %s", DEFAULT_AUTHFILE_DIR_VAR, authfile_dir);
authfile_dir_len = strlen(authfile_dir) + strlen(DEFAULT_AUTHFILE) + 1;
buf = malloc(sizeof(char) * (authfile_dir_len));
if (!buf) {
DBG("Unable to allocate memory");
retval = PAM_IGNORE;
goto done;
}
snprintf(buf, authfile_dir_len,
"%s%s", authfile_dir, DEFAULT_AUTHFILE);
}
DBG("Using default authentication file %s", buf);
cfg->auth_file = buf; /* cfg takes ownership */
should_free_auth_file = 1;
buf = NULL;
} else {
DBG("Using authentication file %s", cfg->auth_file);
}
openasuser = geteuid() == 0 && cfg->openasuser;
if (openasuser) {
if (seteuid(pw_s.pw_uid)) {
DBG("Unable to switch user to uid %i", pw_s.pw_uid);
retval = PAM_IGNORE;
goto done;
}
DBG("Switched to uid %i", pw_s.pw_uid);
}
retval = get_devices_from_authfile(cfg->auth_file, user, cfg->max_devs,
cfg->debug, cfg->debug_file,
devices, &n_devices);
if (openasuser) {
if (seteuid(0)) {
DBG("Unable to switch back to uid 0");
retval = PAM_IGNORE;
goto done;
}
DBG("Switched back to uid 0");
}
if (retval != 1) {
// for nouserok; make sure errors in get_devices_from_authfile don't
// result in valid devices
n_devices = 0;
}
if (n_devices == 0) {
if (cfg->nouserok) {
DBG("Found no devices but nouserok specified. Skipping authentication");
retval = PAM_SUCCESS;
goto done;
} else if (retval != 1) {
DBG("Unable to get devices from file %s", cfg->auth_file);
retval = PAM_AUTHINFO_UNAVAIL;
goto done;
} else {
DBG("Found no devices. Aborting.");
retval = PAM_AUTHINFO_UNAVAIL;
goto done;
}
}
// Determine the full path for authpending_file in order to emit touch request notifications
if (!cfg->authpending_file) {
int actual_size = snprintf(buffer, BUFSIZE, DEFAULT_AUTHPENDING_FILE_PATH, getuid());
if (actual_size >= 0 && actual_size < BUFSIZE) {
cfg->authpending_file = strdup(buffer);
}
if (!cfg->authpending_file) {
DBG("Unable to allocate memory for the authpending_file, touch request notifications will not be emitted");
} else {
should_free_authpending_file = 1;
}
} else {
if (strlen(cfg->authpending_file) == 0) {
DBG("authpending_file is set to an empty value, touch request notifications will be disabled");
cfg->authpending_file = NULL;
}
}
int authpending_file_descriptor = -1;
if (cfg->authpending_file) {
DBG("Using file '%s' for emitting touch request notifications", cfg->authpending_file);
// Open (or create) the authpending_file to indicate that we start waiting for a touch
authpending_file_descriptor =
open(cfg->authpending_file, O_RDONLY | O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_NOCTTY, 0664);
if (authpending_file_descriptor < 0) {
DBG("Unable to emit 'authentication started' notification by opening the file '%s', (%s)",
cfg->authpending_file, strerror(errno));
}
}
if (cfg->manual == 0) {
if (cfg->interactive) {
converse(pamh, PAM_PROMPT_ECHO_ON,
cfg->prompt != NULL ? cfg->prompt : DEFAULT_PROMPT);
}
retval = do_authentication(cfg, devices, n_devices, pamh);
} else {
retval = do_manual_authentication(cfg, devices, n_devices, pamh);
}
// Close the authpending_file to indicate that we stop waiting for a touch
if (authpending_file_descriptor >= 0) {
if (close(authpending_file_descriptor) < 0) {
DBG("Unable to emit 'authentication stopped' notification by closing the file '%s', (%s)",
cfg->authpending_file, strerror(errno));
}
}
if (retval != 1) {
DBG("do_authentication returned %d", retval);
retval = PAM_AUTH_ERR;
goto done;
}
retval = PAM_SUCCESS;
done:
free_devices(devices, n_devices);
if (buf) {
free(buf);
buf = NULL;
}
if (should_free_origin) {
free((char *) cfg->origin);
cfg->origin = NULL;
}
if (should_free_appid) {
free((char *) cfg->appid);
cfg->appid = NULL;
}
if (should_free_auth_file) {
free((char *) cfg->auth_file);
cfg->auth_file = NULL;
}
if (should_free_authpending_file) {
free((char *) cfg->authpending_file);
cfg->authpending_file = NULL;
}
if (cfg->alwaysok && retval != PAM_SUCCESS) {
DBG("alwaysok needed (otherwise return with %d)", retval);
retval = PAM_SUCCESS;
}
DBG("done. [%s]", pam_strerror(pamh, retval));
if (cfg->is_custom_debug_file) {
fclose(cfg->debug_file);
}
return retval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-59'], 'message': 'Drop privileges by default when opening user-related files
The module is typically executed as root and would sometimes
open files or follow symlinks that could be controlled from the
outside.
Drop privileges to the target user before opening any files.
Fixes CVE-2019-12209.
Thanks to Matthias Gerstner of the SUSE Security Team for reporting
the issue.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int compute_password_element (pwd_session_t *session, uint16_t grp_num,
char const *password, int password_len,
char const *id_server, int id_server_len,
char const *id_peer, int id_peer_len,
uint32_t *token)
{
BIGNUM *x_candidate = NULL, *rnd = NULL, *cofactor = NULL;
HMAC_CTX *ctx = NULL;
uint8_t pwe_digest[SHA256_DIGEST_LENGTH], *prfbuf = NULL, ctr;
int nid, is_odd, primebitlen, primebytelen, ret = 0;
ctx = HMAC_CTX_new();
if (ctx == NULL) {
DEBUG("failed allocating HMAC context");
goto fail;
}
switch (grp_num) { /* from IANA registry for IKE D-H groups */
case 19:
nid = NID_X9_62_prime256v1;
break;
case 20:
nid = NID_secp384r1;
break;
case 21:
nid = NID_secp521r1;
break;
case 25:
nid = NID_X9_62_prime192v1;
break;
case 26:
nid = NID_secp224r1;
break;
default:
DEBUG("unknown group %d", grp_num);
goto fail;
}
session->pwe = NULL;
session->order = NULL;
session->prime = NULL;
if ((session->group = EC_GROUP_new_by_curve_name(nid)) == NULL) {
DEBUG("unable to create EC_GROUP");
goto fail;
}
if (((rnd = BN_new()) == NULL) ||
((cofactor = BN_new()) == NULL) ||
((session->pwe = EC_POINT_new(session->group)) == NULL) ||
((session->order = BN_new()) == NULL) ||
((session->prime = BN_new()) == NULL) ||
((x_candidate = BN_new()) == NULL)) {
DEBUG("unable to create bignums");
goto fail;
}
if (!EC_GROUP_get_curve_GFp(session->group, session->prime, NULL, NULL, NULL)) {
DEBUG("unable to get prime for GFp curve");
goto fail;
}
if (!EC_GROUP_get_order(session->group, session->order, NULL)) {
DEBUG("unable to get order for curve");
goto fail;
}
if (!EC_GROUP_get_cofactor(session->group, cofactor, NULL)) {
DEBUG("unable to get cofactor for curve");
goto fail;
}
primebitlen = BN_num_bits(session->prime);
primebytelen = BN_num_bytes(session->prime);
if ((prfbuf = talloc_zero_array(session, uint8_t, primebytelen)) == NULL) {
DEBUG("unable to alloc space for prf buffer");
goto fail;
}
ctr = 0;
while (1) {
if (ctr > 10) {
DEBUG("unable to find random point on curve for group %d, something's fishy", grp_num);
goto fail;
}
ctr++;
/*
* compute counter-mode password value and stretch to prime
* pwd-seed = H(token | peer-id | server-id | password |
* counter)
*/
H_Init(ctx);
H_Update(ctx, (uint8_t *)token, sizeof(*token));
H_Update(ctx, (uint8_t const *)id_peer, id_peer_len);
H_Update(ctx, (uint8_t const *)id_server, id_server_len);
H_Update(ctx, (uint8_t const *)password, password_len);
H_Update(ctx, (uint8_t *)&ctr, sizeof(ctr));
H_Final(ctx, pwe_digest);
BN_bin2bn(pwe_digest, SHA256_DIGEST_LENGTH, rnd);
if (eap_pwd_kdf(pwe_digest, SHA256_DIGEST_LENGTH, "EAP-pwd Hunting And Pecking",
strlen("EAP-pwd Hunting And Pecking"), prfbuf, primebitlen) != 0) {
DEBUG("key derivation function failed");
goto fail;
}
BN_bin2bn(prfbuf, primebytelen, x_candidate);
/*
* eap_pwd_kdf() returns a string of bits 0..primebitlen but
* BN_bin2bn will treat that string of bits as a big endian
* number. If the primebitlen is not an even multiple of 8
* then excessive bits-- those _after_ primebitlen-- so now
* we have to shift right the amount we masked off.
*/
if (primebitlen % 8) BN_rshift(x_candidate, x_candidate, (8 - (primebitlen % 8)));
if (BN_ucmp(x_candidate, session->prime) >= 0) continue;
/*
* need to unambiguously identify the solution, if there is
* one...
*/
is_odd = BN_is_odd(rnd) ? 1 : 0;
/*
* solve the quadratic equation, if it's not solvable then we
* don't have a point
*/
if (!EC_POINT_set_compressed_coordinates_GFp(session->group, session->pwe, x_candidate, is_odd, NULL)) {
continue;
}
/*
* If there's a solution to the equation then the point must be
* on the curve so why check again explicitly? OpenSSL code
* says this is required by X9.62. We're not X9.62 but it can't
* hurt just to be sure.
*/
if (!EC_POINT_is_on_curve(session->group, session->pwe, NULL)) {
DEBUG("EAP-pwd: point is not on curve");
continue;
}
if (BN_cmp(cofactor, BN_value_one())) {
/* make sure the point is not in a small sub-group */
if (!EC_POINT_mul(session->group, session->pwe, NULL, session->pwe,
cofactor, NULL)) {
DEBUG("EAP-pwd: cannot multiply generator by order");
continue;
}
if (EC_POINT_is_at_infinity(session->group, session->pwe)) {
DEBUG("EAP-pwd: point is at infinity");
continue;
}
}
/* if we got here then we have a new generator. */
break;
}
session->group_num = grp_num;
if (0) {
fail: /* DON'T free session, it's in handler->opaque */
ret = -1;
}
/* cleanliness and order.... */
BN_clear_free(cofactor);
BN_clear_free(x_candidate);
BN_clear_free(rnd);
talloc_free(prfbuf);
HMAC_CTX_free(ctx);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-284', 'CWE-203'], 'message': 'EAP-pwd: fix side-channel leak where 1 in 2018 handshakes fail
Previously the Hunting and Pecking algorithm of EAP-pwd aborted when
more than 10 iterations are needed. Every iteration has a 50% chance
of finding the password element. This means one in every 2048 handshakes
will fail, in which case an error frame is sent to the client. This
event leaks information that can be abused in an offline password
brute-force attack. More precisely, the adversary learns that all 10
iterations failed for the given random EAP-pwd token. Using the same
techniques as in the Dragonblood attack, this can be used to brute-force
the password.
This patch fixes the above issue by executing enough iterations such that
the password element is always found eventually.
Note that timing and cache leaks remain a risk against the current
implementation of EAP-pwd.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int ParseCaffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
uint32_t chan_chunk = 0, channel_layout = 0, bcount;
unsigned char *channel_identities = NULL;
unsigned char *channel_reorder = NULL;
int64_t total_samples = 0, infilesize;
CAFFileHeader caf_file_header;
CAFChunkHeader caf_chunk_header;
CAFAudioFormat caf_audio_format;
int i;
infilesize = DoGetFileSize (infile);
memcpy (&caf_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &caf_file_header) + 4, sizeof (CAFFileHeader) - 4, &bcount) ||
bcount != sizeof (CAFFileHeader) - 4)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_file_header, sizeof (CAFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_file_header, CAFFileHeaderFormat);
if (caf_file_header.mFileVersion != 1) {
error_line ("%s: can't handle version %d .CAF files!", infilename, caf_file_header.mFileVersion);
return WAVPACK_SOFT_ERROR;
}
// loop through all elements of the RIFF wav header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &caf_chunk_header, sizeof (CAFChunkHeader), &bcount) ||
bcount != sizeof (CAFChunkHeader)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_chunk_header, sizeof (CAFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_chunk_header, CAFChunkHeaderFormat);
// if it's the format chunk, we want to get some info out of there and
// make sure it's a .caf file we can handle
if (!strncmp (caf_chunk_header.mChunkType, "desc", 4)) {
int supported = TRUE;
if (caf_chunk_header.mChunkSize != sizeof (CAFAudioFormat) ||
!DoReadFile (infile, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize, &bcount) ||
bcount != caf_chunk_header.mChunkSize) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_audio_format, CAFAudioFormatFormat);
if (debug_logging_mode) {
char formatstr [5];
memcpy (formatstr, caf_audio_format.mFormatID, 4);
formatstr [4] = 0;
error_line ("format = %s, flags = %x, sampling rate = %g",
formatstr, caf_audio_format.mFormatFlags, caf_audio_format.mSampleRate);
error_line ("packet = %d bytes and %d frames",
caf_audio_format.mBytesPerPacket, caf_audio_format.mFramesPerPacket);
error_line ("channels per frame = %d, bits per channel = %d",
caf_audio_format.mChannelsPerFrame, caf_audio_format.mBitsPerChannel);
}
if (strncmp (caf_audio_format.mFormatID, "lpcm", 4) || (caf_audio_format.mFormatFlags & ~3))
supported = FALSE;
else if (caf_audio_format.mSampleRate < 1.0 || caf_audio_format.mSampleRate > 16777215.0 ||
caf_audio_format.mSampleRate != floor (caf_audio_format.mSampleRate))
supported = FALSE;
else if (!caf_audio_format.mChannelsPerFrame || caf_audio_format.mChannelsPerFrame > 256)
supported = FALSE;
else if (caf_audio_format.mBitsPerChannel < 1 || caf_audio_format.mBitsPerChannel > 32 ||
((caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) && caf_audio_format.mBitsPerChannel != 32))
supported = FALSE;
else if (caf_audio_format.mFramesPerPacket != 1 ||
caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame < (caf_audio_format.mBitsPerChannel + 7) / 8 ||
caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame > 4 ||
caf_audio_format.mBytesPerPacket % caf_audio_format.mChannelsPerFrame)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .CAF format!", infilename);
return WAVPACK_SOFT_ERROR;
}
config->bytes_per_sample = caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame;
config->float_norm_exp = (caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) ? 127 : 0;
config->bits_per_sample = caf_audio_format.mBitsPerChannel;
config->num_channels = caf_audio_format.mChannelsPerFrame;
config->sample_rate = (int) caf_audio_format.mSampleRate;
if (!(caf_audio_format.mFormatFlags & CAF_FORMAT_LITTLE_ENDIAN) && config->bytes_per_sample > 1)
config->qmode |= QMODE_BIG_ENDIAN;
if (config->bytes_per_sample == 1)
config->qmode |= QMODE_SIGNED_BYTES;
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: 32-bit %s-endian floating point", (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little");
else
error_line ("data format: %d-bit %s-endian integers stored in %d byte(s)",
config->bits_per_sample, (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little", config->bytes_per_sample);
}
}
else if (!strncmp (caf_chunk_header.mChunkType, "chan", 4)) {
CAFChannelLayout *caf_channel_layout;
if (caf_chunk_header.mChunkSize < 0 || caf_chunk_header.mChunkSize > 1024 ||
caf_chunk_header.mChunkSize < sizeof (CAFChannelLayout)) {
error_line ("this .CAF file has an invalid 'chan' chunk!");
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("'chan' chunk is %d bytes", (int) caf_chunk_header.mChunkSize);
caf_channel_layout = malloc ((size_t) caf_chunk_header.mChunkSize);
if (!DoReadFile (infile, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize, &bcount) ||
bcount != caf_chunk_header.mChunkSize) {
error_line ("%s is not a valid .CAF file!", infilename);
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (caf_channel_layout, CAFChannelLayoutFormat);
chan_chunk = 1;
if (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED)) {
error_line ("this CAF file already has channel order information!");
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
switch (caf_channel_layout->mChannelLayoutTag) {
case kCAFChannelLayoutTag_UseChannelDescriptions:
{
CAFChannelDescription *descriptions = (CAFChannelDescription *) (caf_channel_layout + 1);
int num_descriptions = caf_channel_layout->mNumberChannelDescriptions;
int label, cindex = 0, idents = 0;
if (caf_chunk_header.mChunkSize != sizeof (CAFChannelLayout) + sizeof (CAFChannelDescription) * num_descriptions ||
num_descriptions != config->num_channels) {
error_line ("channel descriptions in 'chan' chunk are the wrong size!");
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
if (num_descriptions >= 256) {
error_line ("%d channel descriptions is more than we can handle...ignoring!");
break;
}
// we allocate (and initialize to invalid values) a channel reorder array
// (even though we might not end up doing any reordering) and a string for
// any non-Microsoft channels we encounter
channel_reorder = malloc (num_descriptions);
memset (channel_reorder, -1, num_descriptions);
channel_identities = malloc (num_descriptions+1);
// convert the descriptions array to our native endian so it's easy to access
for (i = 0; i < num_descriptions; ++i) {
WavpackBigEndianToNative (descriptions + i, CAFChannelDescriptionFormat);
if (debug_logging_mode)
error_line ("chan %d --> %d", i + 1, descriptions [i].mChannelLabel);
}
// first, we go though and find any MS channels present, and move those to the beginning
for (label = 1; label <= 18; ++label)
for (i = 0; i < num_descriptions; ++i)
if (descriptions [i].mChannelLabel == label) {
config->channel_mask |= 1 << (label - 1);
channel_reorder [i] = cindex++;
break;
}
// next, we go though the channels again assigning any we haven't done
for (i = 0; i < num_descriptions; ++i)
if (channel_reorder [i] == (unsigned char) -1) {
uint32_t clabel = descriptions [i].mChannelLabel;
if (clabel == 0 || clabel == 0xffffffff || clabel == 100)
channel_identities [idents++] = 0xff;
else if ((clabel >= 33 && clabel <= 44) || (clabel >= 200 && clabel <= 207) || (clabel >= 301 && clabel <= 305))
channel_identities [idents++] = clabel >= 301 ? clabel - 80 : clabel;
else {
error_line ("warning: unknown channel descriptions label: %d", clabel);
channel_identities [idents++] = 0xff;
}
channel_reorder [i] = cindex++;
}
// then, go through the reordering array and see if we really have to reorder
for (i = 0; i < num_descriptions; ++i)
if (channel_reorder [i] != i)
break;
if (i == num_descriptions) {
free (channel_reorder); // no reordering required, so don't
channel_reorder = NULL;
}
else {
config->qmode |= QMODE_REORDERED_CHANS; // reordering required, put channel count into layout
channel_layout = num_descriptions;
}
if (!idents) { // if no non-MS channels, free the identities string
free (channel_identities);
channel_identities = NULL;
}
else
channel_identities [idents] = 0; // otherwise NULL terminate it
if (debug_logging_mode) {
error_line ("layout_tag = 0x%08x, so generated bitmap of 0x%08x from %d descriptions, %d non-MS",
caf_channel_layout->mChannelLayoutTag, config->channel_mask,
caf_channel_layout->mNumberChannelDescriptions, idents);
// if debugging, display the reordering as a string (but only little ones)
if (channel_reorder && num_descriptions <= 8) {
char reorder_string [] = "12345678";
for (i = 0; i < num_descriptions; ++i)
reorder_string [i] = channel_reorder [i] + '1';
reorder_string [i] = 0;
error_line ("reordering string = \"%s\"\n", reorder_string);
}
}
}
break;
case kCAFChannelLayoutTag_UseChannelBitmap:
config->channel_mask = caf_channel_layout->mChannelBitmap;
if (debug_logging_mode)
error_line ("layout_tag = 0x%08x, so using supplied bitmap of 0x%08x",
caf_channel_layout->mChannelLayoutTag, caf_channel_layout->mChannelBitmap);
break;
default:
for (i = 0; i < NUM_LAYOUTS; ++i)
if (caf_channel_layout->mChannelLayoutTag == layouts [i].mChannelLayoutTag) {
config->channel_mask = layouts [i].mChannelBitmap;
channel_layout = layouts [i].mChannelLayoutTag;
if (layouts [i].mChannelReorder) {
channel_reorder = (unsigned char *) strdup (layouts [i].mChannelReorder);
config->qmode |= QMODE_REORDERED_CHANS;
}
if (layouts [i].mChannelIdentities)
channel_identities = (unsigned char *) strdup (layouts [i].mChannelIdentities);
if (debug_logging_mode)
error_line ("layout_tag 0x%08x found in table, bitmap = 0x%08x, reorder = %s, identities = %s",
channel_layout, config->channel_mask, channel_reorder ? "yes" : "no", channel_identities ? "yes" : "no");
break;
}
if (i == NUM_LAYOUTS && debug_logging_mode)
error_line ("layout_tag 0x%08x not found in table...all channels unassigned",
caf_channel_layout->mChannelLayoutTag);
break;
}
free (caf_channel_layout);
}
else if (!strncmp (caf_chunk_header.mChunkType, "data", 4)) { // on the data chunk, get size and exit loop
uint32_t mEditCount;
if (!DoReadFile (infile, &mEditCount, sizeof (mEditCount), &bcount) ||
bcount != sizeof (mEditCount)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &mEditCount, sizeof (mEditCount))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
if ((config->qmode & QMODE_IGNORE_LENGTH) || caf_chunk_header.mChunkSize == -1) {
config->qmode |= QMODE_IGNORE_LENGTH;
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / caf_audio_format.mBytesPerPacket;
else
total_samples = -1;
}
else {
if (infilesize && infilesize - caf_chunk_header.mChunkSize > 16777216) {
error_line (".CAF file %s has over 16 MB of extra CAFF data, probably is corrupt!", infilename);
return WAVPACK_SOFT_ERROR;
}
if ((caf_chunk_header.mChunkSize - 4) % caf_audio_format.mBytesPerPacket) {
error_line (".CAF file %s has an invalid data chunk size, probably is corrupt!", infilename);
return WAVPACK_SOFT_ERROR;
}
total_samples = (caf_chunk_header.mChunkSize - 4) / caf_audio_format.mBytesPerPacket;
if (!total_samples) {
error_line ("this .CAF file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
break;
}
else { // just copy unknown chunks to output file
uint32_t bytes_to_copy = (uint32_t) caf_chunk_header.mChunkSize;
char *buff;
if (caf_chunk_header.mChunkSize < 0 || caf_chunk_header.mChunkSize > 1048576) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
caf_chunk_header.mChunkType [0], caf_chunk_header.mChunkType [1], caf_chunk_header.mChunkType [2],
caf_chunk_header.mChunkType [3], caf_chunk_header.mChunkSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!chan_chunk && !config->channel_mask && config->num_channels <= 2 && !(config->qmode & QMODE_CHANS_UNASSIGNED))
config->channel_mask = 0x5 - config->num_channels;
if (!WavpackSetConfiguration64 (wpc, config, total_samples, channel_identities)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
if (channel_identities)
free (channel_identities);
if (channel_layout || channel_reorder) {
if (!WavpackSetChannelLayout (wpc, channel_layout, channel_reorder)) {
error_line ("problem with setting channel layout (should not happen)");
return WAVPACK_SOFT_ERROR;
}
if (channel_reorder)
free (channel_reorder);
}
return WAVPACK_NO_ERROR;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-665', 'CWE-908'], 'message': 'issue #66: make sure CAF files have a "desc" chunk'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: asn1_get_integer(
unsigned char **buffer, /* IO - Pointer in buffer */
unsigned char *bufend, /* I - End of buffer */
unsigned length) /* I - Length of value */
{
int value; /* Integer value */
if (length > sizeof(int))
{
(*buffer) += length;
return (0);
}
for (value = (**buffer & 0x80) ? -1 : 0;
length > 0 && *buffer < bufend;
length --, (*buffer) ++)
value = (value << 8) | **buffer;
return (value);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120'], 'message': 'Fix multiple security/disclosure issues:
- CVE-2019-8696 and CVE-2019-8675: Fixed SNMP buffer overflows (rdar://51685251)
- Fixed IPP buffer overflow (rdar://50035411)
- Fixed memory disclosure issue in the scheduler (rdar://51373853)
- Fixed DoS issues in the scheduler (rdar://51373929)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: asn1_get_oid(
unsigned char **buffer, /* IO - Pointer in buffer */
unsigned char *bufend, /* I - End of buffer */
unsigned length, /* I - Length of value */
int *oid, /* I - OID buffer */
int oidsize) /* I - Size of OID buffer */
{
unsigned char *valend; /* End of value */
int *oidptr, /* Current OID */
*oidend; /* End of OID buffer */
int number; /* OID number */
valend = *buffer + length;
oidptr = oid;
oidend = oid + oidsize - 1;
if (valend > bufend)
valend = bufend;
number = asn1_get_packed(buffer, bufend);
if (number < 80)
{
*oidptr++ = number / 40;
number = number % 40;
*oidptr++ = number;
}
else
{
*oidptr++ = 2;
number -= 80;
*oidptr++ = number;
}
while (*buffer < valend)
{
number = asn1_get_packed(buffer, bufend);
if (oidptr < oidend)
*oidptr++ = number;
}
*oidptr = -1;
return ((int)(oidptr - oid));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120'], 'message': 'Fix multiple security/disclosure issues:
- CVE-2019-8696 and CVE-2019-8675: Fixed SNMP buffer overflows (rdar://51685251)
- Fixed IPP buffer overflow (rdar://50035411)
- Fixed memory disclosure issue in the scheduler (rdar://51373853)
- Fixed DoS issues in the scheduler (rdar://51373929)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: asn1_get_string(
unsigned char **buffer, /* IO - Pointer in buffer */
unsigned char *bufend, /* I - End of buffer */
unsigned length, /* I - Value length */
char *string, /* I - String buffer */
size_t strsize) /* I - String buffer size */
{
if (length > (unsigned)(bufend - *buffer))
length = (unsigned)(bufend - *buffer);
if (length < strsize)
{
/*
* String is smaller than the buffer...
*/
if (length > 0)
memcpy(string, *buffer, length);
string[length] = '\0';
}
else
{
/*
* String is larger than the buffer...
*/
memcpy(string, *buffer, strsize - 1);
string[strsize - 1] = '\0';
}
if (length > 0)
(*buffer) += length;
return (string);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120'], 'message': 'Fix multiple security/disclosure issues:
- CVE-2019-8696 and CVE-2019-8675: Fixed SNMP buffer overflows (rdar://51685251)
- Fixed IPP buffer overflow (rdar://50035411)
- Fixed memory disclosure issue in the scheduler (rdar://51373853)
- Fixed DoS issues in the scheduler (rdar://51373929)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ippSetValueTag(
ipp_t *ipp, /* I - IPP message */
ipp_attribute_t **attr, /* IO - IPP attribute */
ipp_tag_t value_tag) /* I - Value tag */
{
int i; /* Looping var */
_ipp_value_t *value; /* Current value */
int integer; /* Current integer value */
cups_lang_t *language; /* Current language */
char code[32]; /* Language code */
ipp_tag_t temp_tag; /* Temporary value tag */
/*
* Range check input...
*/
if (!ipp || !attr || !*attr)
return (0);
/*
* If there is no change, return immediately...
*/
if (value_tag == (*attr)->value_tag)
return (1);
/*
* Otherwise implement changes as needed...
*/
temp_tag = (ipp_tag_t)((int)((*attr)->value_tag) & IPP_TAG_CUPS_MASK);
switch (value_tag)
{
case IPP_TAG_UNSUPPORTED_VALUE :
case IPP_TAG_DEFAULT :
case IPP_TAG_UNKNOWN :
case IPP_TAG_NOVALUE :
case IPP_TAG_NOTSETTABLE :
case IPP_TAG_DELETEATTR :
case IPP_TAG_ADMINDEFINE :
/*
* Free any existing values...
*/
if ((*attr)->num_values > 0)
ipp_free_values(*attr, 0, (*attr)->num_values);
/*
* Set out-of-band value...
*/
(*attr)->value_tag = value_tag;
break;
case IPP_TAG_RANGE :
if (temp_tag != IPP_TAG_INTEGER)
return (0);
for (i = (*attr)->num_values, value = (*attr)->values;
i > 0;
i --, value ++)
{
integer = value->integer;
value->range.lower = value->range.upper = integer;
}
(*attr)->value_tag = IPP_TAG_RANGE;
break;
case IPP_TAG_NAME :
if (temp_tag != IPP_TAG_KEYWORD && temp_tag != IPP_TAG_URI &&
temp_tag != IPP_TAG_URISCHEME && temp_tag != IPP_TAG_LANGUAGE &&
temp_tag != IPP_TAG_MIMETYPE)
return (0);
(*attr)->value_tag = (ipp_tag_t)(IPP_TAG_NAME | ((*attr)->value_tag & IPP_TAG_CUPS_CONST));
break;
case IPP_TAG_NAMELANG :
case IPP_TAG_TEXTLANG :
if (value_tag == IPP_TAG_NAMELANG &&
(temp_tag != IPP_TAG_NAME && temp_tag != IPP_TAG_KEYWORD &&
temp_tag != IPP_TAG_URI && temp_tag != IPP_TAG_URISCHEME &&
temp_tag != IPP_TAG_LANGUAGE && temp_tag != IPP_TAG_MIMETYPE))
return (0);
if (value_tag == IPP_TAG_TEXTLANG && temp_tag != IPP_TAG_TEXT)
return (0);
if (ipp->attrs && ipp->attrs->next && ipp->attrs->next->name &&
!strcmp(ipp->attrs->next->name, "attributes-natural-language"))
{
/*
* Use the language code from the IPP message...
*/
(*attr)->values[0].string.language =
_cupsStrAlloc(ipp->attrs->next->values[0].string.text);
}
else
{
/*
* Otherwise, use the language code corresponding to the locale...
*/
language = cupsLangDefault();
(*attr)->values[0].string.language = _cupsStrAlloc(ipp_lang_code(language->language,
code,
sizeof(code)));
}
for (i = (*attr)->num_values - 1, value = (*attr)->values + 1;
i > 0;
i --, value ++)
value->string.language = (*attr)->values[0].string.language;
if ((int)(*attr)->value_tag & IPP_TAG_CUPS_CONST)
{
/*
* Make copies of all values...
*/
for (i = (*attr)->num_values, value = (*attr)->values;
i > 0;
i --, value ++)
value->string.text = _cupsStrAlloc(value->string.text);
}
(*attr)->value_tag = IPP_TAG_NAMELANG;
break;
case IPP_TAG_KEYWORD :
if (temp_tag == IPP_TAG_NAME || temp_tag == IPP_TAG_NAMELANG)
break; /* Silently "allow" name -> keyword */
default :
return (0);
}
return (1);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120'], 'message': 'Fix multiple security/disclosure issues:
- CVE-2019-8696 and CVE-2019-8675: Fixed SNMP buffer overflows (rdar://51685251)
- Fixed IPP buffer overflow (rdar://50035411)
- Fixed memory disclosure issue in the scheduler (rdar://51373853)
- Fixed DoS issues in the scheduler (rdar://51373929)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cupsdSendError(cupsd_client_t *con, /* I - Connection */
http_status_t code, /* I - Error code */
int auth_type)/* I - Authentication type */
{
char location[HTTP_MAX_VALUE]; /* Location field */
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cupsdSendError code=%d, auth_type=%d", code, auth_type);
#ifdef HAVE_SSL
/*
* Force client to upgrade for authentication if that is how the
* server is configured...
*/
if (code == HTTP_STATUS_UNAUTHORIZED &&
DefaultEncryption == HTTP_ENCRYPTION_REQUIRED &&
_cups_strcasecmp(httpGetHostname(con->http, NULL, 0), "localhost") &&
!httpIsEncrypted(con->http))
{
code = HTTP_STATUS_UPGRADE_REQUIRED;
}
#endif /* HAVE_SSL */
/*
* Put the request in the access_log file...
*/
cupsdLogRequest(con, code);
/*
* To work around bugs in some proxies, don't use Keep-Alive for some
* error messages...
*
* Kerberos authentication doesn't work without Keep-Alive, so
* never disable it in that case.
*/
strlcpy(location, httpGetField(con->http, HTTP_FIELD_LOCATION), sizeof(location));
httpClearFields(con->http);
httpSetField(con->http, HTTP_FIELD_LOCATION, location);
if (code >= HTTP_STATUS_BAD_REQUEST && con->type != CUPSD_AUTH_NEGOTIATE)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
if (httpGetVersion(con->http) >= HTTP_VERSION_1_1 &&
httpGetKeepAlive(con->http) == HTTP_KEEPALIVE_OFF)
httpSetField(con->http, HTTP_FIELD_CONNECTION, "close");
if (code >= HTTP_STATUS_BAD_REQUEST)
{
/*
* Send a human-readable error message.
*/
char message[4096], /* Message for user */
urltext[1024], /* URL redirection text */
redirect[1024]; /* Redirection link */
const char *text; /* Status-specific text */
redirect[0] = '\0';
if (code == HTTP_STATUS_UNAUTHORIZED)
text = _cupsLangString(con->language,
_("Enter your username and password or the "
"root username and password to access this "
"page. If you are using Kerberos authentication, "
"make sure you have a valid Kerberos ticket."));
else if (code == HTTP_STATUS_UPGRADE_REQUIRED)
{
text = urltext;
snprintf(urltext, sizeof(urltext),
_cupsLangString(con->language,
_("You must access this page using the URL "
"<A HREF=\"https://%s:%d%s\">"
"https://%s:%d%s</A>.")),
con->servername, con->serverport, con->uri,
con->servername, con->serverport, con->uri);
snprintf(redirect, sizeof(redirect),
"<META HTTP-EQUIV=\"Refresh\" "
"CONTENT=\"3;URL=https://%s:%d%s\">\n",
con->servername, con->serverport, con->uri);
}
else if (code == HTTP_STATUS_CUPS_WEBIF_DISABLED)
text = _cupsLangString(con->language,
_("The web interface is currently disabled. Run "
"\"cupsctl WebInterface=yes\" to enable it."));
else
text = "";
snprintf(message, sizeof(message),
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
"\"http://www.w3.org/TR/html4/loose.dtd\">\n"
"<HTML>\n"
"<HEAD>\n"
"\t<META HTTP-EQUIV=\"Content-Type\" "
"CONTENT=\"text/html; charset=utf-8\">\n"
"\t<TITLE>%s - " CUPS_SVERSION "</TITLE>\n"
"\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
"HREF=\"/cups.css\">\n"
"%s"
"</HEAD>\n"
"<BODY>\n"
"<H1>%s</H1>\n"
"<P>%s</P>\n"
"</BODY>\n"
"</HTML>\n",
_httpStatus(con->language, code), redirect,
_httpStatus(con->language, code), text);
/*
* Send an error message back to the client. If the error code is a
* 400 or 500 series, make sure the message contains some text, too!
*/
size_t length = strlen(message); /* Length of message */
httpSetLength(con->http, length);
if (!cupsdSendHeader(con, code, "text/html", auth_type))
return (0);
if (httpWrite2(con->http, message, length) < 0)
return (0);
if (httpFlushWrite(con->http) < 0)
return (0);
}
else
{
httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
if (!cupsdSendHeader(con, code, NULL, auth_type))
return (0);
}
return (1);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-120'], 'message': 'Fix multiple security/disclosure issues:
- CVE-2019-8696 and CVE-2019-8675: Fixed SNMP buffer overflows (rdar://51685251)
- Fixed IPP buffer overflow (rdar://50035411)
- Fixed memory disclosure issue in the scheduler (rdar://51373853)
- Fixed DoS issues in the scheduler (rdar://51373929)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int blk_init_allocated_queue(struct request_queue *q)
{
WARN_ON_ONCE(q->mq_ops);
q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, q->cmd_size);
if (!q->fq)
return -ENOMEM;
if (q->init_rq_fn && q->init_rq_fn(q, q->fq->flush_rq, GFP_KERNEL))
goto out_free_flush_queue;
if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
goto out_exit_flush_rq;
INIT_WORK(&q->timeout_work, blk_timeout_work);
q->queue_flags |= QUEUE_FLAG_DEFAULT;
/*
* This also sets hw/phys segments, boundary and size
*/
blk_queue_make_request(q, blk_queue_bio);
q->sg_reserved_size = INT_MAX;
if (elevator_init(q))
goto out_exit_flush_rq;
return 0;
out_exit_flush_rq:
if (q->exit_rq_fn)
q->exit_rq_fn(q, q->fq->flush_rq);
out_free_flush_queue:
blk_free_flush_queue(q->fq);
return -ENOMEM;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-703'], 'message': 'block: blk_init_allocated_queue() set q->fq as NULL in the fail case
We find the memory use-after-free issue in __blk_drain_queue()
on the kernel 4.14. After read the latest kernel 4.18-rc6 we
think it has the same problem.
Memory is allocated for q->fq in the blk_init_allocated_queue().
If the elevator init function called with error return, it will
run into the fail case to free the q->fq.
Then the __blk_drain_queue() uses the same memory after the free
of the q->fq, it will lead to the unpredictable event.
The patch is to set q->fq as NULL in the fail case of
blk_init_allocated_queue().
Fixes: commit 7c94e1c157a2 ("block: introduce blk_flush_queue to drive flush machinery")
Cc: <[email protected]>
Reviewed-by: Ming Lei <[email protected]>
Reviewed-by: Bart Van Assche <[email protected]>
Signed-off-by: xiao jin <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int serdes_probe(struct platform_device *pdev)
{
struct phy_provider *provider;
struct serdes_ctrl *ctrl;
unsigned int i;
int ret;
ctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL);
if (!ctrl)
return -ENOMEM;
ctrl->dev = &pdev->dev;
ctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node);
if (IS_ERR(ctrl->regs))
return PTR_ERR(ctrl->regs);
for (i = 0; i <= SERDES_MAX; i++) {
ret = serdes_phy_create(ctrl, i, &ctrl->phys[i]);
if (ret)
return ret;
}
dev_set_drvdata(&pdev->dev, ctrl);
provider = devm_of_phy_provider_register(ctrl->dev,
serdes_simple_xlate);
return PTR_ERR_OR_ZERO(provider);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'phy: ocelot-serdes: fix out-of-bounds read
Currently, there is an out-of-bounds read on array ctrl->phys,
once variable i reaches the maximum array size of SERDES_MAX
in the for loop.
Fix this by changing the condition in the for loop from
i <= SERDES_MAX to i < SERDES_MAX.
Addresses-Coverity-ID: 1473966 ("Out-of-bounds read")
Addresses-Coverity-ID: 1473959 ("Out-of-bounds read")
Fixes: 51f6b410fc22 ("phy: add driver for Microsemi Ocelot SerDes muxing")
Reviewed-by: Quentin Schulz <[email protected]>
Signed-off-by: Gustavo A. R. Silva <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int exif_scan_thumbnail(image_info_type *ImageInfo)
{
uchar c, *data = (uchar*)ImageInfo->Thumbnail.data;
int n, marker;
size_t length=2, pos=0;
jpeg_sof_info sof_info;
if (!data) {
return FALSE; /* nothing to do here */
}
if (memcmp(data, "\xFF\xD8\xFF", 3)) {
if (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) {
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Thumbnail is not a JPEG image");
}
return FALSE;
}
for (;;) {
pos += length;
if (pos>=ImageInfo->Thumbnail.size)
return FALSE;
c = data[pos++];
if (pos>=ImageInfo->Thumbnail.size)
return FALSE;
if (c != 0xFF) {
return FALSE;
}
n = 8;
while ((c = data[pos++]) == 0xFF && n--) {
if (pos+3>=ImageInfo->Thumbnail.size)
return FALSE;
/* +3 = pos++ of next check when reaching marker + 2 bytes for length */
}
if (c == 0xFF)
return FALSE;
marker = c;
if (pos>=ImageInfo->Thumbnail.size)
return FALSE;
length = php_jpg_get16(data+pos);
if (length > ImageInfo->Thumbnail.size || pos >= ImageInfo->Thumbnail.size - length) {
return FALSE;
}
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: process section(x%02X=%s) @ x%04X + x%04X", marker, exif_get_markername(marker), pos, length);
#endif
switch (marker) {
case M_SOF0:
case M_SOF1:
case M_SOF2:
case M_SOF3:
case M_SOF5:
case M_SOF6:
case M_SOF7:
case M_SOF9:
case M_SOF10:
case M_SOF11:
case M_SOF13:
case M_SOF14:
case M_SOF15:
/* handle SOFn block */
if (length < 8 || ImageInfo->Thumbnail.size - 8 < pos) {
/* exif_process_SOFn needs 8 bytes */
return FALSE;
}
exif_process_SOFn(data+pos, marker, &sof_info);
ImageInfo->Thumbnail.height = sof_info.height;
ImageInfo->Thumbnail.width = sof_info.width;
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: size: %d * %d", sof_info.width, sof_info.height);
#endif
return TRUE;
case M_SOS:
case M_EOI:
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Could not compute size of thumbnail");
return FALSE;
break;
default:
/* just skip */
break;
}
}
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Could not compute size of thumbnail");
return FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #78222 (heap-buffer-overflow on exif_scan_thumbnail)
(cherry picked from commit dea2989ab8ba87a6180af497b2efaf0527e985c5)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: managesieve_parser_read_string(struct managesieve_parser *parser,
const unsigned char *data, size_t data_size)
{
size_t i;
/* QUOTED-CHAR = SAFE-UTF8-CHAR / "\" QUOTED-SPECIALS
* quoted = <"> *QUOTED-CHAR <">
* ;; limited to 1024 octets between the <">s
*/
/* read until we've found non-escaped ", CR or LF */
for (i = parser->cur_pos; i < data_size; i++) {
if (data[i] == '"') {
if ( !uni_utf8_data_is_valid(data+1, i-1) ) {
parser->error = "Invalid UTF-8 character in quoted-string.";
return FALSE;
}
managesieve_parser_save_arg(parser, data, i);
i++; /* skip the trailing '"' too */
break;
}
if (data[i] == '\\') {
if (i+1 == data_size) {
/* known data ends with '\' - leave it to
next time as well if it happens to be \" */
break;
}
/* save the first escaped char */
if (parser->str_first_escape < 0)
parser->str_first_escape = i;
/* skip the escaped char */
i++;
if ( !IS_QUOTED_SPECIAL(data[i]) ) {
parser->error =
"Escaped quoted-string character is not a QUOTED-SPECIAL.";
return FALSE;
}
continue;
}
if ( (data[i] & 0x80) == 0 && !IS_SAFE_CHAR(data[i]) ) {
parser->error = "String contains invalid character.";
return FALSE;
}
}
parser->cur_pos = i;
return ( parser->cur_type == ARG_PARSE_NONE );
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'lib-managesieve: Don't accept strings with NULs
ManageSieve doesn't allow NULs in strings.
This fixes a bug with unescaping a string with NULs: str_unescape() could
have been called for memory that points outside the allocated string,
causing heap corruption. This could cause crashes or theoretically even
result in remote code execution exploit.
Found by Nick Roessler and Rafi Rubin'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static h2_stream *get_latest_repeatable_unsubmitted_stream(h2_mplx *m)
{
stream_iter_ctx ctx;
ctx.m = m;
ctx.stream = NULL;
h2_ihash_iter(m->streams, latest_repeatable_unsubmitted_iter, &ctx);
return ctx.stream;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: apr_status_t h2_stream_add_header(h2_stream *stream,
const char *name, size_t nlen,
const char *value, size_t vlen)
{
h2_session *session = stream->session;
int error = 0;
apr_status_t status;
if (stream->has_response) {
return APR_EINVAL;
}
++stream->request_headers_added;
if (name[0] == ':') {
if ((vlen) > session->s->limit_req_line) {
/* pseudo header: approximation of request line size check */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, session->c,
H2_STRM_MSG(stream, "pseudo %s too long"), name);
error = HTTP_REQUEST_URI_TOO_LARGE;
}
}
else if ((nlen + 2 + vlen) > session->s->limit_req_fieldsize) {
/* header too long */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, session->c,
H2_STRM_MSG(stream, "header %s too long"), name);
error = HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE;
}
if (stream->request_headers_added > session->s->limit_req_fields + 4) {
/* too many header lines, include 4 pseudo headers */
if (stream->request_headers_added
> session->s->limit_req_fields + 4 + 100) {
/* yeah, right */
h2_stream_rst(stream, H2_ERR_ENHANCE_YOUR_CALM);
return APR_ECONNRESET;
}
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, session->c,
H2_STRM_MSG(stream, "too many header lines"));
error = HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE;
}
if (error) {
set_error_response(stream, error);
return APR_EINVAL;
}
else if (H2_SS_IDLE == stream->state) {
if (!stream->rtmp) {
stream->rtmp = h2_req_create(stream->id, stream->pool,
NULL, NULL, NULL, NULL, NULL, 0);
}
status = h2_request_add_header(stream->rtmp, stream->pool,
name, nlen, value, vlen);
}
else if (H2_SS_OPEN == stream->state) {
status = add_trailer(stream, name, nlen, value, vlen);
}
else {
status = APR_EINVAL;
}
if (status != APR_SUCCESS) {
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, session->c,
H2_STRM_MSG(stream, "header %s not accepted"), name);
h2_stream_dispatch(stream, H2_SEV_CANCELLED);
}
return status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: apr_status_t h2_session_process(h2_session *session, int async)
{
apr_status_t status = APR_SUCCESS;
conn_rec *c = session->c;
int rv, mpm_state, trace = APLOGctrace3(c);
apr_time_t now;
if (trace) {
ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c,
H2_SSSN_MSG(session, "process start, async=%d"), async);
}
while (session->state != H2_SESSION_ST_DONE) {
now = apr_time_now();
session->have_read = session->have_written = 0;
if (session->local.accepting
&& !ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state)) {
if (mpm_state == AP_MPMQ_STOPPING) {
dispatch_event(session, H2_SESSION_EV_MPM_STOPPING, 0, NULL);
}
}
session->status[0] = '\0';
switch (session->state) {
case H2_SESSION_ST_INIT:
ap_update_child_status_from_conn(c->sbh, SERVER_BUSY_READ, c);
if (!h2_is_acceptable_connection(c, session->r, 1)) {
update_child_status(session, SERVER_BUSY_READ,
"inadequate security");
h2_session_shutdown(session,
NGHTTP2_INADEQUATE_SECURITY, NULL, 1);
}
else {
update_child_status(session, SERVER_BUSY_READ, "init");
status = h2_session_start(session, &rv);
ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, c,
H2_SSSN_LOG(APLOGNO(03079), session,
"started on %s:%d"),
session->s->server_hostname,
c->local_addr->port);
if (status != APR_SUCCESS) {
dispatch_event(session,
H2_SESSION_EV_CONN_ERROR, 0, NULL);
}
dispatch_event(session, H2_SESSION_EV_INIT, 0, NULL);
}
break;
case H2_SESSION_ST_IDLE:
if (session->idle_until && (apr_time_now() + session->idle_delay) > session->idle_until) {
ap_log_cerror( APLOG_MARK, APLOG_TRACE1, status, c,
H2_SSSN_MSG(session, "idle, timeout reached, closing"));
if (session->idle_delay) {
apr_table_setn(session->c->notes, "short-lingering-close", "1");
}
dispatch_event(session, H2_SESSION_EV_CONN_TIMEOUT, 0, "timeout");
goto out;
}
if (session->idle_delay) {
/* we are less interested in spending time on this connection */
ap_log_cerror( APLOG_MARK, APLOG_TRACE2, status, c,
H2_SSSN_MSG(session, "session is idle (%ld ms), idle wait %ld sec left"),
(long)apr_time_as_msec(session->idle_delay),
(long)apr_time_sec(session->idle_until - now));
apr_sleep(session->idle_delay);
session->idle_delay = 0;
}
h2_conn_io_flush(&session->io);
if (async && !session->r && (now > session->idle_sync_until)) {
if (trace) {
ap_log_cerror(APLOG_MARK, APLOG_TRACE3, status, c,
H2_SSSN_MSG(session,
"nonblock read, %d streams open"),
session->open_streams);
}
status = h2_session_read(session, 0);
if (status == APR_SUCCESS) {
session->have_read = 1;
}
else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) {
status = APR_EAGAIN;
goto out;
}
else {
ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, c,
H2_SSSN_LOG(APLOGNO(03403), session,
"no data, error"));
dispatch_event(session,
H2_SESSION_EV_CONN_ERROR, 0, "timeout");
}
}
else {
/* make certain, we send everything before we idle */
if (trace) {
ap_log_cerror(APLOG_MARK, APLOG_TRACE3, status, c,
H2_SSSN_MSG(session,
"sync, stutter 1-sec, %d streams open"),
session->open_streams);
}
/* We wait in smaller increments, using a 1 second timeout.
* That gives us the chance to check for MPMQ_STOPPING often.
*/
status = h2_mplx_idle(session->mplx);
if (status == APR_EAGAIN) {
break;
}
else if (status != APR_SUCCESS) {
dispatch_event(session, H2_SESSION_EV_CONN_ERROR,
H2_ERR_ENHANCE_YOUR_CALM, "less is more");
}
h2_filter_cin_timeout_set(session->cin, apr_time_from_sec(1));
status = h2_session_read(session, 1);
if (status == APR_SUCCESS) {
session->have_read = 1;
}
else if (status == APR_EAGAIN) {
/* nothing to read */
}
else if (APR_STATUS_IS_TIMEUP(status)) {
/* continue reading handling */
}
else if (APR_STATUS_IS_ECONNABORTED(status)
|| APR_STATUS_IS_ECONNRESET(status)
|| APR_STATUS_IS_EOF(status)
|| APR_STATUS_IS_EBADF(status)) {
ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c,
H2_SSSN_MSG(session, "input gone"));
dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL);
}
else {
ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c,
H2_SSSN_MSG(session,
"(1 sec timeout) read failed"));
dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, "error");
}
}
if (nghttp2_session_want_write(session->ngh2)) {
ap_update_child_status(session->c->sbh, SERVER_BUSY_WRITE, NULL);
status = h2_session_send(session);
if (status == APR_SUCCESS) {
status = h2_conn_io_flush(&session->io);
}
if (status != APR_SUCCESS) {
dispatch_event(session, H2_SESSION_EV_CONN_ERROR,
H2_ERR_INTERNAL_ERROR, "writing");
break;
}
}
break;
case H2_SESSION_ST_BUSY:
if (nghttp2_session_want_read(session->ngh2)) {
ap_update_child_status(session->c->sbh, SERVER_BUSY_READ, NULL);
h2_filter_cin_timeout_set(session->cin, session->s->timeout);
status = h2_session_read(session, 0);
if (status == APR_SUCCESS) {
session->have_read = 1;
}
else if (status == APR_EAGAIN) {
/* nothing to read */
}
else if (APR_STATUS_IS_TIMEUP(status)) {
dispatch_event(session, H2_SESSION_EV_CONN_TIMEOUT, 0, NULL);
break;
}
else {
dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL);
}
}
status = dispatch_master(session);
if (status != APR_SUCCESS && status != APR_EAGAIN) {
break;
}
if (nghttp2_session_want_write(session->ngh2)) {
ap_update_child_status(session->c->sbh, SERVER_BUSY_WRITE, NULL);
status = h2_session_send(session);
if (status == APR_SUCCESS) {
status = h2_conn_io_flush(&session->io);
}
if (status != APR_SUCCESS) {
dispatch_event(session, H2_SESSION_EV_CONN_ERROR,
H2_ERR_INTERNAL_ERROR, "writing");
break;
}
}
if (session->have_read || session->have_written) {
if (session->wait_us) {
session->wait_us = 0;
}
}
else if (!nghttp2_session_want_write(session->ngh2)) {
dispatch_event(session, H2_SESSION_EV_NO_IO, 0, NULL);
}
break;
case H2_SESSION_ST_WAIT:
if (session->wait_us <= 0) {
session->wait_us = 10;
if (h2_conn_io_flush(&session->io) != APR_SUCCESS) {
dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL);
break;
}
}
else {
/* repeating, increase timer for graceful backoff */
session->wait_us = H2MIN(session->wait_us*2, MAX_WAIT_MICROS);
}
if (trace) {
ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,
"h2_session: wait for data, %ld micros",
(long)session->wait_us);
}
status = h2_mplx_out_trywait(session->mplx, session->wait_us,
session->iowait);
if (status == APR_SUCCESS) {
session->wait_us = 0;
dispatch_event(session, H2_SESSION_EV_STREAM_CHANGE, 0, NULL);
}
else if (APR_STATUS_IS_TIMEUP(status)) {
/* go back to checking all inputs again */
transit(session, "wait cycle", session->local.shutdown?
H2_SESSION_ST_DONE : H2_SESSION_ST_BUSY);
}
else if (APR_STATUS_IS_ECONNRESET(status)
|| APR_STATUS_IS_ECONNABORTED(status)) {
dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL);
}
else {
ap_log_cerror(APLOG_MARK, APLOG_WARNING, status, c,
H2_SSSN_LOG(APLOGNO(03404), session,
"waiting on conditional"));
h2_session_shutdown(session, H2_ERR_INTERNAL_ERROR,
"cond wait error", 0);
}
break;
default:
ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, c,
H2_SSSN_LOG(APLOGNO(03080), session,
"unknown state"));
dispatch_event(session, H2_SESSION_EV_PROTO_ERROR, 0, NULL);
break;
}
if (!nghttp2_session_want_read(session->ngh2)
&& !nghttp2_session_want_write(session->ngh2)) {
dispatch_event(session, H2_SESSION_EV_NGH2_DONE, 0, NULL);
}
if (session->reprioritize) {
h2_mplx_reprioritize(session->mplx, stream_pri_cmp, session);
session->reprioritize = 0;
}
}
out:
if (trace) {
ap_log_cerror( APLOG_MARK, APLOG_TRACE3, status, c,
H2_SSSN_MSG(session, "process returns"));
}
if ((session->state != H2_SESSION_ST_DONE)
&& (APR_STATUS_IS_EOF(status)
|| APR_STATUS_IS_ECONNRESET(status)
|| APR_STATUS_IS_ECONNABORTED(status))) {
dispatch_event(session, H2_SESSION_EV_CONN_ERROR, 0, NULL);
}
return (session->state == H2_SESSION_ST_DONE)? APR_EOF : APR_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int h2_mplx_awaits_data(h2_mplx *m)
{
int waiting = 1;
H2_MPLX_ENTER_ALWAYS(m);
if (h2_ihash_empty(m->streams)) {
waiting = 0;
}
else if (!m->tasks_active && !h2_ififo_count(m->readyq)
&& h2_iq_empty(m->q)) {
waiting = 0;
}
H2_MPLX_LEAVE(m);
return waiting;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void stream_cleanup(h2_mplx *m, h2_stream *stream)
{
ap_assert(stream->state == H2_SS_CLEANUP);
if (stream->input) {
h2_beam_on_consumed(stream->input, NULL, NULL, NULL);
h2_beam_abort(stream->input);
}
if (stream->output) {
h2_beam_on_produced(stream->output, NULL, NULL);
h2_beam_leave(stream->output);
}
h2_stream_cleanup(stream);
h2_ihash_remove(m->streams, stream->id);
h2_iq_remove(m->q, stream->id);
h2_ififo_remove(m->readyq, stream->id);
h2_ihash_add(m->shold, stream);
if (!stream->task || stream->task->worker_done) {
stream_joined(m, stream);
}
else if (stream->task) {
stream->task->c->aborted = 1;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: apr_status_t h2_conn_run(conn_rec *c)
{
apr_status_t status;
int mpm_state = 0;
h2_session *session = h2_ctx_get_session(c);
ap_assert(session);
do {
if (c->cs) {
c->cs->sense = CONN_SENSE_DEFAULT;
c->cs->state = CONN_STATE_HANDLER;
}
status = h2_session_process(session, async_mpm);
if (APR_STATUS_IS_EOF(status)) {
ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, c,
H2_SSSN_LOG(APLOGNO(03045), session,
"process, closing conn"));
c->keepalive = AP_CONN_CLOSE;
}
else {
c->keepalive = AP_CONN_KEEPALIVE;
}
if (ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state)) {
break;
}
} while (!async_mpm
&& c->keepalive == AP_CONN_KEEPALIVE
&& mpm_state != AP_MPMQ_STOPPING);
if (c->cs) {
switch (session->state) {
case H2_SESSION_ST_INIT:
case H2_SESSION_ST_IDLE:
case H2_SESSION_ST_BUSY:
case H2_SESSION_ST_WAIT:
c->cs->state = CONN_STATE_WRITE_COMPLETION;
break;
case H2_SESSION_ST_CLEANUP:
case H2_SESSION_ST_DONE:
default:
c->cs->state = CONN_STATE_LINGER;
break;
}
}
return APR_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: apr_status_t h2_stream_recv_frame(h2_stream *stream, int ftype, int flags, size_t frame_len)
{
apr_status_t status = APR_SUCCESS;
int new_state, eos = 0;
new_state = on_frame_recv(stream->state, ftype);
if (new_state < 0) {
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
H2_STRM_MSG(stream, "invalid frame %d recv"), ftype);
AP_DEBUG_ASSERT(new_state > S_XXX);
return transit(stream, new_state);
}
switch (ftype) {
case NGHTTP2_DATA:
eos = (flags & NGHTTP2_FLAG_END_STREAM);
break;
case NGHTTP2_HEADERS:
eos = (flags & NGHTTP2_FLAG_END_STREAM);
if (stream->state == H2_SS_OPEN) {
/* trailer HEADER */
if (!eos) {
h2_stream_rst(stream, H2_ERR_PROTOCOL_ERROR);
}
stream->in_trailer_octets += frame_len;
}
else {
/* request HEADER */
ap_assert(stream->request == NULL);
if (stream->rtmp == NULL) {
/* This can only happen, if the stream has received no header
* name/value pairs at all. The lastest nghttp2 version have become
* pretty good at detecting this early. In any case, we have
* to abort the connection here, since this is clearly a protocol error */
return APR_EINVAL;
}
status = h2_request_end_headers(stream->rtmp, stream->pool, eos, frame_len);
if (status != APR_SUCCESS) {
return status;
}
set_policy_for(stream, stream->rtmp);
stream->request = stream->rtmp;
stream->rtmp = NULL;
}
break;
default:
break;
}
status = transit(stream, new_state);
if (status == APR_SUCCESS && eos) {
status = transit(stream, on_event(stream, H2_SEV_CLOSED_R));
}
return status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: apr_status_t h2_task_do(h2_task *task, apr_thread_t *thread, int worker_id)
{
conn_rec *c;
ap_assert(task);
c = task->c;
task->worker_started = 1;
task->started_at = apr_time_now();
if (c->master) {
/* Each conn_rec->id is supposed to be unique at a point in time. Since
* some modules (and maybe external code) uses this id as an identifier
* for the request_rec they handle, it needs to be unique for slave
* connections also.
* The connection id is generated by the MPM and most MPMs use the formula
* id := (child_num * max_threads) + thread_num
* which means that there is a maximum id of about
* idmax := max_child_count * max_threads
* If we assume 2024 child processes with 2048 threads max, we get
* idmax ~= 2024 * 2048 = 2 ** 22
* On 32 bit systems, we have not much space left, but on 64 bit systems
* (and higher?) we can use the upper 32 bits without fear of collision.
* 32 bits is just what we need, since a connection can only handle so
* many streams.
*/
int slave_id, free_bits;
task->id = apr_psprintf(task->pool, "%ld-%d", c->master->id,
task->stream_id);
if (sizeof(unsigned long) >= 8) {
free_bits = 32;
slave_id = task->stream_id;
}
else {
/* Assume we have a more limited number of threads/processes
* and h2 workers on a 32-bit system. Use the worker instead
* of the stream id. */
free_bits = 8;
slave_id = worker_id;
}
task->c->id = (c->master->id << free_bits)^slave_id;
}
h2_beam_create(&task->output.beam, c->pool, task->stream_id, "output",
H2_BEAM_OWNER_SEND, 0, task->timeout);
if (!task->output.beam) {
return APR_ENOMEM;
}
h2_beam_buffer_size_set(task->output.beam, task->output.max_buffer);
h2_beam_send_from(task->output.beam, task->pool);
h2_ctx_create_for(c, task);
apr_table_setn(c->notes, H2_TASK_ID_NOTE, task->id);
h2_slave_run_pre_connection(c, ap_get_conn_socket(c));
task->input.bb = apr_brigade_create(task->pool, c->bucket_alloc);
if (task->request->serialize) {
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c,
"h2_task(%s): serialize request %s %s",
task->id, task->request->method, task->request->path);
apr_brigade_printf(task->input.bb, NULL,
NULL, "%s %s HTTP/1.1\r\n",
task->request->method, task->request->path);
apr_table_do(input_ser_header, task, task->request->headers, NULL);
apr_brigade_puts(task->input.bb, NULL, NULL, "\r\n");
}
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c,
"h2_task(%s): process connection", task->id);
task->c->current_thread = thread;
ap_run_process_connection(c);
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c,
"h2_task(%s): processing done", task->id);
return output_finish(task);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static h2_stream *get_timed_out_busy_stream(h2_mplx *m)
{
stream_iter_ctx ctx;
ctx.m = m;
ctx.stream = NULL;
ctx.now = apr_time_now();
h2_ihash_iter(m->streams, timed_out_busy_iter, &ctx);
return ctx.stream;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,
mpm event backport to 2.4.x up for vote).
* Fixes stream cleanup when connection throttling is in place.
* Counts stream resets by client on streams initiated by client as cause
for connection throttling.
* Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)
* Header length is checked also on the merged value from several header instances
and results in a 431 response.'</s> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.